1 /*-------------------------------------------------------------------------
2  *
3  * pathnodes.h
4  *	  Definitions for planner's internal data structures, especially Paths.
5  *
6  *
7  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/nodes/pathnodes.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef PATHNODES_H
15 #define PATHNODES_H
16 
17 #include "access/sdir.h"
18 #include "fmgr.h"
19 #include "lib/stringinfo.h"
20 #include "nodes/params.h"
21 #include "nodes/parsenodes.h"
22 #include "storage/block.h"
23 
24 
25 /*
26  * Relids
27  *		Set of relation identifiers (indexes into the rangetable).
28  */
29 typedef Bitmapset *Relids;
30 
31 /*
32  * When looking for a "cheapest path", this enum specifies whether we want
33  * cheapest startup cost or cheapest total cost.
34  */
35 typedef enum CostSelector
36 {
37 	STARTUP_COST, TOTAL_COST
38 } CostSelector;
39 
40 /*
41  * The cost estimate produced by cost_qual_eval() includes both a one-time
42  * (startup) cost, and a per-tuple cost.
43  */
44 typedef struct QualCost
45 {
46 	Cost		startup;		/* one-time cost */
47 	Cost		per_tuple;		/* per-evaluation cost */
48 } QualCost;
49 
50 /*
51  * Costing aggregate function execution requires these statistics about
52  * the aggregates to be executed by a given Agg node.  Note that the costs
53  * include the execution costs of the aggregates' argument expressions as
54  * well as the aggregate functions themselves.  Also, the fields must be
55  * defined so that initializing the struct to zeroes with memset is correct.
56  */
57 typedef struct AggClauseCosts
58 {
59 	int			numAggs;		/* total number of aggregate functions */
60 	int			numOrderedAggs; /* number w/ DISTINCT/ORDER BY/WITHIN GROUP */
61 	bool		hasNonPartial;	/* does any agg not support partial mode? */
62 	bool		hasNonSerial;	/* is any partial agg non-serializable? */
63 	QualCost	transCost;		/* total per-input-row execution costs */
64 	QualCost	finalCost;		/* total per-aggregated-row costs */
65 	Size		transitionSpace;	/* space for pass-by-ref transition data */
66 } AggClauseCosts;
67 
68 /*
69  * This enum identifies the different types of "upper" (post-scan/join)
70  * relations that we might deal with during planning.
71  */
72 typedef enum UpperRelationKind
73 {
74 	UPPERREL_SETOP,				/* result of UNION/INTERSECT/EXCEPT, if any */
75 	UPPERREL_PARTIAL_GROUP_AGG, /* result of partial grouping/aggregation, if
76 								 * any */
77 	UPPERREL_GROUP_AGG,			/* result of grouping/aggregation, if any */
78 	UPPERREL_WINDOW,			/* result of window functions, if any */
79 	UPPERREL_DISTINCT,			/* result of "SELECT DISTINCT", if any */
80 	UPPERREL_ORDERED,			/* result of ORDER BY, if any */
81 	UPPERREL_FINAL				/* result of any remaining top-level actions */
82 	/* NB: UPPERREL_FINAL must be last enum entry; it's used to size arrays */
83 } UpperRelationKind;
84 
85 /*
86  * This enum identifies which type of relation is being planned through the
87  * inheritance planner.  INHKIND_NONE indicates the inheritance planner
88  * was not used.
89  */
90 typedef enum InheritanceKind
91 {
92 	INHKIND_NONE,
93 	INHKIND_INHERITED,
94 	INHKIND_PARTITIONED
95 } InheritanceKind;
96 
97 /*----------
98  * PlannerGlobal
99  *		Global information for planning/optimization
100  *
101  * PlannerGlobal holds state for an entire planner invocation; this state
102  * is shared across all levels of sub-Queries that exist in the command being
103  * planned.
104  *----------
105  */
106 typedef struct PlannerGlobal
107 {
108 	NodeTag		type;
109 
110 	ParamListInfo boundParams;	/* Param values provided to planner() */
111 
112 	List	   *subplans;		/* Plans for SubPlan nodes */
113 
114 	List	   *subroots;		/* PlannerInfos for SubPlan nodes */
115 
116 	Bitmapset  *rewindPlanIDs;	/* indices of subplans that require REWIND */
117 
118 	List	   *finalrtable;	/* "flat" rangetable for executor */
119 
120 	List	   *finalrowmarks;	/* "flat" list of PlanRowMarks */
121 
122 	List	   *resultRelations;	/* "flat" list of integer RT indexes */
123 
124 	List	   *rootResultRelations;	/* "flat" list of integer RT indexes */
125 
126 	List	   *relationOids;	/* OIDs of relations the plan depends on */
127 
128 	List	   *invalItems;		/* other dependencies, as PlanInvalItems */
129 
130 	List	   *paramExecTypes; /* type OIDs for PARAM_EXEC Params */
131 
132 	Index		lastPHId;		/* highest PlaceHolderVar ID assigned */
133 
134 	Index		lastRowMarkId;	/* highest PlanRowMark ID assigned */
135 
136 	int			lastPlanNodeId; /* highest plan node ID assigned */
137 
138 	bool		transientPlan;	/* redo plan when TransactionXmin changes? */
139 
140 	bool		dependsOnRole;	/* is plan specific to current role? */
141 
142 	bool		parallelModeOK; /* parallel mode potentially OK? */
143 
144 	bool		parallelModeNeeded; /* parallel mode actually required? */
145 
146 	char		maxParallelHazard;	/* worst PROPARALLEL hazard level */
147 
148 	PartitionDirectory partition_directory; /* partition descriptors */
149 } PlannerGlobal;
150 
151 /* macro for fetching the Plan associated with a SubPlan node */
152 #define planner_subplan_get_plan(root, subplan) \
153 	((Plan *) list_nth((root)->glob->subplans, (subplan)->plan_id - 1))
154 
155 
156 /*----------
157  * PlannerInfo
158  *		Per-query information for planning/optimization
159  *
160  * This struct is conventionally called "root" in all the planner routines.
161  * It holds links to all of the planner's working state, in addition to the
162  * original Query.  Note that at present the planner extensively modifies
163  * the passed-in Query data structure; someday that should stop.
164  *
165  * For reasons explained in optimizer/optimizer.h, we define the typedef
166  * either here or in that header, whichever is read first.
167  *----------
168  */
169 #ifndef HAVE_PLANNERINFO_TYPEDEF
170 typedef struct PlannerInfo PlannerInfo;
171 #define HAVE_PLANNERINFO_TYPEDEF 1
172 #endif
173 
174 struct PlannerInfo
175 {
176 	NodeTag		type;
177 
178 	Query	   *parse;			/* the Query being planned */
179 
180 	PlannerGlobal *glob;		/* global info for current planner run */
181 
182 	Index		query_level;	/* 1 at the outermost Query */
183 
184 	PlannerInfo *parent_root;	/* NULL at outermost Query */
185 
186 	/*
187 	 * plan_params contains the expressions that this query level needs to
188 	 * make available to a lower query level that is currently being planned.
189 	 * outer_params contains the paramIds of PARAM_EXEC Params that outer
190 	 * query levels will make available to this query level.
191 	 */
192 	List	   *plan_params;	/* list of PlannerParamItems, see below */
193 	Bitmapset  *outer_params;
194 
195 	/*
196 	 * simple_rel_array holds pointers to "base rels" and "other rels" (see
197 	 * comments for RelOptInfo for more info).  It is indexed by rangetable
198 	 * index (so entry 0 is always wasted).  Entries can be NULL when an RTE
199 	 * does not correspond to a base relation, such as a join RTE or an
200 	 * unreferenced view RTE; or if the RelOptInfo hasn't been made yet.
201 	 */
202 	struct RelOptInfo **simple_rel_array;	/* All 1-rel RelOptInfos */
203 	int			simple_rel_array_size;	/* allocated size of array */
204 
205 	/*
206 	 * simple_rte_array is the same length as simple_rel_array and holds
207 	 * pointers to the associated rangetable entries.  This lets us avoid
208 	 * rt_fetch(), which can be a bit slow once large inheritance sets have
209 	 * been expanded.
210 	 */
211 	RangeTblEntry **simple_rte_array;	/* rangetable as an array */
212 
213 	/*
214 	 * append_rel_array is the same length as the above arrays, and holds
215 	 * pointers to the corresponding AppendRelInfo entry indexed by
216 	 * child_relid, or NULL if none.  The array itself is not allocated if
217 	 * append_rel_list is empty.
218 	 */
219 	struct AppendRelInfo **append_rel_array;
220 
221 	/*
222 	 * all_baserels is a Relids set of all base relids (but not "other"
223 	 * relids) in the query; that is, the Relids identifier of the final join
224 	 * we need to form.  This is computed in make_one_rel, just before we
225 	 * start making Paths.
226 	 */
227 	Relids		all_baserels;
228 
229 	/*
230 	 * nullable_baserels is a Relids set of base relids that are nullable by
231 	 * some outer join in the jointree; these are rels that are potentially
232 	 * nullable below the WHERE clause, SELECT targetlist, etc.  This is
233 	 * computed in deconstruct_jointree.
234 	 */
235 	Relids		nullable_baserels;
236 
237 	/*
238 	 * join_rel_list is a list of all join-relation RelOptInfos we have
239 	 * considered in this planning run.  For small problems we just scan the
240 	 * list to do lookups, but when there are many join relations we build a
241 	 * hash table for faster lookups.  The hash table is present and valid
242 	 * when join_rel_hash is not NULL.  Note that we still maintain the list
243 	 * even when using the hash table for lookups; this simplifies life for
244 	 * GEQO.
245 	 */
246 	List	   *join_rel_list;	/* list of join-relation RelOptInfos */
247 	struct HTAB *join_rel_hash; /* optional hashtable for join relations */
248 
249 	/*
250 	 * When doing a dynamic-programming-style join search, join_rel_level[k]
251 	 * is a list of all join-relation RelOptInfos of level k, and
252 	 * join_cur_level is the current level.  New join-relation RelOptInfos are
253 	 * automatically added to the join_rel_level[join_cur_level] list.
254 	 * join_rel_level is NULL if not in use.
255 	 */
256 	List	  **join_rel_level; /* lists of join-relation RelOptInfos */
257 	int			join_cur_level; /* index of list being extended */
258 
259 	List	   *init_plans;		/* init SubPlans for query */
260 
261 	List	   *cte_plan_ids;	/* per-CTE-item list of subplan IDs */
262 
263 	List	   *multiexpr_params;	/* List of Lists of Params for MULTIEXPR
264 									 * subquery outputs */
265 
266 	List	   *eq_classes;		/* list of active EquivalenceClasses */
267 
268 	List	   *canon_pathkeys; /* list of "canonical" PathKeys */
269 
270 	List	   *left_join_clauses;	/* list of RestrictInfos for mergejoinable
271 									 * outer join clauses w/nonnullable var on
272 									 * left */
273 
274 	List	   *right_join_clauses; /* list of RestrictInfos for mergejoinable
275 									 * outer join clauses w/nonnullable var on
276 									 * right */
277 
278 	List	   *full_join_clauses;	/* list of RestrictInfos for mergejoinable
279 									 * full join clauses */
280 
281 	List	   *join_info_list; /* list of SpecialJoinInfos */
282 
283 	/*
284 	 * Note: for AppendRelInfos describing partitions of a partitioned table,
285 	 * we guarantee that partitions that come earlier in the partitioned
286 	 * table's PartitionDesc will appear earlier in append_rel_list.
287 	 */
288 	List	   *append_rel_list;	/* list of AppendRelInfos */
289 
290 	List	   *rowMarks;		/* list of PlanRowMarks */
291 
292 	List	   *placeholder_list;	/* list of PlaceHolderInfos */
293 
294 	List	   *fkey_list;		/* list of ForeignKeyOptInfos */
295 
296 	List	   *query_pathkeys; /* desired pathkeys for query_planner() */
297 
298 	List	   *group_pathkeys; /* groupClause pathkeys, if any */
299 	List	   *window_pathkeys;	/* pathkeys of bottom window, if any */
300 	List	   *distinct_pathkeys;	/* distinctClause pathkeys, if any */
301 	List	   *sort_pathkeys;	/* sortClause pathkeys, if any */
302 
303 	List	   *part_schemes;	/* Canonicalised partition schemes used in the
304 								 * query. */
305 
306 	List	   *initial_rels;	/* RelOptInfos we are now trying to join */
307 
308 	/* Use fetch_upper_rel() to get any particular upper rel */
309 	List	   *upper_rels[UPPERREL_FINAL + 1]; /* upper-rel RelOptInfos */
310 
311 	/* Result tlists chosen by grouping_planner for upper-stage processing */
312 	struct PathTarget *upper_targets[UPPERREL_FINAL + 1];
313 
314 	/*
315 	 * The fully-processed targetlist is kept here.  It differs from
316 	 * parse->targetList in that (for INSERT and UPDATE) it's been reordered
317 	 * to match the target table, and defaults have been filled in.  Also,
318 	 * additional resjunk targets may be present.  preprocess_targetlist()
319 	 * does most of this work, but note that more resjunk targets can get
320 	 * added during appendrel expansion.  (Hence, upper_targets mustn't get
321 	 * set up till after that.)
322 	 */
323 	List	   *processed_tlist;
324 
325 	/* Fields filled during create_plan() for use in setrefs.c */
326 	AttrNumber *grouping_map;	/* for GroupingFunc fixup */
327 	List	   *minmax_aggs;	/* List of MinMaxAggInfos */
328 
329 	MemoryContext planner_cxt;	/* context holding PlannerInfo */
330 
331 	double		total_table_pages;	/* # of pages in all non-dummy tables of
332 									 * query */
333 
334 	double		tuple_fraction; /* tuple_fraction passed to query_planner */
335 	double		limit_tuples;	/* limit_tuples passed to query_planner */
336 
337 	Index		qual_security_level;	/* minimum security_level for quals */
338 	/* Note: qual_security_level is zero if there are no securityQuals */
339 
340 	InheritanceKind inhTargetKind;	/* indicates if the target relation is an
341 									 * inheritance child or partition or a
342 									 * partitioned table */
343 	bool		hasJoinRTEs;	/* true if any RTEs are RTE_JOIN kind */
344 	bool		hasLateralRTEs; /* true if any RTEs are marked LATERAL */
345 	bool		hasHavingQual;	/* true if havingQual was non-null */
346 	bool		hasPseudoConstantQuals; /* true if any RestrictInfo has
347 										 * pseudoconstant = true */
348 	bool		hasRecursion;	/* true if planning a recursive WITH item */
349 
350 	/* These fields are used only when hasRecursion is true: */
351 	int			wt_param_id;	/* PARAM_EXEC ID for the work table */
352 	struct Path *non_recursive_path;	/* a path for non-recursive term */
353 
354 	/* These fields are workspace for createplan.c */
355 	Relids		curOuterRels;	/* outer rels above current node */
356 	List	   *curOuterParams; /* not-yet-assigned NestLoopParams */
357 
358 	/* optional private data for join_search_hook, e.g., GEQO */
359 	void	   *join_search_private;
360 
361 	/* Does this query modify any partition key columns? */
362 	bool		partColsUpdated;
363 };
364 
365 
366 /*
367  * In places where it's known that simple_rte_array[] must have been prepared
368  * already, we just index into it to fetch RTEs.  In code that might be
369  * executed before or after entering query_planner(), use this macro.
370  */
371 #define planner_rt_fetch(rti, root) \
372 	((root)->simple_rte_array ? (root)->simple_rte_array[rti] : \
373 	 rt_fetch(rti, (root)->parse->rtable))
374 
375 /*
376  * If multiple relations are partitioned the same way, all such partitions
377  * will have a pointer to the same PartitionScheme.  A list of PartitionScheme
378  * objects is attached to the PlannerInfo.  By design, the partition scheme
379  * incorporates only the general properties of the partition method (LIST vs.
380  * RANGE, number of partitioning columns and the type information for each)
381  * and not the specific bounds.
382  *
383  * We store the opclass-declared input data types instead of the partition key
384  * datatypes since the former rather than the latter are used to compare
385  * partition bounds. Since partition key data types and the opclass declared
386  * input data types are expected to be binary compatible (per ResolveOpClass),
387  * both of those should have same byval and length properties.
388  */
389 typedef struct PartitionSchemeData
390 {
391 	char		strategy;		/* partition strategy */
392 	int16		partnatts;		/* number of partition attributes */
393 	Oid		   *partopfamily;	/* OIDs of operator families */
394 	Oid		   *partopcintype;	/* OIDs of opclass declared input data types */
395 	Oid		   *partcollation;	/* OIDs of partitioning collations */
396 
397 	/* Cached information about partition key data types. */
398 	int16	   *parttyplen;
399 	bool	   *parttypbyval;
400 
401 	/* Cached information about partition comparison functions. */
402 	FmgrInfo   *partsupfunc;
403 }			PartitionSchemeData;
404 
405 typedef struct PartitionSchemeData *PartitionScheme;
406 
407 /*----------
408  * RelOptInfo
409  *		Per-relation information for planning/optimization
410  *
411  * For planning purposes, a "base rel" is either a plain relation (a table)
412  * or the output of a sub-SELECT or function that appears in the range table.
413  * In either case it is uniquely identified by an RT index.  A "joinrel"
414  * is the joining of two or more base rels.  A joinrel is identified by
415  * the set of RT indexes for its component baserels.  We create RelOptInfo
416  * nodes for each baserel and joinrel, and store them in the PlannerInfo's
417  * simple_rel_array and join_rel_list respectively.
418  *
419  * Note that there is only one joinrel for any given set of component
420  * baserels, no matter what order we assemble them in; so an unordered
421  * set is the right datatype to identify it with.
422  *
423  * We also have "other rels", which are like base rels in that they refer to
424  * single RT indexes; but they are not part of the join tree, and are given
425  * a different RelOptKind to identify them.
426  * Currently the only kind of otherrels are those made for member relations
427  * of an "append relation", that is an inheritance set or UNION ALL subquery.
428  * An append relation has a parent RTE that is a base rel, which represents
429  * the entire append relation.  The member RTEs are otherrels.  The parent
430  * is present in the query join tree but the members are not.  The member
431  * RTEs and otherrels are used to plan the scans of the individual tables or
432  * subqueries of the append set; then the parent baserel is given Append
433  * and/or MergeAppend paths comprising the best paths for the individual
434  * member rels.  (See comments for AppendRelInfo for more information.)
435  *
436  * At one time we also made otherrels to represent join RTEs, for use in
437  * handling join alias Vars.  Currently this is not needed because all join
438  * alias Vars are expanded to non-aliased form during preprocess_expression.
439  *
440  * We also have relations representing joins between child relations of
441  * different partitioned tables. These relations are not added to
442  * join_rel_level lists as they are not joined directly by the dynamic
443  * programming algorithm.
444  *
445  * There is also a RelOptKind for "upper" relations, which are RelOptInfos
446  * that describe post-scan/join processing steps, such as aggregation.
447  * Many of the fields in these RelOptInfos are meaningless, but their Path
448  * fields always hold Paths showing ways to do that processing step.
449  *
450  * Lastly, there is a RelOptKind for "dead" relations, which are base rels
451  * that we have proven we don't need to join after all.
452  *
453  * Parts of this data structure are specific to various scan and join
454  * mechanisms.  It didn't seem worth creating new node types for them.
455  *
456  *		relids - Set of base-relation identifiers; it is a base relation
457  *				if there is just one, a join relation if more than one
458  *		rows - estimated number of tuples in the relation after restriction
459  *			   clauses have been applied (ie, output rows of a plan for it)
460  *		consider_startup - true if there is any value in keeping plain paths for
461  *						   this rel on the basis of having cheap startup cost
462  *		consider_param_startup - the same for parameterized paths
463  *		reltarget - Default Path output tlist for this rel; normally contains
464  *					Var and PlaceHolderVar nodes for the values we need to
465  *					output from this relation.
466  *					List is in no particular order, but all rels of an
467  *					appendrel set must use corresponding orders.
468  *					NOTE: in an appendrel child relation, may contain
469  *					arbitrary expressions pulled up from a subquery!
470  *		pathlist - List of Path nodes, one for each potentially useful
471  *				   method of generating the relation
472  *		ppilist - ParamPathInfo nodes for parameterized Paths, if any
473  *		cheapest_startup_path - the pathlist member with lowest startup cost
474  *			(regardless of ordering) among the unparameterized paths;
475  *			or NULL if there is no unparameterized path
476  *		cheapest_total_path - the pathlist member with lowest total cost
477  *			(regardless of ordering) among the unparameterized paths;
478  *			or if there is no unparameterized path, the path with lowest
479  *			total cost among the paths with minimum parameterization
480  *		cheapest_unique_path - for caching cheapest path to produce unique
481  *			(no duplicates) output from relation; NULL if not yet requested
482  *		cheapest_parameterized_paths - best paths for their parameterizations;
483  *			always includes cheapest_total_path, even if that's unparameterized
484  *		direct_lateral_relids - rels this rel has direct LATERAL references to
485  *		lateral_relids - required outer rels for LATERAL, as a Relids set
486  *			(includes both direct and indirect lateral references)
487  *
488  * If the relation is a base relation it will have these fields set:
489  *
490  *		relid - RTE index (this is redundant with the relids field, but
491  *				is provided for convenience of access)
492  *		rtekind - copy of RTE's rtekind field
493  *		min_attr, max_attr - range of valid AttrNumbers for rel
494  *		attr_needed - array of bitmapsets indicating the highest joinrel
495  *				in which each attribute is needed; if bit 0 is set then
496  *				the attribute is needed as part of final targetlist
497  *		attr_widths - cache space for per-attribute width estimates;
498  *					  zero means not computed yet
499  *		lateral_vars - lateral cross-references of rel, if any (list of
500  *					   Vars and PlaceHolderVars)
501  *		lateral_referencers - relids of rels that reference this one laterally
502  *				(includes both direct and indirect lateral references)
503  *		indexlist - list of IndexOptInfo nodes for relation's indexes
504  *					(always NIL if it's not a table)
505  *		pages - number of disk pages in relation (zero if not a table)
506  *		tuples - number of tuples in relation (not considering restrictions)
507  *		allvisfrac - fraction of disk pages that are marked all-visible
508  *		subroot - PlannerInfo for subquery (NULL if it's not a subquery)
509  *		subplan_params - list of PlannerParamItems to be passed to subquery
510  *
511  *		Note: for a subquery, tuples and subroot are not set immediately
512  *		upon creation of the RelOptInfo object; they are filled in when
513  *		set_subquery_pathlist processes the object.
514  *
515  *		For otherrels that are appendrel members, these fields are filled
516  *		in just as for a baserel, except we don't bother with lateral_vars.
517  *
518  * If the relation is either a foreign table or a join of foreign tables that
519  * all belong to the same foreign server and are assigned to the same user to
520  * check access permissions as (cf checkAsUser), these fields will be set:
521  *
522  *		serverid - OID of foreign server, if foreign table (else InvalidOid)
523  *		userid - OID of user to check access as (InvalidOid means current user)
524  *		useridiscurrent - we've assumed that userid equals current user
525  *		fdwroutine - function hooks for FDW, if foreign table (else NULL)
526  *		fdw_private - private state for FDW, if foreign table (else NULL)
527  *
528  * Two fields are used to cache knowledge acquired during the join search
529  * about whether this rel is provably unique when being joined to given other
530  * relation(s), ie, it can have at most one row matching any given row from
531  * that join relation.  Currently we only attempt such proofs, and thus only
532  * populate these fields, for base rels; but someday they might be used for
533  * join rels too:
534  *
535  *		unique_for_rels - list of Relid sets, each one being a set of other
536  *					rels for which this one has been proven unique
537  *		non_unique_for_rels - list of Relid sets, each one being a set of
538  *					other rels for which we have tried and failed to prove
539  *					this one unique
540  *
541  * The presence of the following fields depends on the restrictions
542  * and joins that the relation participates in:
543  *
544  *		baserestrictinfo - List of RestrictInfo nodes, containing info about
545  *					each non-join qualification clause in which this relation
546  *					participates (only used for base rels)
547  *		baserestrictcost - Estimated cost of evaluating the baserestrictinfo
548  *					clauses at a single tuple (only used for base rels)
549  *		baserestrict_min_security - Smallest security_level found among
550  *					clauses in baserestrictinfo
551  *		joininfo  - List of RestrictInfo nodes, containing info about each
552  *					join clause in which this relation participates (but
553  *					note this excludes clauses that might be derivable from
554  *					EquivalenceClasses)
555  *		has_eclass_joins - flag that EquivalenceClass joins are possible
556  *
557  * Note: Keeping a restrictinfo list in the RelOptInfo is useful only for
558  * base rels, because for a join rel the set of clauses that are treated as
559  * restrict clauses varies depending on which sub-relations we choose to join.
560  * (For example, in a 3-base-rel join, a clause relating rels 1 and 2 must be
561  * treated as a restrictclause if we join {1} and {2 3} to make {1 2 3}; but
562  * if we join {1 2} and {3} then that clause will be a restrictclause in {1 2}
563  * and should not be processed again at the level of {1 2 3}.)	Therefore,
564  * the restrictinfo list in the join case appears in individual JoinPaths
565  * (field joinrestrictinfo), not in the parent relation.  But it's OK for
566  * the RelOptInfo to store the joininfo list, because that is the same
567  * for a given rel no matter how we form it.
568  *
569  * We store baserestrictcost in the RelOptInfo (for base relations) because
570  * we know we will need it at least once (to price the sequential scan)
571  * and may need it multiple times to price index scans.
572  *
573  * If the relation is partitioned, these fields will be set:
574  *
575  *		part_scheme - Partitioning scheme of the relation
576  *		nparts - Number of partitions
577  *		boundinfo - Partition bounds
578  *		partition_qual - Partition constraint if not the root
579  *		part_rels - RelOptInfos for each partition
580  *		partexprs, nullable_partexprs - Partition key expressions
581  *		partitioned_child_rels - RT indexes of unpruned partitions of
582  *								 this relation that are partitioned tables
583  *								 themselves, in hierarchical order
584  *
585  * Note: A base relation always has only one set of partition keys, but a join
586  * relation may have as many sets of partition keys as the number of relations
587  * being joined. partexprs and nullable_partexprs are arrays containing
588  * part_scheme->partnatts elements each. Each of these elements is a list of
589  * partition key expressions.  For a base relation each list in partexprs
590  * contains only one expression and nullable_partexprs is not populated. For a
591  * join relation, partexprs and nullable_partexprs contain partition key
592  * expressions from non-nullable and nullable relations resp. Lists at any
593  * given position in those arrays together contain as many elements as the
594  * number of joining relations.
595  *----------
596  */
597 typedef enum RelOptKind
598 {
599 	RELOPT_BASEREL,
600 	RELOPT_JOINREL,
601 	RELOPT_OTHER_MEMBER_REL,
602 	RELOPT_OTHER_JOINREL,
603 	RELOPT_UPPER_REL,
604 	RELOPT_OTHER_UPPER_REL,
605 	RELOPT_DEADREL
606 } RelOptKind;
607 
608 /*
609  * Is the given relation a simple relation i.e a base or "other" member
610  * relation?
611  */
612 #define IS_SIMPLE_REL(rel) \
613 	((rel)->reloptkind == RELOPT_BASEREL || \
614 	 (rel)->reloptkind == RELOPT_OTHER_MEMBER_REL)
615 
616 /* Is the given relation a join relation? */
617 #define IS_JOIN_REL(rel)	\
618 	((rel)->reloptkind == RELOPT_JOINREL || \
619 	 (rel)->reloptkind == RELOPT_OTHER_JOINREL)
620 
621 /* Is the given relation an upper relation? */
622 #define IS_UPPER_REL(rel)	\
623 	((rel)->reloptkind == RELOPT_UPPER_REL || \
624 	 (rel)->reloptkind == RELOPT_OTHER_UPPER_REL)
625 
626 /* Is the given relation an "other" relation? */
627 #define IS_OTHER_REL(rel) \
628 	((rel)->reloptkind == RELOPT_OTHER_MEMBER_REL || \
629 	 (rel)->reloptkind == RELOPT_OTHER_JOINREL || \
630 	 (rel)->reloptkind == RELOPT_OTHER_UPPER_REL)
631 
632 typedef struct RelOptInfo
633 {
634 	NodeTag		type;
635 
636 	RelOptKind	reloptkind;
637 
638 	/* all relations included in this RelOptInfo */
639 	Relids		relids;			/* set of base relids (rangetable indexes) */
640 
641 	/* size estimates generated by planner */
642 	double		rows;			/* estimated number of result tuples */
643 
644 	/* per-relation planner control flags */
645 	bool		consider_startup;	/* keep cheap-startup-cost paths? */
646 	bool		consider_param_startup; /* ditto, for parameterized paths? */
647 	bool		consider_parallel;	/* consider parallel paths? */
648 
649 	/* default result targetlist for Paths scanning this relation */
650 	struct PathTarget *reltarget;	/* list of Vars/Exprs, cost, width */
651 
652 	/* materialization information */
653 	List	   *pathlist;		/* Path structures */
654 	List	   *ppilist;		/* ParamPathInfos used in pathlist */
655 	List	   *partial_pathlist;	/* partial Paths */
656 	struct Path *cheapest_startup_path;
657 	struct Path *cheapest_total_path;
658 	struct Path *cheapest_unique_path;
659 	List	   *cheapest_parameterized_paths;
660 
661 	/* parameterization information needed for both base rels and join rels */
662 	/* (see also lateral_vars and lateral_referencers) */
663 	Relids		direct_lateral_relids;	/* rels directly laterally referenced */
664 	Relids		lateral_relids; /* minimum parameterization of rel */
665 
666 	/* information about a base rel (not set for join rels!) */
667 	Index		relid;
668 	Oid			reltablespace;	/* containing tablespace */
669 	RTEKind		rtekind;		/* RELATION, SUBQUERY, FUNCTION, etc */
670 	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
671 	AttrNumber	max_attr;		/* largest attrno of rel */
672 	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
673 	int32	   *attr_widths;	/* array indexed [min_attr .. max_attr] */
674 	List	   *lateral_vars;	/* LATERAL Vars and PHVs referenced by rel */
675 	Relids		lateral_referencers;	/* rels that reference me laterally */
676 	List	   *indexlist;		/* list of IndexOptInfo */
677 	List	   *statlist;		/* list of StatisticExtInfo */
678 	BlockNumber pages;			/* size estimates derived from pg_class */
679 	double		tuples;
680 	double		allvisfrac;
681 	PlannerInfo *subroot;		/* if subquery */
682 	List	   *subplan_params; /* if subquery */
683 	int			rel_parallel_workers;	/* wanted number of parallel workers */
684 
685 	/* Information about foreign tables and foreign joins */
686 	Oid			serverid;		/* identifies server for the table or join */
687 	Oid			userid;			/* identifies user to check access as */
688 	bool		useridiscurrent;	/* join is only valid for current user */
689 	/* use "struct FdwRoutine" to avoid including fdwapi.h here */
690 	struct FdwRoutine *fdwroutine;
691 	void	   *fdw_private;
692 
693 	/* cache space for remembering if we have proven this relation unique */
694 	List	   *unique_for_rels;	/* known unique for these other relid
695 									 * set(s) */
696 	List	   *non_unique_for_rels;	/* known not unique for these set(s) */
697 
698 	/* used by various scans and joins: */
699 	List	   *baserestrictinfo;	/* RestrictInfo structures (if base rel) */
700 	QualCost	baserestrictcost;	/* cost of evaluating the above */
701 	Index		baserestrict_min_security;	/* min security_level found in
702 											 * baserestrictinfo */
703 	List	   *joininfo;		/* RestrictInfo structures for join clauses
704 								 * involving this rel */
705 	bool		has_eclass_joins;	/* T means joininfo is incomplete */
706 
707 	/* used by partitionwise joins: */
708 	bool		consider_partitionwise_join;	/* consider partitionwise join
709 												 * paths? (if partitioned rel) */
710 	Relids		top_parent_relids;	/* Relids of topmost parents (if "other"
711 									 * rel) */
712 
713 	/* used for partitioned relations */
714 	PartitionScheme part_scheme;	/* Partitioning scheme. */
715 	int			nparts;			/* number of partitions */
716 	struct PartitionBoundInfoData *boundinfo;	/* Partition bounds */
717 	List	   *partition_qual; /* partition constraint */
718 	struct RelOptInfo **part_rels;	/* Array of RelOptInfos of partitions,
719 									 * stored in the same order of bounds */
720 	List	  **partexprs;		/* Non-nullable partition key expressions. */
721 	List	  **nullable_partexprs; /* Nullable partition key expressions. */
722 	List	   *partitioned_child_rels; /* List of RT indexes. */
723 } RelOptInfo;
724 
725 /*
726  * Is given relation partitioned?
727  *
728  * It's not enough to test whether rel->part_scheme is set, because it might
729  * be that the basic partitioning properties of the input relations matched
730  * but the partition bounds did not.  Also, if we are able to prove a rel
731  * dummy (empty), we should henceforth treat it as unpartitioned.
732  */
733 #define IS_PARTITIONED_REL(rel) \
734 	((rel)->part_scheme && (rel)->boundinfo && (rel)->nparts > 0 && \
735 	 (rel)->part_rels && !IS_DUMMY_REL(rel))
736 
737 /*
738  * Convenience macro to make sure that a partitioned relation has all the
739  * required members set.
740  */
741 #define REL_HAS_ALL_PART_PROPS(rel)	\
742 	((rel)->part_scheme && (rel)->boundinfo && (rel)->nparts > 0 && \
743 	 (rel)->part_rels && (rel)->partexprs && (rel)->nullable_partexprs)
744 
745 /*
746  * IndexOptInfo
747  *		Per-index information for planning/optimization
748  *
749  *		indexkeys[], indexcollations[] each have ncolumns entries.
750  *		opfamily[], and opcintype[]	each have nkeycolumns entries. They do
751  *		not contain any information about included attributes.
752  *
753  *		sortopfamily[], reverse_sort[], and nulls_first[] have
754  *		nkeycolumns entries, if the index is ordered; but if it is unordered,
755  *		those pointers are NULL.
756  *
757  *		Zeroes in the indexkeys[] array indicate index columns that are
758  *		expressions; there is one element in indexprs for each such column.
759  *
760  *		For an ordered index, reverse_sort[] and nulls_first[] describe the
761  *		sort ordering of a forward indexscan; we can also consider a backward
762  *		indexscan, which will generate the reverse ordering.
763  *
764  *		The indexprs and indpred expressions have been run through
765  *		prepqual.c and eval_const_expressions() for ease of matching to
766  *		WHERE clauses. indpred is in implicit-AND form.
767  *
768  *		indextlist is a TargetEntry list representing the index columns.
769  *		It provides an equivalent base-relation Var for each simple column,
770  *		and links to the matching indexprs element for each expression column.
771  *
772  *		While most of these fields are filled when the IndexOptInfo is created
773  *		(by plancat.c), indrestrictinfo and predOK are set later, in
774  *		check_index_predicates().
775  */
776 #ifndef HAVE_INDEXOPTINFO_TYPEDEF
777 typedef struct IndexOptInfo IndexOptInfo;
778 #define HAVE_INDEXOPTINFO_TYPEDEF 1
779 #endif
780 
781 struct IndexOptInfo
782 {
783 	NodeTag		type;
784 
785 	Oid			indexoid;		/* OID of the index relation */
786 	Oid			reltablespace;	/* tablespace of index (not table) */
787 	RelOptInfo *rel;			/* back-link to index's table */
788 
789 	/* index-size statistics (from pg_class and elsewhere) */
790 	BlockNumber pages;			/* number of disk pages in index */
791 	double		tuples;			/* number of index tuples in index */
792 	int			tree_height;	/* index tree height, or -1 if unknown */
793 
794 	/* index descriptor information */
795 	int			ncolumns;		/* number of columns in index */
796 	int			nkeycolumns;	/* number of key columns in index */
797 	int		   *indexkeys;		/* column numbers of index's attributes both
798 								 * key and included columns, or 0 */
799 	Oid		   *indexcollations;	/* OIDs of collations of index columns */
800 	Oid		   *opfamily;		/* OIDs of operator families for columns */
801 	Oid		   *opcintype;		/* OIDs of opclass declared input data types */
802 	Oid		   *sortopfamily;	/* OIDs of btree opfamilies, if orderable */
803 	bool	   *reverse_sort;	/* is sort order descending? */
804 	bool	   *nulls_first;	/* do NULLs come first in the sort order? */
805 	bool	   *canreturn;		/* which index cols can be returned in an
806 								 * index-only scan? */
807 	Oid			relam;			/* OID of the access method (in pg_am) */
808 
809 	List	   *indexprs;		/* expressions for non-simple index columns */
810 	List	   *indpred;		/* predicate if a partial index, else NIL */
811 
812 	List	   *indextlist;		/* targetlist representing index columns */
813 
814 	List	   *indrestrictinfo;	/* parent relation's baserestrictinfo
815 									 * list, less any conditions implied by
816 									 * the index's predicate (unless it's a
817 									 * target rel, see comments in
818 									 * check_index_predicates()) */
819 
820 	bool		predOK;			/* true if index predicate matches query */
821 	bool		unique;			/* true if a unique index */
822 	bool		immediate;		/* is uniqueness enforced immediately? */
823 	bool		hypothetical;	/* true if index doesn't really exist */
824 
825 	/* Remaining fields are copied from the index AM's API struct: */
826 	bool		amcanorderbyop; /* does AM support order by operator result? */
827 	bool		amoptionalkey;	/* can query omit key for the first column? */
828 	bool		amsearcharray;	/* can AM handle ScalarArrayOpExpr quals? */
829 	bool		amsearchnulls;	/* can AM search for NULL/NOT NULL entries? */
830 	bool		amhasgettuple;	/* does AM have amgettuple interface? */
831 	bool		amhasgetbitmap; /* does AM have amgetbitmap interface? */
832 	bool		amcanparallel;	/* does AM support parallel scan? */
833 	bool		amcanmarkpos;	/* does AM support mark/restore? */
834 	/* Rather than include amapi.h here, we declare amcostestimate like this */
835 	void		(*amcostestimate) ();	/* AM's cost estimator */
836 };
837 
838 /*
839  * ForeignKeyOptInfo
840  *		Per-foreign-key information for planning/optimization
841  *
842  * The per-FK-column arrays can be fixed-size because we allow at most
843  * INDEX_MAX_KEYS columns in a foreign key constraint.  Each array has
844  * nkeys valid entries.
845  */
846 typedef struct ForeignKeyOptInfo
847 {
848 	NodeTag		type;
849 
850 	/* Basic data about the foreign key (fetched from catalogs): */
851 	Index		con_relid;		/* RT index of the referencing table */
852 	Index		ref_relid;		/* RT index of the referenced table */
853 	int			nkeys;			/* number of columns in the foreign key */
854 	AttrNumber	conkey[INDEX_MAX_KEYS]; /* cols in referencing table */
855 	AttrNumber	confkey[INDEX_MAX_KEYS];	/* cols in referenced table */
856 	Oid			conpfeqop[INDEX_MAX_KEYS];	/* PK = FK operator OIDs */
857 
858 	/* Derived info about whether FK's equality conditions match the query: */
859 	int			nmatched_ec;	/* # of FK cols matched by ECs */
860 	int			nmatched_rcols; /* # of FK cols matched by non-EC rinfos */
861 	int			nmatched_ri;	/* total # of non-EC rinfos matched to FK */
862 	/* Pointer to eclass matching each column's condition, if there is one */
863 	struct EquivalenceClass *eclass[INDEX_MAX_KEYS];
864 	/* List of non-EC RestrictInfos matching each column's condition */
865 	List	   *rinfos[INDEX_MAX_KEYS];
866 } ForeignKeyOptInfo;
867 
868 /*
869  * StatisticExtInfo
870  *		Information about extended statistics for planning/optimization
871  *
872  * Each pg_statistic_ext row is represented by one or more nodes of this
873  * type, or even zero if ANALYZE has not computed them.
874  */
875 typedef struct StatisticExtInfo
876 {
877 	NodeTag		type;
878 
879 	Oid			statOid;		/* OID of the statistics row */
880 	RelOptInfo *rel;			/* back-link to statistic's table */
881 	char		kind;			/* statistics kind of this entry */
882 	Bitmapset  *keys;			/* attnums of the columns covered */
883 } StatisticExtInfo;
884 
885 /*
886  * EquivalenceClasses
887  *
888  * Whenever we can determine that a mergejoinable equality clause A = B is
889  * not delayed by any outer join, we create an EquivalenceClass containing
890  * the expressions A and B to record this knowledge.  If we later find another
891  * equivalence B = C, we add C to the existing EquivalenceClass; this may
892  * require merging two existing EquivalenceClasses.  At the end of the qual
893  * distribution process, we have sets of values that are known all transitively
894  * equal to each other, where "equal" is according to the rules of the btree
895  * operator family(s) shown in ec_opfamilies, as well as the collation shown
896  * by ec_collation.  (We restrict an EC to contain only equalities whose
897  * operators belong to the same set of opfamilies.  This could probably be
898  * relaxed, but for now it's not worth the trouble, since nearly all equality
899  * operators belong to only one btree opclass anyway.  Similarly, we suppose
900  * that all or none of the input datatypes are collatable, so that a single
901  * collation value is sufficient.)
902  *
903  * We also use EquivalenceClasses as the base structure for PathKeys, letting
904  * us represent knowledge about different sort orderings being equivalent.
905  * Since every PathKey must reference an EquivalenceClass, we will end up
906  * with single-member EquivalenceClasses whenever a sort key expression has
907  * not been equivalenced to anything else.  It is also possible that such an
908  * EquivalenceClass will contain a volatile expression ("ORDER BY random()"),
909  * which is a case that can't arise otherwise since clauses containing
910  * volatile functions are never considered mergejoinable.  We mark such
911  * EquivalenceClasses specially to prevent them from being merged with
912  * ordinary EquivalenceClasses.  Also, for volatile expressions we have
913  * to be careful to match the EquivalenceClass to the correct targetlist
914  * entry: consider SELECT random() AS a, random() AS b ... ORDER BY b,a.
915  * So we record the SortGroupRef of the originating sort clause.
916  *
917  * We allow equality clauses appearing below the nullable side of an outer join
918  * to form EquivalenceClasses, but these have a slightly different meaning:
919  * the included values might be all NULL rather than all the same non-null
920  * values.  See src/backend/optimizer/README for more on that point.
921  *
922  * NB: if ec_merged isn't NULL, this class has been merged into another, and
923  * should be ignored in favor of using the pointed-to class.
924  */
925 typedef struct EquivalenceClass
926 {
927 	NodeTag		type;
928 
929 	List	   *ec_opfamilies;	/* btree operator family OIDs */
930 	Oid			ec_collation;	/* collation, if datatypes are collatable */
931 	List	   *ec_members;		/* list of EquivalenceMembers */
932 	List	   *ec_sources;		/* list of generating RestrictInfos */
933 	List	   *ec_derives;		/* list of derived RestrictInfos */
934 	Relids		ec_relids;		/* all relids appearing in ec_members, except
935 								 * for child members (see below) */
936 	bool		ec_has_const;	/* any pseudoconstants in ec_members? */
937 	bool		ec_has_volatile;	/* the (sole) member is a volatile expr */
938 	bool		ec_below_outer_join;	/* equivalence applies below an OJ */
939 	bool		ec_broken;		/* failed to generate needed clauses? */
940 	Index		ec_sortref;		/* originating sortclause label, or 0 */
941 	Index		ec_min_security;	/* minimum security_level in ec_sources */
942 	Index		ec_max_security;	/* maximum security_level in ec_sources */
943 	struct EquivalenceClass *ec_merged; /* set if merged into another EC */
944 } EquivalenceClass;
945 
946 /*
947  * If an EC contains a const and isn't below-outer-join, any PathKey depending
948  * on it must be redundant, since there's only one possible value of the key.
949  */
950 #define EC_MUST_BE_REDUNDANT(eclass)  \
951 	((eclass)->ec_has_const && !(eclass)->ec_below_outer_join)
952 
953 /*
954  * EquivalenceMember - one member expression of an EquivalenceClass
955  *
956  * em_is_child signifies that this element was built by transposing a member
957  * for an appendrel parent relation to represent the corresponding expression
958  * for an appendrel child.  These members are used for determining the
959  * pathkeys of scans on the child relation and for explicitly sorting the
960  * child when necessary to build a MergeAppend path for the whole appendrel
961  * tree.  An em_is_child member has no impact on the properties of the EC as a
962  * whole; in particular the EC's ec_relids field does NOT include the child
963  * relation.  An em_is_child member should never be marked em_is_const nor
964  * cause ec_has_const or ec_has_volatile to be set, either.  Thus, em_is_child
965  * members are not really full-fledged members of the EC, but just reflections
966  * or doppelgangers of real members.  Most operations on EquivalenceClasses
967  * should ignore em_is_child members, and those that don't should test
968  * em_relids to make sure they only consider relevant members.
969  *
970  * em_datatype is usually the same as exprType(em_expr), but can be
971  * different when dealing with a binary-compatible opfamily; in particular
972  * anyarray_ops would never work without this.  Use em_datatype when
973  * looking up a specific btree operator to work with this expression.
974  */
975 typedef struct EquivalenceMember
976 {
977 	NodeTag		type;
978 
979 	Expr	   *em_expr;		/* the expression represented */
980 	Relids		em_relids;		/* all relids appearing in em_expr */
981 	Relids		em_nullable_relids; /* nullable by lower outer joins */
982 	bool		em_is_const;	/* expression is pseudoconstant? */
983 	bool		em_is_child;	/* derived version for a child relation? */
984 	Oid			em_datatype;	/* the "nominal type" used by the opfamily */
985 } EquivalenceMember;
986 
987 /*
988  * PathKeys
989  *
990  * The sort ordering of a path is represented by a list of PathKey nodes.
991  * An empty list implies no known ordering.  Otherwise the first item
992  * represents the primary sort key, the second the first secondary sort key,
993  * etc.  The value being sorted is represented by linking to an
994  * EquivalenceClass containing that value and including pk_opfamily among its
995  * ec_opfamilies.  The EquivalenceClass tells which collation to use, too.
996  * This is a convenient method because it makes it trivial to detect
997  * equivalent and closely-related orderings. (See optimizer/README for more
998  * information.)
999  *
1000  * Note: pk_strategy is either BTLessStrategyNumber (for ASC) or
1001  * BTGreaterStrategyNumber (for DESC).  We assume that all ordering-capable
1002  * index types will use btree-compatible strategy numbers.
1003  */
1004 typedef struct PathKey
1005 {
1006 	NodeTag		type;
1007 
1008 	EquivalenceClass *pk_eclass;	/* the value that is ordered */
1009 	Oid			pk_opfamily;	/* btree opfamily defining the ordering */
1010 	int			pk_strategy;	/* sort direction (ASC or DESC) */
1011 	bool		pk_nulls_first; /* do NULLs come before normal values? */
1012 } PathKey;
1013 
1014 
1015 /*
1016  * PathTarget
1017  *
1018  * This struct contains what we need to know during planning about the
1019  * targetlist (output columns) that a Path will compute.  Each RelOptInfo
1020  * includes a default PathTarget, which its individual Paths may simply
1021  * reference.  However, in some cases a Path may compute outputs different
1022  * from other Paths, and in that case we make a custom PathTarget for it.
1023  * For example, an indexscan might return index expressions that would
1024  * otherwise need to be explicitly calculated.  (Note also that "upper"
1025  * relations generally don't have useful default PathTargets.)
1026  *
1027  * exprs contains bare expressions; they do not have TargetEntry nodes on top,
1028  * though those will appear in finished Plans.
1029  *
1030  * sortgrouprefs[] is an array of the same length as exprs, containing the
1031  * corresponding sort/group refnos, or zeroes for expressions not referenced
1032  * by sort/group clauses.  If sortgrouprefs is NULL (which it generally is in
1033  * RelOptInfo.reltarget targets; only upper-level Paths contain this info),
1034  * we have not identified sort/group columns in this tlist.  This allows us to
1035  * deal with sort/group refnos when needed with less expense than including
1036  * TargetEntry nodes in the exprs list.
1037  */
1038 typedef struct PathTarget
1039 {
1040 	NodeTag		type;
1041 	List	   *exprs;			/* list of expressions to be computed */
1042 	Index	   *sortgrouprefs;	/* corresponding sort/group refnos, or 0 */
1043 	QualCost	cost;			/* cost of evaluating the expressions */
1044 	int			width;			/* estimated avg width of result tuples */
1045 } PathTarget;
1046 
1047 /* Convenience macro to get a sort/group refno from a PathTarget */
1048 #define get_pathtarget_sortgroupref(target, colno) \
1049 	((target)->sortgrouprefs ? (target)->sortgrouprefs[colno] : (Index) 0)
1050 
1051 
1052 /*
1053  * ParamPathInfo
1054  *
1055  * All parameterized paths for a given relation with given required outer rels
1056  * link to a single ParamPathInfo, which stores common information such as
1057  * the estimated rowcount for this parameterization.  We do this partly to
1058  * avoid recalculations, but mostly to ensure that the estimated rowcount
1059  * is in fact the same for every such path.
1060  *
1061  * Note: ppi_clauses is only used in ParamPathInfos for base relation paths;
1062  * in join cases it's NIL because the set of relevant clauses varies depending
1063  * on how the join is formed.  The relevant clauses will appear in each
1064  * parameterized join path's joinrestrictinfo list, instead.
1065  */
1066 typedef struct ParamPathInfo
1067 {
1068 	NodeTag		type;
1069 
1070 	Relids		ppi_req_outer;	/* rels supplying parameters used by path */
1071 	double		ppi_rows;		/* estimated number of result tuples */
1072 	List	   *ppi_clauses;	/* join clauses available from outer rels */
1073 } ParamPathInfo;
1074 
1075 
1076 /*
1077  * Type "Path" is used as-is for sequential-scan paths, as well as some other
1078  * simple plan types that we don't need any extra information in the path for.
1079  * For other path types it is the first component of a larger struct.
1080  *
1081  * "pathtype" is the NodeTag of the Plan node we could build from this Path.
1082  * It is partially redundant with the Path's NodeTag, but allows us to use
1083  * the same Path type for multiple Plan types when there is no need to
1084  * distinguish the Plan type during path processing.
1085  *
1086  * "parent" identifies the relation this Path scans, and "pathtarget"
1087  * describes the precise set of output columns the Path would compute.
1088  * In simple cases all Paths for a given rel share the same targetlist,
1089  * which we represent by having path->pathtarget equal to parent->reltarget.
1090  *
1091  * "param_info", if not NULL, links to a ParamPathInfo that identifies outer
1092  * relation(s) that provide parameter values to each scan of this path.
1093  * That means this path can only be joined to those rels by means of nestloop
1094  * joins with this path on the inside.  Also note that a parameterized path
1095  * is responsible for testing all "movable" joinclauses involving this rel
1096  * and the specified outer rel(s).
1097  *
1098  * "rows" is the same as parent->rows in simple paths, but in parameterized
1099  * paths and UniquePaths it can be less than parent->rows, reflecting the
1100  * fact that we've filtered by extra join conditions or removed duplicates.
1101  *
1102  * "pathkeys" is a List of PathKey nodes (see above), describing the sort
1103  * ordering of the path's output rows.
1104  */
1105 typedef struct Path
1106 {
1107 	NodeTag		type;
1108 
1109 	NodeTag		pathtype;		/* tag identifying scan/join method */
1110 
1111 	RelOptInfo *parent;			/* the relation this path can build */
1112 	PathTarget *pathtarget;		/* list of Vars/Exprs, cost, width */
1113 
1114 	ParamPathInfo *param_info;	/* parameterization info, or NULL if none */
1115 
1116 	bool		parallel_aware; /* engage parallel-aware logic? */
1117 	bool		parallel_safe;	/* OK to use as part of parallel plan? */
1118 	int			parallel_workers;	/* desired # of workers; 0 = not parallel */
1119 
1120 	/* estimated size/costs for path (see costsize.c for more info) */
1121 	double		rows;			/* estimated number of result tuples */
1122 	Cost		startup_cost;	/* cost expended before fetching any tuples */
1123 	Cost		total_cost;		/* total cost (assuming all tuples fetched) */
1124 
1125 	List	   *pathkeys;		/* sort ordering of path's output */
1126 	/* pathkeys is a List of PathKey nodes; see above */
1127 } Path;
1128 
1129 /* Macro for extracting a path's parameterization relids; beware double eval */
1130 #define PATH_REQ_OUTER(path)  \
1131 	((path)->param_info ? (path)->param_info->ppi_req_outer : (Relids) NULL)
1132 
1133 /*----------
1134  * IndexPath represents an index scan over a single index.
1135  *
1136  * This struct is used for both regular indexscans and index-only scans;
1137  * path.pathtype is T_IndexScan or T_IndexOnlyScan to show which is meant.
1138  *
1139  * 'indexinfo' is the index to be scanned.
1140  *
1141  * 'indexclauses' is a list of IndexClause nodes, each representing one
1142  * index-checkable restriction, with implicit AND semantics across the list.
1143  * An empty list implies a full index scan.
1144  *
1145  * 'indexorderbys', if not NIL, is a list of ORDER BY expressions that have
1146  * been found to be usable as ordering operators for an amcanorderbyop index.
1147  * The list must match the path's pathkeys, ie, one expression per pathkey
1148  * in the same order.  These are not RestrictInfos, just bare expressions,
1149  * since they generally won't yield booleans.  It's guaranteed that each
1150  * expression has the index key on the left side of the operator.
1151  *
1152  * 'indexorderbycols' is an integer list of index column numbers (zero-based)
1153  * of the same length as 'indexorderbys', showing which index column each
1154  * ORDER BY expression is meant to be used with.  (There is no restriction
1155  * on which index column each ORDER BY can be used with.)
1156  *
1157  * 'indexscandir' is one of:
1158  *		ForwardScanDirection: forward scan of an ordered index
1159  *		BackwardScanDirection: backward scan of an ordered index
1160  *		NoMovementScanDirection: scan of an unordered index, or don't care
1161  * (The executor doesn't care whether it gets ForwardScanDirection or
1162  * NoMovementScanDirection for an indexscan, but the planner wants to
1163  * distinguish ordered from unordered indexes for building pathkeys.)
1164  *
1165  * 'indextotalcost' and 'indexselectivity' are saved in the IndexPath so that
1166  * we need not recompute them when considering using the same index in a
1167  * bitmap index/heap scan (see BitmapHeapPath).  The costs of the IndexPath
1168  * itself represent the costs of an IndexScan or IndexOnlyScan plan type.
1169  *----------
1170  */
1171 typedef struct IndexPath
1172 {
1173 	Path		path;
1174 	IndexOptInfo *indexinfo;
1175 	List	   *indexclauses;
1176 	List	   *indexorderbys;
1177 	List	   *indexorderbycols;
1178 	ScanDirection indexscandir;
1179 	Cost		indextotalcost;
1180 	Selectivity indexselectivity;
1181 } IndexPath;
1182 
1183 /*
1184  * Each IndexClause references a RestrictInfo node from the query's WHERE
1185  * or JOIN conditions, and shows how that restriction can be applied to
1186  * the particular index.  We support both indexclauses that are directly
1187  * usable by the index machinery, which are typically of the form
1188  * "indexcol OP pseudoconstant", and those from which an indexable qual
1189  * can be derived.  The simplest such transformation is that a clause
1190  * of the form "pseudoconstant OP indexcol" can be commuted to produce an
1191  * indexable qual (the index machinery expects the indexcol to be on the
1192  * left always).  Another example is that we might be able to extract an
1193  * indexable range condition from a LIKE condition, as in "x LIKE 'foo%bar'"
1194  * giving rise to "x >= 'foo' AND x < 'fop'".  Derivation of such lossy
1195  * conditions is done by a planner support function attached to the
1196  * indexclause's top-level function or operator.
1197  *
1198  * indexquals is a list of RestrictInfos for the directly-usable index
1199  * conditions associated with this IndexClause.  In the simplest case
1200  * it's a one-element list whose member is iclause->rinfo.  Otherwise,
1201  * it contains one or more directly-usable indexqual conditions extracted
1202  * from the given clause.  The 'lossy' flag indicates whether the
1203  * indexquals are semantically equivalent to the original clause, or
1204  * represent a weaker condition.
1205  *
1206  * Normally, indexcol is the index of the single index column the clause
1207  * works on, and indexcols is NIL.  But if the clause is a RowCompareExpr,
1208  * indexcol is the index of the leading column, and indexcols is a list of
1209  * all the affected columns.  (Note that indexcols matches up with the
1210  * columns of the actual indexable RowCompareExpr in indexquals, which
1211  * might be different from the original in rinfo.)
1212  *
1213  * An IndexPath's IndexClause list is required to be ordered by index
1214  * column, i.e. the indexcol values must form a nondecreasing sequence.
1215  * (The order of multiple clauses for the same index column is unspecified.)
1216  */
1217 typedef struct IndexClause
1218 {
1219 	NodeTag		type;
1220 	struct RestrictInfo *rinfo; /* original restriction or join clause */
1221 	List	   *indexquals;		/* indexqual(s) derived from it */
1222 	bool		lossy;			/* are indexquals a lossy version of clause? */
1223 	AttrNumber	indexcol;		/* index column the clause uses (zero-based) */
1224 	List	   *indexcols;		/* multiple index columns, if RowCompare */
1225 } IndexClause;
1226 
1227 /*
1228  * BitmapHeapPath represents one or more indexscans that generate TID bitmaps
1229  * instead of directly accessing the heap, followed by AND/OR combinations
1230  * to produce a single bitmap, followed by a heap scan that uses the bitmap.
1231  * Note that the output is always considered unordered, since it will come
1232  * out in physical heap order no matter what the underlying indexes did.
1233  *
1234  * The individual indexscans are represented by IndexPath nodes, and any
1235  * logic on top of them is represented by a tree of BitmapAndPath and
1236  * BitmapOrPath nodes.  Notice that we can use the same IndexPath node both
1237  * to represent a regular (or index-only) index scan plan, and as the child
1238  * of a BitmapHeapPath that represents scanning the same index using a
1239  * BitmapIndexScan.  The startup_cost and total_cost figures of an IndexPath
1240  * always represent the costs to use it as a regular (or index-only)
1241  * IndexScan.  The costs of a BitmapIndexScan can be computed using the
1242  * IndexPath's indextotalcost and indexselectivity.
1243  */
1244 typedef struct BitmapHeapPath
1245 {
1246 	Path		path;
1247 	Path	   *bitmapqual;		/* IndexPath, BitmapAndPath, BitmapOrPath */
1248 } BitmapHeapPath;
1249 
1250 /*
1251  * BitmapAndPath represents a BitmapAnd plan node; it can only appear as
1252  * part of the substructure of a BitmapHeapPath.  The Path structure is
1253  * a bit more heavyweight than we really need for this, but for simplicity
1254  * we make it a derivative of Path anyway.
1255  */
1256 typedef struct BitmapAndPath
1257 {
1258 	Path		path;
1259 	List	   *bitmapquals;	/* IndexPaths and BitmapOrPaths */
1260 	Selectivity bitmapselectivity;
1261 } BitmapAndPath;
1262 
1263 /*
1264  * BitmapOrPath represents a BitmapOr plan node; it can only appear as
1265  * part of the substructure of a BitmapHeapPath.  The Path structure is
1266  * a bit more heavyweight than we really need for this, but for simplicity
1267  * we make it a derivative of Path anyway.
1268  */
1269 typedef struct BitmapOrPath
1270 {
1271 	Path		path;
1272 	List	   *bitmapquals;	/* IndexPaths and BitmapAndPaths */
1273 	Selectivity bitmapselectivity;
1274 } BitmapOrPath;
1275 
1276 /*
1277  * TidPath represents a scan by TID
1278  *
1279  * tidquals is an implicitly OR'ed list of qual expressions of the form
1280  * "CTID = pseudoconstant", or "CTID = ANY(pseudoconstant_array)",
1281  * or a CurrentOfExpr for the relation.
1282  */
1283 typedef struct TidPath
1284 {
1285 	Path		path;
1286 	List	   *tidquals;		/* qual(s) involving CTID = something */
1287 } TidPath;
1288 
1289 /*
1290  * SubqueryScanPath represents a scan of an unflattened subquery-in-FROM
1291  *
1292  * Note that the subpath comes from a different planning domain; for example
1293  * RTE indexes within it mean something different from those known to the
1294  * SubqueryScanPath.  path.parent->subroot is the planning context needed to
1295  * interpret the subpath.
1296  */
1297 typedef struct SubqueryScanPath
1298 {
1299 	Path		path;
1300 	Path	   *subpath;		/* path representing subquery execution */
1301 } SubqueryScanPath;
1302 
1303 /*
1304  * ForeignPath represents a potential scan of a foreign table, foreign join
1305  * or foreign upper-relation.
1306  *
1307  * fdw_private stores FDW private data about the scan.  While fdw_private is
1308  * not actually touched by the core code during normal operations, it's
1309  * generally a good idea to use a representation that can be dumped by
1310  * nodeToString(), so that you can examine the structure during debugging
1311  * with tools like pprint().
1312  */
1313 typedef struct ForeignPath
1314 {
1315 	Path		path;
1316 	Path	   *fdw_outerpath;
1317 	List	   *fdw_private;
1318 } ForeignPath;
1319 
1320 /*
1321  * CustomPath represents a table scan done by some out-of-core extension.
1322  *
1323  * We provide a set of hooks here - which the provider must take care to set
1324  * up correctly - to allow extensions to supply their own methods of scanning
1325  * a relation.  For example, a provider might provide GPU acceleration, a
1326  * cache-based scan, or some other kind of logic we haven't dreamed up yet.
1327  *
1328  * CustomPaths can be injected into the planning process for a relation by
1329  * set_rel_pathlist_hook functions.
1330  *
1331  * Core code must avoid assuming that the CustomPath is only as large as
1332  * the structure declared here; providers are allowed to make it the first
1333  * element in a larger structure.  (Since the planner never copies Paths,
1334  * this doesn't add any complication.)  However, for consistency with the
1335  * FDW case, we provide a "custom_private" field in CustomPath; providers
1336  * may prefer to use that rather than define another struct type.
1337  */
1338 
1339 struct CustomPathMethods;
1340 
1341 typedef struct CustomPath
1342 {
1343 	Path		path;
1344 	uint32		flags;			/* mask of CUSTOMPATH_* flags, see
1345 								 * nodes/extensible.h */
1346 	List	   *custom_paths;	/* list of child Path nodes, if any */
1347 	List	   *custom_private;
1348 	const struct CustomPathMethods *methods;
1349 } CustomPath;
1350 
1351 /*
1352  * AppendPath represents an Append plan, ie, successive execution of
1353  * several member plans.
1354  *
1355  * For partial Append, 'subpaths' contains non-partial subpaths followed by
1356  * partial subpaths.
1357  *
1358  * Note: it is possible for "subpaths" to contain only one, or even no,
1359  * elements.  These cases are optimized during create_append_plan.
1360  * In particular, an AppendPath with no subpaths is a "dummy" path that
1361  * is created to represent the case that a relation is provably empty.
1362  * (This is a convenient representation because it means that when we build
1363  * an appendrel and find that all its children have been excluded, no extra
1364  * action is needed to recognize the relation as dummy.)
1365  */
1366 typedef struct AppendPath
1367 {
1368 	Path		path;
1369 	/* RT indexes of non-leaf tables in a partition tree */
1370 	List	   *partitioned_rels;
1371 	List	   *subpaths;		/* list of component Paths */
1372 	/* Index of first partial path in subpaths; list_length(subpaths) if none */
1373 	int			first_partial_path;
1374 	double		limit_tuples;	/* hard limit on output tuples, or -1 */
1375 } AppendPath;
1376 
1377 #define IS_DUMMY_APPEND(p) \
1378 	(IsA((p), AppendPath) && ((AppendPath *) (p))->subpaths == NIL)
1379 
1380 /*
1381  * A relation that's been proven empty will have one path that is dummy
1382  * (but might have projection paths on top).  For historical reasons,
1383  * this is provided as a macro that wraps is_dummy_rel().
1384  */
1385 #define IS_DUMMY_REL(r) is_dummy_rel(r)
1386 extern bool is_dummy_rel(RelOptInfo *rel);
1387 
1388 /*
1389  * MergeAppendPath represents a MergeAppend plan, ie, the merging of sorted
1390  * results from several member plans to produce similarly-sorted output.
1391  */
1392 typedef struct MergeAppendPath
1393 {
1394 	Path		path;
1395 	/* RT indexes of non-leaf tables in a partition tree */
1396 	List	   *partitioned_rels;
1397 	List	   *subpaths;		/* list of component Paths */
1398 	double		limit_tuples;	/* hard limit on output tuples, or -1 */
1399 } MergeAppendPath;
1400 
1401 /*
1402  * GroupResultPath represents use of a Result plan node to compute the
1403  * output of a degenerate GROUP BY case, wherein we know we should produce
1404  * exactly one row, which might then be filtered by a HAVING qual.
1405  *
1406  * Note that quals is a list of bare clauses, not RestrictInfos.
1407  */
1408 typedef struct GroupResultPath
1409 {
1410 	Path		path;
1411 	List	   *quals;
1412 } GroupResultPath;
1413 
1414 /*
1415  * MaterialPath represents use of a Material plan node, i.e., caching of
1416  * the output of its subpath.  This is used when the subpath is expensive
1417  * and needs to be scanned repeatedly, or when we need mark/restore ability
1418  * and the subpath doesn't have it.
1419  */
1420 typedef struct MaterialPath
1421 {
1422 	Path		path;
1423 	Path	   *subpath;
1424 } MaterialPath;
1425 
1426 /*
1427  * UniquePath represents elimination of distinct rows from the output of
1428  * its subpath.
1429  *
1430  * This can represent significantly different plans: either hash-based or
1431  * sort-based implementation, or a no-op if the input path can be proven
1432  * distinct already.  The decision is sufficiently localized that it's not
1433  * worth having separate Path node types.  (Note: in the no-op case, we could
1434  * eliminate the UniquePath node entirely and just return the subpath; but
1435  * it's convenient to have a UniquePath in the path tree to signal upper-level
1436  * routines that the input is known distinct.)
1437  */
1438 typedef enum
1439 {
1440 	UNIQUE_PATH_NOOP,			/* input is known unique already */
1441 	UNIQUE_PATH_HASH,			/* use hashing */
1442 	UNIQUE_PATH_SORT			/* use sorting */
1443 } UniquePathMethod;
1444 
1445 typedef struct UniquePath
1446 {
1447 	Path		path;
1448 	Path	   *subpath;
1449 	UniquePathMethod umethod;
1450 	List	   *in_operators;	/* equality operators of the IN clause */
1451 	List	   *uniq_exprs;		/* expressions to be made unique */
1452 } UniquePath;
1453 
1454 /*
1455  * GatherPath runs several copies of a plan in parallel and collects the
1456  * results.  The parallel leader may also execute the plan, unless the
1457  * single_copy flag is set.
1458  */
1459 typedef struct GatherPath
1460 {
1461 	Path		path;
1462 	Path	   *subpath;		/* path for each worker */
1463 	bool		single_copy;	/* don't execute path more than once */
1464 	int			num_workers;	/* number of workers sought to help */
1465 } GatherPath;
1466 
1467 /*
1468  * GatherMergePath runs several copies of a plan in parallel and collects
1469  * the results, preserving their common sort order.
1470  */
1471 typedef struct GatherMergePath
1472 {
1473 	Path		path;
1474 	Path	   *subpath;		/* path for each worker */
1475 	int			num_workers;	/* number of workers sought to help */
1476 } GatherMergePath;
1477 
1478 
1479 /*
1480  * All join-type paths share these fields.
1481  */
1482 
1483 typedef struct JoinPath
1484 {
1485 	Path		path;
1486 
1487 	JoinType	jointype;
1488 
1489 	bool		inner_unique;	/* each outer tuple provably matches no more
1490 								 * than one inner tuple */
1491 
1492 	Path	   *outerjoinpath;	/* path for the outer side of the join */
1493 	Path	   *innerjoinpath;	/* path for the inner side of the join */
1494 
1495 	List	   *joinrestrictinfo;	/* RestrictInfos to apply to join */
1496 
1497 	/*
1498 	 * See the notes for RelOptInfo and ParamPathInfo to understand why
1499 	 * joinrestrictinfo is needed in JoinPath, and can't be merged into the
1500 	 * parent RelOptInfo.
1501 	 */
1502 } JoinPath;
1503 
1504 /*
1505  * A nested-loop path needs no special fields.
1506  */
1507 
1508 typedef JoinPath NestPath;
1509 
1510 /*
1511  * A mergejoin path has these fields.
1512  *
1513  * Unlike other path types, a MergePath node doesn't represent just a single
1514  * run-time plan node: it can represent up to four.  Aside from the MergeJoin
1515  * node itself, there can be a Sort node for the outer input, a Sort node
1516  * for the inner input, and/or a Material node for the inner input.  We could
1517  * represent these nodes by separate path nodes, but considering how many
1518  * different merge paths are investigated during a complex join problem,
1519  * it seems better to avoid unnecessary palloc overhead.
1520  *
1521  * path_mergeclauses lists the clauses (in the form of RestrictInfos)
1522  * that will be used in the merge.
1523  *
1524  * Note that the mergeclauses are a subset of the parent relation's
1525  * restriction-clause list.  Any join clauses that are not mergejoinable
1526  * appear only in the parent's restrict list, and must be checked by a
1527  * qpqual at execution time.
1528  *
1529  * outersortkeys (resp. innersortkeys) is NIL if the outer path
1530  * (resp. inner path) is already ordered appropriately for the
1531  * mergejoin.  If it is not NIL then it is a PathKeys list describing
1532  * the ordering that must be created by an explicit Sort node.
1533  *
1534  * skip_mark_restore is true if the executor need not do mark/restore calls.
1535  * Mark/restore overhead is usually required, but can be skipped if we know
1536  * that the executor need find only one match per outer tuple, and that the
1537  * mergeclauses are sufficient to identify a match.  In such cases the
1538  * executor can immediately advance the outer relation after processing a
1539  * match, and therefore it need never back up the inner relation.
1540  *
1541  * materialize_inner is true if a Material node should be placed atop the
1542  * inner input.  This may appear with or without an inner Sort step.
1543  */
1544 
1545 typedef struct MergePath
1546 {
1547 	JoinPath	jpath;
1548 	List	   *path_mergeclauses;	/* join clauses to be used for merge */
1549 	List	   *outersortkeys;	/* keys for explicit sort, if any */
1550 	List	   *innersortkeys;	/* keys for explicit sort, if any */
1551 	bool		skip_mark_restore;	/* can executor skip mark/restore? */
1552 	bool		materialize_inner;	/* add Materialize to inner? */
1553 } MergePath;
1554 
1555 /*
1556  * A hashjoin path has these fields.
1557  *
1558  * The remarks above for mergeclauses apply for hashclauses as well.
1559  *
1560  * Hashjoin does not care what order its inputs appear in, so we have
1561  * no need for sortkeys.
1562  */
1563 
1564 typedef struct HashPath
1565 {
1566 	JoinPath	jpath;
1567 	List	   *path_hashclauses;	/* join clauses used for hashing */
1568 	int			num_batches;	/* number of batches expected */
1569 	double		inner_rows_total;	/* total inner rows expected */
1570 } HashPath;
1571 
1572 /*
1573  * ProjectionPath represents a projection (that is, targetlist computation)
1574  *
1575  * Nominally, this path node represents using a Result plan node to do a
1576  * projection step.  However, if the input plan node supports projection,
1577  * we can just modify its output targetlist to do the required calculations
1578  * directly, and not need a Result.  In some places in the planner we can just
1579  * jam the desired PathTarget into the input path node (and adjust its cost
1580  * accordingly), so we don't need a ProjectionPath.  But in other places
1581  * it's necessary to not modify the input path node, so we need a separate
1582  * ProjectionPath node, which is marked dummy to indicate that we intend to
1583  * assign the work to the input plan node.  The estimated cost for the
1584  * ProjectionPath node will account for whether a Result will be used or not.
1585  */
1586 typedef struct ProjectionPath
1587 {
1588 	Path		path;
1589 	Path	   *subpath;		/* path representing input source */
1590 	bool		dummypp;		/* true if no separate Result is needed */
1591 } ProjectionPath;
1592 
1593 /*
1594  * ProjectSetPath represents evaluation of a targetlist that includes
1595  * set-returning function(s), which will need to be implemented by a
1596  * ProjectSet plan node.
1597  */
1598 typedef struct ProjectSetPath
1599 {
1600 	Path		path;
1601 	Path	   *subpath;		/* path representing input source */
1602 } ProjectSetPath;
1603 
1604 /*
1605  * SortPath represents an explicit sort step
1606  *
1607  * The sort keys are, by definition, the same as path.pathkeys.
1608  *
1609  * Note: the Sort plan node cannot project, so path.pathtarget must be the
1610  * same as the input's pathtarget.
1611  */
1612 typedef struct SortPath
1613 {
1614 	Path		path;
1615 	Path	   *subpath;		/* path representing input source */
1616 } SortPath;
1617 
1618 /*
1619  * GroupPath represents grouping (of presorted input)
1620  *
1621  * groupClause represents the columns to be grouped on; the input path
1622  * must be at least that well sorted.
1623  *
1624  * We can also apply a qual to the grouped rows (equivalent of HAVING)
1625  */
1626 typedef struct GroupPath
1627 {
1628 	Path		path;
1629 	Path	   *subpath;		/* path representing input source */
1630 	List	   *groupClause;	/* a list of SortGroupClause's */
1631 	List	   *qual;			/* quals (HAVING quals), if any */
1632 } GroupPath;
1633 
1634 /*
1635  * UpperUniquePath represents adjacent-duplicate removal (in presorted input)
1636  *
1637  * The columns to be compared are the first numkeys columns of the path's
1638  * pathkeys.  The input is presumed already sorted that way.
1639  */
1640 typedef struct UpperUniquePath
1641 {
1642 	Path		path;
1643 	Path	   *subpath;		/* path representing input source */
1644 	int			numkeys;		/* number of pathkey columns to compare */
1645 } UpperUniquePath;
1646 
1647 /*
1648  * AggPath represents generic computation of aggregate functions
1649  *
1650  * This may involve plain grouping (but not grouping sets), using either
1651  * sorted or hashed grouping; for the AGG_SORTED case, the input must be
1652  * appropriately presorted.
1653  */
1654 typedef struct AggPath
1655 {
1656 	Path		path;
1657 	Path	   *subpath;		/* path representing input source */
1658 	AggStrategy aggstrategy;	/* basic strategy, see nodes.h */
1659 	AggSplit	aggsplit;		/* agg-splitting mode, see nodes.h */
1660 	double		numGroups;		/* estimated number of groups in input */
1661 	List	   *groupClause;	/* a list of SortGroupClause's */
1662 	List	   *qual;			/* quals (HAVING quals), if any */
1663 } AggPath;
1664 
1665 /*
1666  * Various annotations used for grouping sets in the planner.
1667  */
1668 
1669 typedef struct GroupingSetData
1670 {
1671 	NodeTag		type;
1672 	List	   *set;			/* grouping set as list of sortgrouprefs */
1673 	double		numGroups;		/* est. number of result groups */
1674 } GroupingSetData;
1675 
1676 typedef struct RollupData
1677 {
1678 	NodeTag		type;
1679 	List	   *groupClause;	/* applicable subset of parse->groupClause */
1680 	List	   *gsets;			/* lists of integer indexes into groupClause */
1681 	List	   *gsets_data;		/* list of GroupingSetData */
1682 	double		numGroups;		/* est. number of result groups */
1683 	bool		hashable;		/* can be hashed */
1684 	bool		is_hashed;		/* to be implemented as a hashagg */
1685 } RollupData;
1686 
1687 /*
1688  * GroupingSetsPath represents a GROUPING SETS aggregation
1689  */
1690 
1691 typedef struct GroupingSetsPath
1692 {
1693 	Path		path;
1694 	Path	   *subpath;		/* path representing input source */
1695 	AggStrategy aggstrategy;	/* basic strategy */
1696 	List	   *rollups;		/* list of RollupData */
1697 	List	   *qual;			/* quals (HAVING quals), if any */
1698 } GroupingSetsPath;
1699 
1700 /*
1701  * MinMaxAggPath represents computation of MIN/MAX aggregates from indexes
1702  */
1703 typedef struct MinMaxAggPath
1704 {
1705 	Path		path;
1706 	List	   *mmaggregates;	/* list of MinMaxAggInfo */
1707 	List	   *quals;			/* HAVING quals, if any */
1708 } MinMaxAggPath;
1709 
1710 /*
1711  * WindowAggPath represents generic computation of window functions
1712  */
1713 typedef struct WindowAggPath
1714 {
1715 	Path		path;
1716 	Path	   *subpath;		/* path representing input source */
1717 	WindowClause *winclause;	/* WindowClause we'll be using */
1718 } WindowAggPath;
1719 
1720 /*
1721  * SetOpPath represents a set-operation, that is INTERSECT or EXCEPT
1722  */
1723 typedef struct SetOpPath
1724 {
1725 	Path		path;
1726 	Path	   *subpath;		/* path representing input source */
1727 	SetOpCmd	cmd;			/* what to do, see nodes.h */
1728 	SetOpStrategy strategy;		/* how to do it, see nodes.h */
1729 	List	   *distinctList;	/* SortGroupClauses identifying target cols */
1730 	AttrNumber	flagColIdx;		/* where is the flag column, if any */
1731 	int			firstFlag;		/* flag value for first input relation */
1732 	double		numGroups;		/* estimated number of groups in input */
1733 } SetOpPath;
1734 
1735 /*
1736  * RecursiveUnionPath represents a recursive UNION node
1737  */
1738 typedef struct RecursiveUnionPath
1739 {
1740 	Path		path;
1741 	Path	   *leftpath;		/* paths representing input sources */
1742 	Path	   *rightpath;
1743 	List	   *distinctList;	/* SortGroupClauses identifying target cols */
1744 	int			wtParam;		/* ID of Param representing work table */
1745 	double		numGroups;		/* estimated number of groups in input */
1746 } RecursiveUnionPath;
1747 
1748 /*
1749  * LockRowsPath represents acquiring row locks for SELECT FOR UPDATE/SHARE
1750  */
1751 typedef struct LockRowsPath
1752 {
1753 	Path		path;
1754 	Path	   *subpath;		/* path representing input source */
1755 	List	   *rowMarks;		/* a list of PlanRowMark's */
1756 	int			epqParam;		/* ID of Param for EvalPlanQual re-eval */
1757 } LockRowsPath;
1758 
1759 /*
1760  * ModifyTablePath represents performing INSERT/UPDATE/DELETE modifications
1761  *
1762  * We represent most things that will be in the ModifyTable plan node
1763  * literally, except we have child Path(s) not Plan(s).  But analysis of the
1764  * OnConflictExpr is deferred to createplan.c, as is collection of FDW data.
1765  */
1766 typedef struct ModifyTablePath
1767 {
1768 	Path		path;
1769 	CmdType		operation;		/* INSERT, UPDATE, or DELETE */
1770 	bool		canSetTag;		/* do we set the command tag/es_processed? */
1771 	Index		nominalRelation;	/* Parent RT index for use of EXPLAIN */
1772 	Index		rootRelation;	/* Root RT index, if target is partitioned */
1773 	bool		partColsUpdated;	/* some part key in hierarchy updated */
1774 	List	   *resultRelations;	/* integer list of RT indexes */
1775 	List	   *subpaths;		/* Path(s) producing source data */
1776 	List	   *subroots;		/* per-target-table PlannerInfos */
1777 	List	   *withCheckOptionLists;	/* per-target-table WCO lists */
1778 	List	   *returningLists; /* per-target-table RETURNING tlists */
1779 	List	   *rowMarks;		/* PlanRowMarks (non-locking only) */
1780 	OnConflictExpr *onconflict; /* ON CONFLICT clause, or NULL */
1781 	int			epqParam;		/* ID of Param for EvalPlanQual re-eval */
1782 } ModifyTablePath;
1783 
1784 /*
1785  * LimitPath represents applying LIMIT/OFFSET restrictions
1786  */
1787 typedef struct LimitPath
1788 {
1789 	Path		path;
1790 	Path	   *subpath;		/* path representing input source */
1791 	Node	   *limitOffset;	/* OFFSET parameter, or NULL if none */
1792 	Node	   *limitCount;		/* COUNT parameter, or NULL if none */
1793 } LimitPath;
1794 
1795 
1796 /*
1797  * Restriction clause info.
1798  *
1799  * We create one of these for each AND sub-clause of a restriction condition
1800  * (WHERE or JOIN/ON clause).  Since the restriction clauses are logically
1801  * ANDed, we can use any one of them or any subset of them to filter out
1802  * tuples, without having to evaluate the rest.  The RestrictInfo node itself
1803  * stores data used by the optimizer while choosing the best query plan.
1804  *
1805  * If a restriction clause references a single base relation, it will appear
1806  * in the baserestrictinfo list of the RelOptInfo for that base rel.
1807  *
1808  * If a restriction clause references more than one base rel, it will
1809  * appear in the joininfo list of every RelOptInfo that describes a strict
1810  * subset of the base rels mentioned in the clause.  The joininfo lists are
1811  * used to drive join tree building by selecting plausible join candidates.
1812  * The clause cannot actually be applied until we have built a join rel
1813  * containing all the base rels it references, however.
1814  *
1815  * When we construct a join rel that includes all the base rels referenced
1816  * in a multi-relation restriction clause, we place that clause into the
1817  * joinrestrictinfo lists of paths for the join rel, if neither left nor
1818  * right sub-path includes all base rels referenced in the clause.  The clause
1819  * will be applied at that join level, and will not propagate any further up
1820  * the join tree.  (Note: the "predicate migration" code was once intended to
1821  * push restriction clauses up and down the plan tree based on evaluation
1822  * costs, but it's dead code and is unlikely to be resurrected in the
1823  * foreseeable future.)
1824  *
1825  * Note that in the presence of more than two rels, a multi-rel restriction
1826  * might reach different heights in the join tree depending on the join
1827  * sequence we use.  So, these clauses cannot be associated directly with
1828  * the join RelOptInfo, but must be kept track of on a per-join-path basis.
1829  *
1830  * RestrictInfos that represent equivalence conditions (i.e., mergejoinable
1831  * equalities that are not outerjoin-delayed) are handled a bit differently.
1832  * Initially we attach them to the EquivalenceClasses that are derived from
1833  * them.  When we construct a scan or join path, we look through all the
1834  * EquivalenceClasses and generate derived RestrictInfos representing the
1835  * minimal set of conditions that need to be checked for this particular scan
1836  * or join to enforce that all members of each EquivalenceClass are in fact
1837  * equal in all rows emitted by the scan or join.
1838  *
1839  * When dealing with outer joins we have to be very careful about pushing qual
1840  * clauses up and down the tree.  An outer join's own JOIN/ON conditions must
1841  * be evaluated exactly at that join node, unless they are "degenerate"
1842  * conditions that reference only Vars from the nullable side of the join.
1843  * Quals appearing in WHERE or in a JOIN above the outer join cannot be pushed
1844  * down below the outer join, if they reference any nullable Vars.
1845  * RestrictInfo nodes contain a flag to indicate whether a qual has been
1846  * pushed down to a lower level than its original syntactic placement in the
1847  * join tree would suggest.  If an outer join prevents us from pushing a qual
1848  * down to its "natural" semantic level (the level associated with just the
1849  * base rels used in the qual) then we mark the qual with a "required_relids"
1850  * value including more than just the base rels it actually uses.  By
1851  * pretending that the qual references all the rels required to form the outer
1852  * join, we prevent it from being evaluated below the outer join's joinrel.
1853  * When we do form the outer join's joinrel, we still need to distinguish
1854  * those quals that are actually in that join's JOIN/ON condition from those
1855  * that appeared elsewhere in the tree and were pushed down to the join rel
1856  * because they used no other rels.  That's what the is_pushed_down flag is
1857  * for; it tells us that a qual is not an OUTER JOIN qual for the set of base
1858  * rels listed in required_relids.  A clause that originally came from WHERE
1859  * or an INNER JOIN condition will *always* have its is_pushed_down flag set.
1860  * It's possible for an OUTER JOIN clause to be marked is_pushed_down too,
1861  * if we decide that it can be pushed down into the nullable side of the join.
1862  * In that case it acts as a plain filter qual for wherever it gets evaluated.
1863  * (In short, is_pushed_down is only false for non-degenerate outer join
1864  * conditions.  Possibly we should rename it to reflect that meaning?  But
1865  * see also the comments for RINFO_IS_PUSHED_DOWN, below.)
1866  *
1867  * RestrictInfo nodes also contain an outerjoin_delayed flag, which is true
1868  * if the clause's applicability must be delayed due to any outer joins
1869  * appearing below it (ie, it has to be postponed to some join level higher
1870  * than the set of relations it actually references).
1871  *
1872  * There is also an outer_relids field, which is NULL except for outer join
1873  * clauses; for those, it is the set of relids on the outer side of the
1874  * clause's outer join.  (These are rels that the clause cannot be applied to
1875  * in parameterized scans, since pushing it into the join's outer side would
1876  * lead to wrong answers.)
1877  *
1878  * There is also a nullable_relids field, which is the set of rels the clause
1879  * references that can be forced null by some outer join below the clause.
1880  *
1881  * outerjoin_delayed = true is subtly different from nullable_relids != NULL:
1882  * a clause might reference some nullable rels and yet not be
1883  * outerjoin_delayed because it also references all the other rels of the
1884  * outer join(s). A clause that is not outerjoin_delayed can be enforced
1885  * anywhere it is computable.
1886  *
1887  * To handle security-barrier conditions efficiently, we mark RestrictInfo
1888  * nodes with a security_level field, in which higher values identify clauses
1889  * coming from less-trusted sources.  The exact semantics are that a clause
1890  * cannot be evaluated before another clause with a lower security_level value
1891  * unless the first clause is leakproof.  As with outer-join clauses, this
1892  * creates a reason for clauses to sometimes need to be evaluated higher in
1893  * the join tree than their contents would suggest; and even at a single plan
1894  * node, this rule constrains the order of application of clauses.
1895  *
1896  * In general, the referenced clause might be arbitrarily complex.  The
1897  * kinds of clauses we can handle as indexscan quals, mergejoin clauses,
1898  * or hashjoin clauses are limited (e.g., no volatile functions).  The code
1899  * for each kind of path is responsible for identifying the restrict clauses
1900  * it can use and ignoring the rest.  Clauses not implemented by an indexscan,
1901  * mergejoin, or hashjoin will be placed in the plan qual or joinqual field
1902  * of the finished Plan node, where they will be enforced by general-purpose
1903  * qual-expression-evaluation code.  (But we are still entitled to count
1904  * their selectivity when estimating the result tuple count, if we
1905  * can guess what it is...)
1906  *
1907  * When the referenced clause is an OR clause, we generate a modified copy
1908  * in which additional RestrictInfo nodes are inserted below the top-level
1909  * OR/AND structure.  This is a convenience for OR indexscan processing:
1910  * indexquals taken from either the top level or an OR subclause will have
1911  * associated RestrictInfo nodes.
1912  *
1913  * The can_join flag is set true if the clause looks potentially useful as
1914  * a merge or hash join clause, that is if it is a binary opclause with
1915  * nonoverlapping sets of relids referenced in the left and right sides.
1916  * (Whether the operator is actually merge or hash joinable isn't checked,
1917  * however.)
1918  *
1919  * The pseudoconstant flag is set true if the clause contains no Vars of
1920  * the current query level and no volatile functions.  Such a clause can be
1921  * pulled out and used as a one-time qual in a gating Result node.  We keep
1922  * pseudoconstant clauses in the same lists as other RestrictInfos so that
1923  * the regular clause-pushing machinery can assign them to the correct join
1924  * level, but they need to be treated specially for cost and selectivity
1925  * estimates.  Note that a pseudoconstant clause can never be an indexqual
1926  * or merge or hash join clause, so it's of no interest to large parts of
1927  * the planner.
1928  *
1929  * When join clauses are generated from EquivalenceClasses, there may be
1930  * several equally valid ways to enforce join equivalence, of which we need
1931  * apply only one.  We mark clauses of this kind by setting parent_ec to
1932  * point to the generating EquivalenceClass.  Multiple clauses with the same
1933  * parent_ec in the same join are redundant.
1934  */
1935 
1936 typedef struct RestrictInfo
1937 {
1938 	NodeTag		type;
1939 
1940 	Expr	   *clause;			/* the represented clause of WHERE or JOIN */
1941 
1942 	bool		is_pushed_down; /* true if clause was pushed down in level */
1943 
1944 	bool		outerjoin_delayed;	/* true if delayed by lower outer join */
1945 
1946 	bool		can_join;		/* see comment above */
1947 
1948 	bool		pseudoconstant; /* see comment above */
1949 
1950 	bool		leakproof;		/* true if known to contain no leaked Vars */
1951 
1952 	Index		security_level; /* see comment above */
1953 
1954 	/* The set of relids (varnos) actually referenced in the clause: */
1955 	Relids		clause_relids;
1956 
1957 	/* The set of relids required to evaluate the clause: */
1958 	Relids		required_relids;
1959 
1960 	/* If an outer-join clause, the outer-side relations, else NULL: */
1961 	Relids		outer_relids;
1962 
1963 	/* The relids used in the clause that are nullable by lower outer joins: */
1964 	Relids		nullable_relids;
1965 
1966 	/* These fields are set for any binary opclause: */
1967 	Relids		left_relids;	/* relids in left side of clause */
1968 	Relids		right_relids;	/* relids in right side of clause */
1969 
1970 	/* This field is NULL unless clause is an OR clause: */
1971 	Expr	   *orclause;		/* modified clause with RestrictInfos */
1972 
1973 	/* This field is NULL unless clause is potentially redundant: */
1974 	EquivalenceClass *parent_ec;	/* generating EquivalenceClass */
1975 
1976 	/* cache space for cost and selectivity */
1977 	QualCost	eval_cost;		/* eval cost of clause; -1 if not yet set */
1978 	Selectivity norm_selec;		/* selectivity for "normal" (JOIN_INNER)
1979 								 * semantics; -1 if not yet set; >1 means a
1980 								 * redundant clause */
1981 	Selectivity outer_selec;	/* selectivity for outer join semantics; -1 if
1982 								 * not yet set */
1983 
1984 	/* valid if clause is mergejoinable, else NIL */
1985 	List	   *mergeopfamilies;	/* opfamilies containing clause operator */
1986 
1987 	/* cache space for mergeclause processing; NULL if not yet set */
1988 	EquivalenceClass *left_ec;	/* EquivalenceClass containing lefthand */
1989 	EquivalenceClass *right_ec; /* EquivalenceClass containing righthand */
1990 	EquivalenceMember *left_em; /* EquivalenceMember for lefthand */
1991 	EquivalenceMember *right_em;	/* EquivalenceMember for righthand */
1992 	List	   *scansel_cache;	/* list of MergeScanSelCache structs */
1993 
1994 	/* transient workspace for use while considering a specific join path */
1995 	bool		outer_is_left;	/* T = outer var on left, F = on right */
1996 
1997 	/* valid if clause is hashjoinable, else InvalidOid: */
1998 	Oid			hashjoinoperator;	/* copy of clause operator */
1999 
2000 	/* cache space for hashclause processing; -1 if not yet set */
2001 	Selectivity left_bucketsize;	/* avg bucketsize of left side */
2002 	Selectivity right_bucketsize;	/* avg bucketsize of right side */
2003 	Selectivity left_mcvfreq;	/* left side's most common val's freq */
2004 	Selectivity right_mcvfreq;	/* right side's most common val's freq */
2005 } RestrictInfo;
2006 
2007 /*
2008  * This macro embodies the correct way to test whether a RestrictInfo is
2009  * "pushed down" to a given outer join, that is, should be treated as a filter
2010  * clause rather than a join clause at that outer join.  This is certainly so
2011  * if is_pushed_down is true; but examining that is not sufficient anymore,
2012  * because outer-join clauses will get pushed down to lower outer joins when
2013  * we generate a path for the lower outer join that is parameterized by the
2014  * LHS of the upper one.  We can detect such a clause by noting that its
2015  * required_relids exceed the scope of the join.
2016  */
2017 #define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids) \
2018 	((rinfo)->is_pushed_down || \
2019 	 !bms_is_subset((rinfo)->required_relids, joinrelids))
2020 
2021 /*
2022  * Since mergejoinscansel() is a relatively expensive function, and would
2023  * otherwise be invoked many times while planning a large join tree,
2024  * we go out of our way to cache its results.  Each mergejoinable
2025  * RestrictInfo carries a list of the specific sort orderings that have
2026  * been considered for use with it, and the resulting selectivities.
2027  */
2028 typedef struct MergeScanSelCache
2029 {
2030 	/* Ordering details (cache lookup key) */
2031 	Oid			opfamily;		/* btree opfamily defining the ordering */
2032 	Oid			collation;		/* collation for the ordering */
2033 	int			strategy;		/* sort direction (ASC or DESC) */
2034 	bool		nulls_first;	/* do NULLs come before normal values? */
2035 	/* Results */
2036 	Selectivity leftstartsel;	/* first-join fraction for clause left side */
2037 	Selectivity leftendsel;		/* last-join fraction for clause left side */
2038 	Selectivity rightstartsel;	/* first-join fraction for clause right side */
2039 	Selectivity rightendsel;	/* last-join fraction for clause right side */
2040 } MergeScanSelCache;
2041 
2042 /*
2043  * Placeholder node for an expression to be evaluated below the top level
2044  * of a plan tree.  This is used during planning to represent the contained
2045  * expression.  At the end of the planning process it is replaced by either
2046  * the contained expression or a Var referring to a lower-level evaluation of
2047  * the contained expression.  Typically the evaluation occurs below an outer
2048  * join, and Var references above the outer join might thereby yield NULL
2049  * instead of the expression value.
2050  *
2051  * Although the planner treats this as an expression node type, it is not
2052  * recognized by the parser or executor, so we declare it here rather than
2053  * in primnodes.h.
2054  */
2055 
2056 typedef struct PlaceHolderVar
2057 {
2058 	Expr		xpr;
2059 	Expr	   *phexpr;			/* the represented expression */
2060 	Relids		phrels;			/* base relids syntactically within expr src */
2061 	Index		phid;			/* ID for PHV (unique within planner run) */
2062 	Index		phlevelsup;		/* > 0 if PHV belongs to outer query */
2063 } PlaceHolderVar;
2064 
2065 /*
2066  * "Special join" info.
2067  *
2068  * One-sided outer joins constrain the order of joining partially but not
2069  * completely.  We flatten such joins into the planner's top-level list of
2070  * relations to join, but record information about each outer join in a
2071  * SpecialJoinInfo struct.  These structs are kept in the PlannerInfo node's
2072  * join_info_list.
2073  *
2074  * Similarly, semijoins and antijoins created by flattening IN (subselect)
2075  * and EXISTS(subselect) clauses create partial constraints on join order.
2076  * These are likewise recorded in SpecialJoinInfo structs.
2077  *
2078  * We make SpecialJoinInfos for FULL JOINs even though there is no flexibility
2079  * of planning for them, because this simplifies make_join_rel()'s API.
2080  *
2081  * min_lefthand and min_righthand are the sets of base relids that must be
2082  * available on each side when performing the special join.  lhs_strict is
2083  * true if the special join's condition cannot succeed when the LHS variables
2084  * are all NULL (this means that an outer join can commute with upper-level
2085  * outer joins even if it appears in their RHS).  We don't bother to set
2086  * lhs_strict for FULL JOINs, however.
2087  *
2088  * It is not valid for either min_lefthand or min_righthand to be empty sets;
2089  * if they were, this would break the logic that enforces join order.
2090  *
2091  * syn_lefthand and syn_righthand are the sets of base relids that are
2092  * syntactically below this special join.  (These are needed to help compute
2093  * min_lefthand and min_righthand for higher joins.)
2094  *
2095  * delay_upper_joins is set true if we detect a pushed-down clause that has
2096  * to be evaluated after this join is formed (because it references the RHS).
2097  * Any outer joins that have such a clause and this join in their RHS cannot
2098  * commute with this join, because that would leave noplace to check the
2099  * pushed-down clause.  (We don't track this for FULL JOINs, either.)
2100  *
2101  * For a semijoin, we also extract the join operators and their RHS arguments
2102  * and set semi_operators, semi_rhs_exprs, semi_can_btree, and semi_can_hash.
2103  * This is done in support of possibly unique-ifying the RHS, so we don't
2104  * bother unless at least one of semi_can_btree and semi_can_hash can be set
2105  * true.  (You might expect that this information would be computed during
2106  * join planning; but it's helpful to have it available during planning of
2107  * parameterized table scans, so we store it in the SpecialJoinInfo structs.)
2108  *
2109  * jointype is never JOIN_RIGHT; a RIGHT JOIN is handled by switching
2110  * the inputs to make it a LEFT JOIN.  So the allowed values of jointype
2111  * in a join_info_list member are only LEFT, FULL, SEMI, or ANTI.
2112  *
2113  * For purposes of join selectivity estimation, we create transient
2114  * SpecialJoinInfo structures for regular inner joins; so it is possible
2115  * to have jointype == JOIN_INNER in such a structure, even though this is
2116  * not allowed within join_info_list.  We also create transient
2117  * SpecialJoinInfos with jointype == JOIN_INNER for outer joins, since for
2118  * cost estimation purposes it is sometimes useful to know the join size under
2119  * plain innerjoin semantics.  Note that lhs_strict, delay_upper_joins, and
2120  * of course the semi_xxx fields are not set meaningfully within such structs.
2121  */
2122 #ifndef HAVE_SPECIALJOININFO_TYPEDEF
2123 typedef struct SpecialJoinInfo SpecialJoinInfo;
2124 #define HAVE_SPECIALJOININFO_TYPEDEF 1
2125 #endif
2126 
2127 struct SpecialJoinInfo
2128 {
2129 	NodeTag		type;
2130 	Relids		min_lefthand;	/* base relids in minimum LHS for join */
2131 	Relids		min_righthand;	/* base relids in minimum RHS for join */
2132 	Relids		syn_lefthand;	/* base relids syntactically within LHS */
2133 	Relids		syn_righthand;	/* base relids syntactically within RHS */
2134 	JoinType	jointype;		/* always INNER, LEFT, FULL, SEMI, or ANTI */
2135 	bool		lhs_strict;		/* joinclause is strict for some LHS rel */
2136 	bool		delay_upper_joins;	/* can't commute with upper RHS */
2137 	/* Remaining fields are set only for JOIN_SEMI jointype: */
2138 	bool		semi_can_btree; /* true if semi_operators are all btree */
2139 	bool		semi_can_hash;	/* true if semi_operators are all hash */
2140 	List	   *semi_operators; /* OIDs of equality join operators */
2141 	List	   *semi_rhs_exprs; /* righthand-side expressions of these ops */
2142 };
2143 
2144 /*
2145  * Append-relation info.
2146  *
2147  * When we expand an inheritable table or a UNION-ALL subselect into an
2148  * "append relation" (essentially, a list of child RTEs), we build an
2149  * AppendRelInfo for each child RTE.  The list of AppendRelInfos indicates
2150  * which child RTEs must be included when expanding the parent, and each node
2151  * carries information needed to translate Vars referencing the parent into
2152  * Vars referencing that child.
2153  *
2154  * These structs are kept in the PlannerInfo node's append_rel_list.
2155  * Note that we just throw all the structs into one list, and scan the
2156  * whole list when desiring to expand any one parent.  We could have used
2157  * a more complex data structure (eg, one list per parent), but this would
2158  * be harder to update during operations such as pulling up subqueries,
2159  * and not really any easier to scan.  Considering that typical queries
2160  * will not have many different append parents, it doesn't seem worthwhile
2161  * to complicate things.
2162  *
2163  * Note: after completion of the planner prep phase, any given RTE is an
2164  * append parent having entries in append_rel_list if and only if its
2165  * "inh" flag is set.  We clear "inh" for plain tables that turn out not
2166  * to have inheritance children, and (in an abuse of the original meaning
2167  * of the flag) we set "inh" for subquery RTEs that turn out to be
2168  * flattenable UNION ALL queries.  This lets us avoid useless searches
2169  * of append_rel_list.
2170  *
2171  * Note: the data structure assumes that append-rel members are single
2172  * baserels.  This is OK for inheritance, but it prevents us from pulling
2173  * up a UNION ALL member subquery if it contains a join.  While that could
2174  * be fixed with a more complex data structure, at present there's not much
2175  * point because no improvement in the plan could result.
2176  */
2177 
2178 typedef struct AppendRelInfo
2179 {
2180 	NodeTag		type;
2181 
2182 	/*
2183 	 * These fields uniquely identify this append relationship.  There can be
2184 	 * (in fact, always should be) multiple AppendRelInfos for the same
2185 	 * parent_relid, but never more than one per child_relid, since a given
2186 	 * RTE cannot be a child of more than one append parent.
2187 	 */
2188 	Index		parent_relid;	/* RT index of append parent rel */
2189 	Index		child_relid;	/* RT index of append child rel */
2190 
2191 	/*
2192 	 * For an inheritance appendrel, the parent and child are both regular
2193 	 * relations, and we store their rowtype OIDs here for use in translating
2194 	 * whole-row Vars.  For a UNION-ALL appendrel, the parent and child are
2195 	 * both subqueries with no named rowtype, and we store InvalidOid here.
2196 	 */
2197 	Oid			parent_reltype; /* OID of parent's composite type */
2198 	Oid			child_reltype;	/* OID of child's composite type */
2199 
2200 	/*
2201 	 * The N'th element of this list is a Var or expression representing the
2202 	 * child column corresponding to the N'th column of the parent. This is
2203 	 * used to translate Vars referencing the parent rel into references to
2204 	 * the child.  A list element is NULL if it corresponds to a dropped
2205 	 * column of the parent (this is only possible for inheritance cases, not
2206 	 * UNION ALL).  The list elements are always simple Vars for inheritance
2207 	 * cases, but can be arbitrary expressions in UNION ALL cases.
2208 	 *
2209 	 * Notice we only store entries for user columns (attno > 0).  Whole-row
2210 	 * Vars are special-cased, and system columns (attno < 0) need no special
2211 	 * translation since their attnos are the same for all tables.
2212 	 *
2213 	 * Caution: the Vars have varlevelsup = 0.  Be careful to adjust as needed
2214 	 * when copying into a subquery.
2215 	 */
2216 	List	   *translated_vars;	/* Expressions in the child's Vars */
2217 
2218 	/*
2219 	 * We store the parent table's OID here for inheritance, or InvalidOid for
2220 	 * UNION ALL.  This is only needed to help in generating error messages if
2221 	 * an attempt is made to reference a dropped parent column.
2222 	 */
2223 	Oid			parent_reloid;	/* OID of parent relation */
2224 } AppendRelInfo;
2225 
2226 /*
2227  * For each distinct placeholder expression generated during planning, we
2228  * store a PlaceHolderInfo node in the PlannerInfo node's placeholder_list.
2229  * This stores info that is needed centrally rather than in each copy of the
2230  * PlaceHolderVar.  The phid fields identify which PlaceHolderInfo goes with
2231  * each PlaceHolderVar.  Note that phid is unique throughout a planner run,
2232  * not just within a query level --- this is so that we need not reassign ID's
2233  * when pulling a subquery into its parent.
2234  *
2235  * The idea is to evaluate the expression at (only) the ph_eval_at join level,
2236  * then allow it to bubble up like a Var until the ph_needed join level.
2237  * ph_needed has the same definition as attr_needed for a regular Var.
2238  *
2239  * The PlaceHolderVar's expression might contain LATERAL references to vars
2240  * coming from outside its syntactic scope.  If so, those rels are *not*
2241  * included in ph_eval_at, but they are recorded in ph_lateral.
2242  *
2243  * Notice that when ph_eval_at is a join rather than a single baserel, the
2244  * PlaceHolderInfo may create constraints on join order: the ph_eval_at join
2245  * has to be formed below any outer joins that should null the PlaceHolderVar.
2246  *
2247  * We create a PlaceHolderInfo only after determining that the PlaceHolderVar
2248  * is actually referenced in the plan tree, so that unreferenced placeholders
2249  * don't result in unnecessary constraints on join order.
2250  */
2251 
2252 typedef struct PlaceHolderInfo
2253 {
2254 	NodeTag		type;
2255 
2256 	Index		phid;			/* ID for PH (unique within planner run) */
2257 	PlaceHolderVar *ph_var;		/* copy of PlaceHolderVar tree */
2258 	Relids		ph_eval_at;		/* lowest level we can evaluate value at */
2259 	Relids		ph_lateral;		/* relids of contained lateral refs, if any */
2260 	Relids		ph_needed;		/* highest level the value is needed at */
2261 	int32		ph_width;		/* estimated attribute width */
2262 } PlaceHolderInfo;
2263 
2264 /*
2265  * This struct describes one potentially index-optimizable MIN/MAX aggregate
2266  * function.  MinMaxAggPath contains a list of these, and if we accept that
2267  * path, the list is stored into root->minmax_aggs for use during setrefs.c.
2268  */
2269 typedef struct MinMaxAggInfo
2270 {
2271 	NodeTag		type;
2272 
2273 	Oid			aggfnoid;		/* pg_proc Oid of the aggregate */
2274 	Oid			aggsortop;		/* Oid of its sort operator */
2275 	Expr	   *target;			/* expression we are aggregating on */
2276 	PlannerInfo *subroot;		/* modified "root" for planning the subquery */
2277 	Path	   *path;			/* access path for subquery */
2278 	Cost		pathcost;		/* estimated cost to fetch first row */
2279 	Param	   *param;			/* param for subplan's output */
2280 } MinMaxAggInfo;
2281 
2282 /*
2283  * At runtime, PARAM_EXEC slots are used to pass values around from one plan
2284  * node to another.  They can be used to pass values down into subqueries (for
2285  * outer references in subqueries), or up out of subqueries (for the results
2286  * of a subplan), or from a NestLoop plan node into its inner relation (when
2287  * the inner scan is parameterized with values from the outer relation).
2288  * The planner is responsible for assigning nonconflicting PARAM_EXEC IDs to
2289  * the PARAM_EXEC Params it generates.
2290  *
2291  * Outer references are managed via root->plan_params, which is a list of
2292  * PlannerParamItems.  While planning a subquery, each parent query level's
2293  * plan_params contains the values required from it by the current subquery.
2294  * During create_plan(), we use plan_params to track values that must be
2295  * passed from outer to inner sides of NestLoop plan nodes.
2296  *
2297  * The item a PlannerParamItem represents can be one of three kinds:
2298  *
2299  * A Var: the slot represents a variable of this level that must be passed
2300  * down because subqueries have outer references to it, or must be passed
2301  * from a NestLoop node to its inner scan.  The varlevelsup value in the Var
2302  * will always be zero.
2303  *
2304  * A PlaceHolderVar: this works much like the Var case, except that the
2305  * entry is a PlaceHolderVar node with a contained expression.  The PHV
2306  * will have phlevelsup = 0, and the contained expression is adjusted
2307  * to match in level.
2308  *
2309  * An Aggref (with an expression tree representing its argument): the slot
2310  * represents an aggregate expression that is an outer reference for some
2311  * subquery.  The Aggref itself has agglevelsup = 0, and its argument tree
2312  * is adjusted to match in level.
2313  *
2314  * Note: we detect duplicate Var and PlaceHolderVar parameters and coalesce
2315  * them into one slot, but we do not bother to do that for Aggrefs.
2316  * The scope of duplicate-elimination only extends across the set of
2317  * parameters passed from one query level into a single subquery, or for
2318  * nestloop parameters across the set of nestloop parameters used in a single
2319  * query level.  So there is no possibility of a PARAM_EXEC slot being used
2320  * for conflicting purposes.
2321  *
2322  * In addition, PARAM_EXEC slots are assigned for Params representing outputs
2323  * from subplans (values that are setParam items for those subplans).  These
2324  * IDs need not be tracked via PlannerParamItems, since we do not need any
2325  * duplicate-elimination nor later processing of the represented expressions.
2326  * Instead, we just record the assignment of the slot number by appending to
2327  * root->glob->paramExecTypes.
2328  */
2329 typedef struct PlannerParamItem
2330 {
2331 	NodeTag		type;
2332 
2333 	Node	   *item;			/* the Var, PlaceHolderVar, or Aggref */
2334 	int			paramId;		/* its assigned PARAM_EXEC slot number */
2335 } PlannerParamItem;
2336 
2337 /*
2338  * When making cost estimates for a SEMI/ANTI/inner_unique join, there are
2339  * some correction factors that are needed in both nestloop and hash joins
2340  * to account for the fact that the executor can stop scanning inner rows
2341  * as soon as it finds a match to the current outer row.  These numbers
2342  * depend only on the selected outer and inner join relations, not on the
2343  * particular paths used for them, so it's worthwhile to calculate them
2344  * just once per relation pair not once per considered path.  This struct
2345  * is filled by compute_semi_anti_join_factors and must be passed along
2346  * to the join cost estimation functions.
2347  *
2348  * outer_match_frac is the fraction of the outer tuples that are
2349  *		expected to have at least one match.
2350  * match_count is the average number of matches expected for
2351  *		outer tuples that have at least one match.
2352  */
2353 typedef struct SemiAntiJoinFactors
2354 {
2355 	Selectivity outer_match_frac;
2356 	Selectivity match_count;
2357 } SemiAntiJoinFactors;
2358 
2359 /*
2360  * Struct for extra information passed to subroutines of add_paths_to_joinrel
2361  *
2362  * restrictlist contains all of the RestrictInfo nodes for restriction
2363  *		clauses that apply to this join
2364  * mergeclause_list is a list of RestrictInfo nodes for available
2365  *		mergejoin clauses in this join
2366  * inner_unique is true if each outer tuple provably matches no more
2367  *		than one inner tuple
2368  * sjinfo is extra info about special joins for selectivity estimation
2369  * semifactors is as shown above (only valid for SEMI/ANTI/inner_unique joins)
2370  * param_source_rels are OK targets for parameterization of result paths
2371  */
2372 typedef struct JoinPathExtraData
2373 {
2374 	List	   *restrictlist;
2375 	List	   *mergeclause_list;
2376 	bool		inner_unique;
2377 	SpecialJoinInfo *sjinfo;
2378 	SemiAntiJoinFactors semifactors;
2379 	Relids		param_source_rels;
2380 } JoinPathExtraData;
2381 
2382 /*
2383  * Various flags indicating what kinds of grouping are possible.
2384  *
2385  * GROUPING_CAN_USE_SORT should be set if it's possible to perform
2386  * sort-based implementations of grouping.  When grouping sets are in use,
2387  * this will be true if sorting is potentially usable for any of the grouping
2388  * sets, even if it's not usable for all of them.
2389  *
2390  * GROUPING_CAN_USE_HASH should be set if it's possible to perform
2391  * hash-based implementations of grouping.
2392  *
2393  * GROUPING_CAN_PARTIAL_AGG should be set if the aggregation is of a type
2394  * for which we support partial aggregation (not, for example, grouping sets).
2395  * It says nothing about parallel-safety or the availability of suitable paths.
2396  */
2397 #define GROUPING_CAN_USE_SORT       0x0001
2398 #define GROUPING_CAN_USE_HASH       0x0002
2399 #define GROUPING_CAN_PARTIAL_AGG	0x0004
2400 
2401 /*
2402  * What kind of partitionwise aggregation is in use?
2403  *
2404  * PARTITIONWISE_AGGREGATE_NONE: Not used.
2405  *
2406  * PARTITIONWISE_AGGREGATE_FULL: Aggregate each partition separately, and
2407  * append the results.
2408  *
2409  * PARTITIONWISE_AGGREGATE_PARTIAL: Partially aggregate each partition
2410  * separately, append the results, and then finalize aggregation.
2411  */
2412 typedef enum
2413 {
2414 	PARTITIONWISE_AGGREGATE_NONE,
2415 	PARTITIONWISE_AGGREGATE_FULL,
2416 	PARTITIONWISE_AGGREGATE_PARTIAL
2417 } PartitionwiseAggregateType;
2418 
2419 /*
2420  * Struct for extra information passed to subroutines of create_grouping_paths
2421  *
2422  * flags indicating what kinds of grouping are possible.
2423  * partial_costs_set is true if the agg_partial_costs and agg_final_costs
2424  * 		have been initialized.
2425  * agg_partial_costs gives partial aggregation costs.
2426  * agg_final_costs gives finalization costs.
2427  * target_parallel_safe is true if target is parallel safe.
2428  * havingQual gives list of quals to be applied after aggregation.
2429  * targetList gives list of columns to be projected.
2430  * patype is the type of partitionwise aggregation that is being performed.
2431  */
2432 typedef struct
2433 {
2434 	/* Data which remains constant once set. */
2435 	int			flags;
2436 	bool		partial_costs_set;
2437 	AggClauseCosts agg_partial_costs;
2438 	AggClauseCosts agg_final_costs;
2439 
2440 	/* Data which may differ across partitions. */
2441 	bool		target_parallel_safe;
2442 	Node	   *havingQual;
2443 	List	   *targetList;
2444 	PartitionwiseAggregateType patype;
2445 } GroupPathExtraData;
2446 
2447 /*
2448  * Struct for extra information passed to subroutines of grouping_planner
2449  *
2450  * limit_needed is true if we actually need a Limit plan node.
2451  * limit_tuples is an estimated bound on the number of output tuples,
2452  *		or -1 if no LIMIT or couldn't estimate.
2453  * count_est and offset_est are the estimated values of the LIMIT and OFFSET
2454  * 		expressions computed by preprocess_limit() (see comments for
2455  * 		preprocess_limit() for more information).
2456  */
2457 typedef struct
2458 {
2459 	bool		limit_needed;
2460 	double		limit_tuples;
2461 	int64		count_est;
2462 	int64		offset_est;
2463 } FinalPathExtraData;
2464 
2465 /*
2466  * For speed reasons, cost estimation for join paths is performed in two
2467  * phases: the first phase tries to quickly derive a lower bound for the
2468  * join cost, and then we check if that's sufficient to reject the path.
2469  * If not, we come back for a more refined cost estimate.  The first phase
2470  * fills a JoinCostWorkspace struct with its preliminary cost estimates
2471  * and possibly additional intermediate values.  The second phase takes
2472  * these values as inputs to avoid repeating work.
2473  *
2474  * (Ideally we'd declare this in cost.h, but it's also needed in pathnode.h,
2475  * so seems best to put it here.)
2476  */
2477 typedef struct JoinCostWorkspace
2478 {
2479 	/* Preliminary cost estimates --- must not be larger than final ones! */
2480 	Cost		startup_cost;	/* cost expended before fetching any tuples */
2481 	Cost		total_cost;		/* total cost (assuming all tuples fetched) */
2482 
2483 	/* Fields below here should be treated as private to costsize.c */
2484 	Cost		run_cost;		/* non-startup cost components */
2485 
2486 	/* private for cost_nestloop code */
2487 	Cost		inner_run_cost; /* also used by cost_mergejoin code */
2488 	Cost		inner_rescan_run_cost;
2489 
2490 	/* private for cost_mergejoin code */
2491 	double		outer_rows;
2492 	double		inner_rows;
2493 	double		outer_skip_rows;
2494 	double		inner_skip_rows;
2495 
2496 	/* private for cost_hashjoin code */
2497 	int			numbuckets;
2498 	int			numbatches;
2499 	double		inner_rows_total;
2500 } JoinCostWorkspace;
2501 
2502 #endif							/* PATHNODES_H */
2503