1 /*-------------------------------------------------------------------------
4 * Definitions for planner's internal data structures.
7 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/include/nodes/relation.h
12 *-------------------------------------------------------------------------
17 #include "access/sdir.h"
18 #include "nodes/params.h"
19 #include "nodes/parsenodes.h"
20 #include "storage/block.h"
25 * Set of relation identifiers (indexes into the rangetable).
27 typedef Bitmapset *Relids;
30 * When looking for a "cheapest path", this enum specifies whether we want
31 * cheapest startup cost or cheapest total cost.
33 typedef enum CostSelector
35 STARTUP_COST, TOTAL_COST
39 * The cost estimate produced by cost_qual_eval() includes both a one-time
40 * (startup) cost, and a per-tuple cost.
42 typedef struct QualCost
44 Cost startup; /* one-time cost */
45 Cost per_tuple; /* per-evaluation cost */
49 * Costing aggregate function execution requires these statistics about
50 * the aggregates to be executed by a given Agg node. Note that transCost
51 * includes the execution costs of the aggregates' input expressions.
53 typedef struct AggClauseCosts
55 int numAggs; /* total number of aggregate functions */
56 int numOrderedAggs; /* number that use DISTINCT or ORDER BY */
57 QualCost transCost; /* total per-input-row execution costs */
58 Cost finalCost; /* total costs of agg final functions */
59 Size transitionSpace; /* space for pass-by-ref transition data */
65 * Global information for planning/optimization
67 * PlannerGlobal holds state for an entire planner invocation; this state
68 * is shared across all levels of sub-Queries that exist in the command being
72 typedef struct PlannerGlobal
76 ParamListInfo boundParams; /* Param values provided to planner() */
78 List *subplans; /* Plans for SubPlan nodes */
80 List *subroots; /* PlannerInfos for SubPlan nodes */
82 Bitmapset *rewindPlanIDs; /* indices of subplans that require REWIND */
84 List *finalrtable; /* "flat" rangetable for executor */
86 List *finalrowmarks; /* "flat" list of PlanRowMarks */
88 List *resultRelations; /* "flat" list of integer RT indexes */
90 List *relationOids; /* OIDs of relations the plan depends on */
92 List *invalItems; /* other dependencies, as PlanInvalItems */
94 int nParamExec; /* number of PARAM_EXEC Params used */
96 Index lastPHId; /* highest PlaceHolderVar ID assigned */
98 Index lastRowMarkId; /* highest PlanRowMark ID assigned */
100 bool transientPlan; /* redo plan when TransactionXmin changes? */
103 /* macro for fetching the Plan associated with a SubPlan node */
104 #define planner_subplan_get_plan(root, subplan) \
105 ((Plan *) list_nth((root)->glob->subplans, (subplan)->plan_id - 1))
110 * Per-query information for planning/optimization
112 * This struct is conventionally called "root" in all the planner routines.
113 * It holds links to all of the planner's working state, in addition to the
114 * original Query. Note that at present the planner extensively modifies
115 * the passed-in Query data structure; someday that should stop.
118 typedef struct PlannerInfo
122 Query *parse; /* the Query being planned */
124 PlannerGlobal *glob; /* global info for current planner run */
126 Index query_level; /* 1 at the outermost Query */
128 struct PlannerInfo *parent_root; /* NULL at outermost Query */
130 List *plan_params; /* list of PlannerParamItems, see below */
133 * simple_rel_array holds pointers to "base rels" and "other rels" (see
134 * comments for RelOptInfo for more info). It is indexed by rangetable
135 * index (so entry 0 is always wasted). Entries can be NULL when an RTE
136 * does not correspond to a base relation, such as a join RTE or an
137 * unreferenced view RTE; or if the RelOptInfo hasn't been made yet.
139 struct RelOptInfo **simple_rel_array; /* All 1-rel RelOptInfos */
140 int simple_rel_array_size; /* allocated size of array */
143 * simple_rte_array is the same length as simple_rel_array and holds
144 * pointers to the associated rangetable entries. This lets us avoid
145 * rt_fetch(), which can be a bit slow once large inheritance sets have
148 RangeTblEntry **simple_rte_array; /* rangetable as an array */
151 * all_baserels is a Relids set of all base relids (but not "other"
152 * relids) in the query; that is, the Relids identifier of the final join
158 * join_rel_list is a list of all join-relation RelOptInfos we have
159 * considered in this planning run. For small problems we just scan the
160 * list to do lookups, but when there are many join relations we build a
161 * hash table for faster lookups. The hash table is present and valid
162 * when join_rel_hash is not NULL. Note that we still maintain the list
163 * even when using the hash table for lookups; this simplifies life for
166 List *join_rel_list; /* list of join-relation RelOptInfos */
167 struct HTAB *join_rel_hash; /* optional hashtable for join relations */
170 * When doing a dynamic-programming-style join search, join_rel_level[k]
171 * is a list of all join-relation RelOptInfos of level k, and
172 * join_cur_level is the current level. New join-relation RelOptInfos are
173 * automatically added to the join_rel_level[join_cur_level] list.
174 * join_rel_level is NULL if not in use.
176 List **join_rel_level; /* lists of join-relation RelOptInfos */
177 int join_cur_level; /* index of list being extended */
179 List *init_plans; /* init SubPlans for query */
181 List *cte_plan_ids; /* per-CTE-item list of subplan IDs */
183 List *eq_classes; /* list of active EquivalenceClasses */
185 List *canon_pathkeys; /* list of "canonical" PathKeys */
187 List *left_join_clauses; /* list of RestrictInfos for
188 * mergejoinable outer join clauses
189 * w/nonnullable var on left */
191 List *right_join_clauses; /* list of RestrictInfos for
192 * mergejoinable outer join clauses
193 * w/nonnullable var on right */
195 List *full_join_clauses; /* list of RestrictInfos for
196 * mergejoinable full join clauses */
198 List *join_info_list; /* list of SpecialJoinInfos */
200 List *lateral_info_list; /* list of LateralJoinInfos */
202 List *append_rel_list; /* list of AppendRelInfos */
204 List *rowMarks; /* list of PlanRowMarks */
206 List *placeholder_list; /* list of PlaceHolderInfos */
208 List *query_pathkeys; /* desired pathkeys for query_planner(), and
209 * actual pathkeys afterwards */
211 List *group_pathkeys; /* groupClause pathkeys, if any */
212 List *window_pathkeys; /* pathkeys of bottom window, if any */
213 List *distinct_pathkeys; /* distinctClause pathkeys, if any */
214 List *sort_pathkeys; /* sortClause pathkeys, if any */
216 List *minmax_aggs; /* List of MinMaxAggInfos */
218 List *initial_rels; /* RelOptInfos we are now trying to join */
220 MemoryContext planner_cxt; /* context holding PlannerInfo */
222 double total_table_pages; /* # of pages in all tables of query */
224 double tuple_fraction; /* tuple_fraction passed to query_planner */
225 double limit_tuples; /* limit_tuples passed to query_planner */
227 bool hasInheritedTarget; /* true if parse->resultRelation is an
228 * inheritance child rel */
229 bool hasJoinRTEs; /* true if any RTEs are RTE_JOIN kind */
230 bool hasLateralRTEs; /* true if any RTEs are marked LATERAL */
231 bool hasHavingQual; /* true if havingQual was non-null */
232 bool hasPseudoConstantQuals; /* true if any RestrictInfo has
233 * pseudoconstant = true */
234 bool hasRecursion; /* true if planning a recursive WITH item */
236 /* These fields are used only when hasRecursion is true: */
237 int wt_param_id; /* PARAM_EXEC ID for the work table */
238 struct Plan *non_recursive_plan; /* plan for non-recursive term */
240 /* These fields are workspace for createplan.c */
241 Relids curOuterRels; /* outer rels above current node */
242 List *curOuterParams; /* not-yet-assigned NestLoopParams */
244 /* optional private data for join_search_hook, e.g., GEQO */
245 void *join_search_private;
250 * In places where it's known that simple_rte_array[] must have been prepared
251 * already, we just index into it to fetch RTEs. In code that might be
252 * executed before or after entering query_planner(), use this macro.
254 #define planner_rt_fetch(rti, root) \
255 ((root)->simple_rte_array ? (root)->simple_rte_array[rti] : \
256 rt_fetch(rti, (root)->parse->rtable))
261 * Per-relation information for planning/optimization
263 * For planning purposes, a "base rel" is either a plain relation (a table)
264 * or the output of a sub-SELECT or function that appears in the range table.
265 * In either case it is uniquely identified by an RT index. A "joinrel"
266 * is the joining of two or more base rels. A joinrel is identified by
267 * the set of RT indexes for its component baserels. We create RelOptInfo
268 * nodes for each baserel and joinrel, and store them in the PlannerInfo's
269 * simple_rel_array and join_rel_list respectively.
271 * Note that there is only one joinrel for any given set of component
272 * baserels, no matter what order we assemble them in; so an unordered
273 * set is the right datatype to identify it with.
275 * We also have "other rels", which are like base rels in that they refer to
276 * single RT indexes; but they are not part of the join tree, and are given
277 * a different RelOptKind to identify them. Lastly, there is a RelOptKind
278 * for "dead" relations, which are base rels that we have proven we don't
279 * need to join after all.
281 * Currently the only kind of otherrels are those made for member relations
282 * of an "append relation", that is an inheritance set or UNION ALL subquery.
283 * An append relation has a parent RTE that is a base rel, which represents
284 * the entire append relation. The member RTEs are otherrels. The parent
285 * is present in the query join tree but the members are not. The member
286 * RTEs and otherrels are used to plan the scans of the individual tables or
287 * subqueries of the append set; then the parent baserel is given Append
288 * and/or MergeAppend paths comprising the best paths for the individual
289 * member rels. (See comments for AppendRelInfo for more information.)
291 * At one time we also made otherrels to represent join RTEs, for use in
292 * handling join alias Vars. Currently this is not needed because all join
293 * alias Vars are expanded to non-aliased form during preprocess_expression.
295 * Parts of this data structure are specific to various scan and join
296 * mechanisms. It didn't seem worth creating new node types for them.
298 * relids - Set of base-relation identifiers; it is a base relation
299 * if there is just one, a join relation if more than one
300 * rows - estimated number of tuples in the relation after restriction
301 * clauses have been applied (ie, output rows of a plan for it)
302 * width - avg. number of bytes per tuple in the relation after the
303 * appropriate projections have been done (ie, output width)
304 * consider_startup - true if there is any value in keeping paths for
305 * this rel on the basis of having cheap startup cost
306 * reltargetlist - List of Var and PlaceHolderVar nodes for the values
307 * we need to output from this relation.
308 * List is in no particular order, but all rels of an
309 * appendrel set must use corresponding orders.
310 * NOTE: in an appendrel child relation, may contain
311 * arbitrary expressions pulled up from a subquery!
312 * pathlist - List of Path nodes, one for each potentially useful
313 * method of generating the relation
314 * ppilist - ParamPathInfo nodes for parameterized Paths, if any
315 * cheapest_startup_path - the pathlist member with lowest startup cost
316 * (regardless of ordering) among the unparameterized paths;
317 * or NULL if there is no unparameterized path
318 * cheapest_total_path - the pathlist member with lowest total cost
319 * (regardless of ordering) among the unparameterized paths;
320 * or if there is no unparameterized path, the path with lowest
321 * total cost among the paths with minimum parameterization
322 * cheapest_unique_path - for caching cheapest path to produce unique
323 * (no duplicates) output from relation; NULL if not yet requested
324 * cheapest_parameterized_paths - best paths for their parameterizations;
325 * always includes cheapest_total_path, even if that's unparameterized
327 * If the relation is a base relation it will have these fields set:
329 * relid - RTE index (this is redundant with the relids field, but
330 * is provided for convenience of access)
331 * rtekind - distinguishes plain relation, subquery, or function RTE
332 * min_attr, max_attr - range of valid AttrNumbers for rel
333 * attr_needed - array of bitmapsets indicating the highest joinrel
334 * in which each attribute is needed; if bit 0 is set then
335 * the attribute is needed as part of final targetlist
336 * attr_widths - cache space for per-attribute width estimates;
337 * zero means not computed yet
338 * lateral_vars - lateral cross-references of rel, if any (list of
339 * Vars and PlaceHolderVars)
340 * lateral_relids - required outer rels for LATERAL, as a Relids set
341 * (for child rels this can be more than lateral_vars)
342 * indexlist - list of IndexOptInfo nodes for relation's indexes
343 * (always NIL if it's not a table)
344 * pages - number of disk pages in relation (zero if not a table)
345 * tuples - number of tuples in relation (not considering restrictions)
346 * allvisfrac - fraction of disk pages that are marked all-visible
347 * subplan - plan for subquery (NULL if it's not a subquery)
348 * subroot - PlannerInfo for subquery (NULL if it's not a subquery)
349 * subplan_params - list of PlannerParamItems to be passed to subquery
350 * fdwroutine - function hooks for FDW, if foreign table (else NULL)
351 * fdw_private - private state for FDW, if foreign table (else NULL)
353 * Note: for a subquery, tuples, subplan, subroot are not set immediately
354 * upon creation of the RelOptInfo object; they are filled in when
355 * set_subquery_pathlist processes the object. Likewise, fdwroutine
356 * and fdw_private are filled during initial path creation.
358 * For otherrels that are appendrel members, these fields are filled
359 * in just as for a baserel.
361 * The presence of the remaining fields depends on the restrictions
362 * and joins that the relation participates in:
364 * baserestrictinfo - List of RestrictInfo nodes, containing info about
365 * each non-join qualification clause in which this relation
366 * participates (only used for base rels)
367 * baserestrictcost - Estimated cost of evaluating the baserestrictinfo
368 * clauses at a single tuple (only used for base rels)
369 * joininfo - List of RestrictInfo nodes, containing info about each
370 * join clause in which this relation participates (but
371 * note this excludes clauses that might be derivable from
372 * EquivalenceClasses)
373 * has_eclass_joins - flag that EquivalenceClass joins are possible
375 * Note: Keeping a restrictinfo list in the RelOptInfo is useful only for
376 * base rels, because for a join rel the set of clauses that are treated as
377 * restrict clauses varies depending on which sub-relations we choose to join.
378 * (For example, in a 3-base-rel join, a clause relating rels 1 and 2 must be
379 * treated as a restrictclause if we join {1} and {2 3} to make {1 2 3}; but
380 * if we join {1 2} and {3} then that clause will be a restrictclause in {1 2}
381 * and should not be processed again at the level of {1 2 3}.) Therefore,
382 * the restrictinfo list in the join case appears in individual JoinPaths
383 * (field joinrestrictinfo), not in the parent relation. But it's OK for
384 * the RelOptInfo to store the joininfo list, because that is the same
385 * for a given rel no matter how we form it.
387 * We store baserestrictcost in the RelOptInfo (for base relations) because
388 * we know we will need it at least once (to price the sequential scan)
389 * and may need it multiple times to price index scans.
392 typedef enum RelOptKind
396 RELOPT_OTHER_MEMBER_REL,
400 typedef struct RelOptInfo
404 RelOptKind reloptkind;
406 /* all relations included in this RelOptInfo */
407 Relids relids; /* set of base relids (rangetable indexes) */
409 /* size estimates generated by planner */
410 double rows; /* estimated number of result tuples */
411 int width; /* estimated avg width of result tuples */
413 /* per-relation planner control flags */
414 bool consider_startup; /* keep cheap-startup-cost paths? */
416 /* materialization information */
417 List *reltargetlist; /* Vars to be output by scan of relation */
418 List *pathlist; /* Path structures */
419 List *ppilist; /* ParamPathInfos used in pathlist */
420 struct Path *cheapest_startup_path;
421 struct Path *cheapest_total_path;
422 struct Path *cheapest_unique_path;
423 List *cheapest_parameterized_paths;
425 /* information about a base rel (not set for join rels!) */
427 Oid reltablespace; /* containing tablespace */
428 RTEKind rtekind; /* RELATION, SUBQUERY, or FUNCTION */
429 AttrNumber min_attr; /* smallest attrno of rel (often <0) */
430 AttrNumber max_attr; /* largest attrno of rel */
431 Relids *attr_needed; /* array indexed [min_attr .. max_attr] */
432 int32 *attr_widths; /* array indexed [min_attr .. max_attr] */
433 List *lateral_vars; /* LATERAL Vars and PHVs referenced by rel */
434 Relids lateral_relids; /* minimum parameterization of rel */
435 List *indexlist; /* list of IndexOptInfo */
436 BlockNumber pages; /* size estimates derived from pg_class */
439 /* use "struct Plan" to avoid including plannodes.h here */
440 struct Plan *subplan; /* if subquery */
441 PlannerInfo *subroot; /* if subquery */
442 List *subplan_params; /* if subquery */
443 /* use "struct FdwRoutine" to avoid including fdwapi.h here */
444 struct FdwRoutine *fdwroutine; /* if foreign table */
445 void *fdw_private; /* if foreign table */
447 /* used by various scans and joins: */
448 List *baserestrictinfo; /* RestrictInfo structures (if base
450 QualCost baserestrictcost; /* cost of evaluating the above */
451 List *joininfo; /* RestrictInfo structures for join clauses
452 * involving this rel */
453 bool has_eclass_joins; /* T means joininfo is incomplete */
458 * Per-index information for planning/optimization
460 * indexkeys[], indexcollations[], opfamily[], and opcintype[]
461 * each have ncolumns entries.
463 * sortopfamily[], reverse_sort[], and nulls_first[] likewise have
464 * ncolumns entries, if the index is ordered; but if it is unordered,
465 * those pointers are NULL.
467 * Zeroes in the indexkeys[] array indicate index columns that are
468 * expressions; there is one element in indexprs for each such column.
470 * For an ordered index, reverse_sort[] and nulls_first[] describe the
471 * sort ordering of a forward indexscan; we can also consider a backward
472 * indexscan, which will generate the reverse ordering.
474 * The indexprs and indpred expressions have been run through
475 * prepqual.c and eval_const_expressions() for ease of matching to
476 * WHERE clauses. indpred is in implicit-AND form.
478 * indextlist is a TargetEntry list representing the index columns.
479 * It provides an equivalent base-relation Var for each simple column,
480 * and links to the matching indexprs element for each expression column.
482 typedef struct IndexOptInfo
486 Oid indexoid; /* OID of the index relation */
487 Oid reltablespace; /* tablespace of index (not table) */
488 RelOptInfo *rel; /* back-link to index's table */
490 /* statistics from pg_class */
491 BlockNumber pages; /* number of disk pages in index */
492 double tuples; /* number of index tuples in index */
494 /* index descriptor information */
495 int ncolumns; /* number of columns in index */
496 int *indexkeys; /* column numbers of index's keys, or 0 */
497 Oid *indexcollations; /* OIDs of collations of index columns */
498 Oid *opfamily; /* OIDs of operator families for columns */
499 Oid *opcintype; /* OIDs of opclass declared input data types */
500 Oid *sortopfamily; /* OIDs of btree opfamilies, if orderable */
501 bool *reverse_sort; /* is sort order descending? */
502 bool *nulls_first; /* do NULLs come first in the sort order? */
503 Oid relam; /* OID of the access method (in pg_am) */
505 RegProcedure amcostestimate; /* OID of the access method's cost fcn */
507 List *indexprs; /* expressions for non-simple index columns */
508 List *indpred; /* predicate if a partial index, else NIL */
510 List *indextlist; /* targetlist representing index columns */
512 bool predOK; /* true if predicate matches query */
513 bool unique; /* true if a unique index */
514 bool immediate; /* is uniqueness enforced immediately? */
515 bool hypothetical; /* true if index doesn't really exist */
516 bool canreturn; /* can index return IndexTuples? */
517 bool amcanorderbyop; /* does AM support order by operator result? */
518 bool amoptionalkey; /* can query omit key for the first column? */
519 bool amsearcharray; /* can AM handle ScalarArrayOpExpr quals? */
520 bool amsearchnulls; /* can AM search for NULL/NOT NULL entries? */
521 bool amhasgettuple; /* does AM have amgettuple interface? */
522 bool amhasgetbitmap; /* does AM have amgetbitmap interface? */
529 * Whenever we can determine that a mergejoinable equality clause A = B is
530 * not delayed by any outer join, we create an EquivalenceClass containing
531 * the expressions A and B to record this knowledge. If we later find another
532 * equivalence B = C, we add C to the existing EquivalenceClass; this may
533 * require merging two existing EquivalenceClasses. At the end of the qual
534 * distribution process, we have sets of values that are known all transitively
535 * equal to each other, where "equal" is according to the rules of the btree
536 * operator family(s) shown in ec_opfamilies, as well as the collation shown
537 * by ec_collation. (We restrict an EC to contain only equalities whose
538 * operators belong to the same set of opfamilies. This could probably be
539 * relaxed, but for now it's not worth the trouble, since nearly all equality
540 * operators belong to only one btree opclass anyway. Similarly, we suppose
541 * that all or none of the input datatypes are collatable, so that a single
542 * collation value is sufficient.)
544 * We also use EquivalenceClasses as the base structure for PathKeys, letting
545 * us represent knowledge about different sort orderings being equivalent.
546 * Since every PathKey must reference an EquivalenceClass, we will end up
547 * with single-member EquivalenceClasses whenever a sort key expression has
548 * not been equivalenced to anything else. It is also possible that such an
549 * EquivalenceClass will contain a volatile expression ("ORDER BY random()"),
550 * which is a case that can't arise otherwise since clauses containing
551 * volatile functions are never considered mergejoinable. We mark such
552 * EquivalenceClasses specially to prevent them from being merged with
553 * ordinary EquivalenceClasses. Also, for volatile expressions we have
554 * to be careful to match the EquivalenceClass to the correct targetlist
555 * entry: consider SELECT random() AS a, random() AS b ... ORDER BY b,a.
556 * So we record the SortGroupRef of the originating sort clause.
558 * We allow equality clauses appearing below the nullable side of an outer join
559 * to form EquivalenceClasses, but these have a slightly different meaning:
560 * the included values might be all NULL rather than all the same non-null
561 * values. See src/backend/optimizer/README for more on that point.
563 * NB: if ec_merged isn't NULL, this class has been merged into another, and
564 * should be ignored in favor of using the pointed-to class.
566 typedef struct EquivalenceClass
570 List *ec_opfamilies; /* btree operator family OIDs */
571 Oid ec_collation; /* collation, if datatypes are collatable */
572 List *ec_members; /* list of EquivalenceMembers */
573 List *ec_sources; /* list of generating RestrictInfos */
574 List *ec_derives; /* list of derived RestrictInfos */
575 Relids ec_relids; /* all relids appearing in ec_members */
576 bool ec_has_const; /* any pseudoconstants in ec_members? */
577 bool ec_has_volatile; /* the (sole) member is a volatile expr */
578 bool ec_below_outer_join; /* equivalence applies below an OJ */
579 bool ec_broken; /* failed to generate needed clauses? */
580 Index ec_sortref; /* originating sortclause label, or 0 */
581 struct EquivalenceClass *ec_merged; /* set if merged into another EC */
585 * If an EC contains a const and isn't below-outer-join, any PathKey depending
586 * on it must be redundant, since there's only one possible value of the key.
588 #define EC_MUST_BE_REDUNDANT(eclass) \
589 ((eclass)->ec_has_const && !(eclass)->ec_below_outer_join)
592 * EquivalenceMember - one member expression of an EquivalenceClass
594 * em_is_child signifies that this element was built by transposing a member
595 * for an appendrel parent relation to represent the corresponding expression
596 * for an appendrel child. These members are used for determining the
597 * pathkeys of scans on the child relation and for explicitly sorting the
598 * child when necessary to build a MergeAppend path for the whole appendrel
599 * tree. An em_is_child member has no impact on the properties of the EC as a
600 * whole; in particular the EC's ec_relids field does NOT include the child
601 * relation. An em_is_child member should never be marked em_is_const nor
602 * cause ec_has_const or ec_has_volatile to be set, either. Thus, em_is_child
603 * members are not really full-fledged members of the EC, but just reflections
604 * or doppelgangers of real members. Most operations on EquivalenceClasses
605 * should ignore em_is_child members, and those that don't should test
606 * em_relids to make sure they only consider relevant members.
608 * em_datatype is usually the same as exprType(em_expr), but can be
609 * different when dealing with a binary-compatible opfamily; in particular
610 * anyarray_ops would never work without this. Use em_datatype when
611 * looking up a specific btree operator to work with this expression.
613 typedef struct EquivalenceMember
617 Expr *em_expr; /* the expression represented */
618 Relids em_relids; /* all relids appearing in em_expr */
619 Relids em_nullable_relids; /* nullable by lower outer joins */
620 bool em_is_const; /* expression is pseudoconstant? */
621 bool em_is_child; /* derived version for a child relation? */
622 Oid em_datatype; /* the "nominal type" used by the opfamily */
628 * The sort ordering of a path is represented by a list of PathKey nodes.
629 * An empty list implies no known ordering. Otherwise the first item
630 * represents the primary sort key, the second the first secondary sort key,
631 * etc. The value being sorted is represented by linking to an
632 * EquivalenceClass containing that value and including pk_opfamily among its
633 * ec_opfamilies. The EquivalenceClass tells which collation to use, too.
634 * This is a convenient method because it makes it trivial to detect
635 * equivalent and closely-related orderings. (See optimizer/README for more
638 * Note: pk_strategy is either BTLessStrategyNumber (for ASC) or
639 * BTGreaterStrategyNumber (for DESC). We assume that all ordering-capable
640 * index types will use btree-compatible strategy numbers.
642 typedef struct PathKey
646 EquivalenceClass *pk_eclass; /* the value that is ordered */
647 Oid pk_opfamily; /* btree opfamily defining the ordering */
648 int pk_strategy; /* sort direction (ASC or DESC) */
649 bool pk_nulls_first; /* do NULLs come before normal values? */
656 * All parameterized paths for a given relation with given required outer rels
657 * link to a single ParamPathInfo, which stores common information such as
658 * the estimated rowcount for this parameterization. We do this partly to
659 * avoid recalculations, but mostly to ensure that the estimated rowcount
660 * is in fact the same for every such path.
662 * Note: ppi_clauses is only used in ParamPathInfos for base relation paths;
663 * in join cases it's NIL because the set of relevant clauses varies depending
664 * on how the join is formed. The relevant clauses will appear in each
665 * parameterized join path's joinrestrictinfo list, instead.
667 typedef struct ParamPathInfo
671 Relids ppi_req_outer; /* rels supplying parameters used by path */
672 double ppi_rows; /* estimated number of result tuples */
673 List *ppi_clauses; /* join clauses available from outer rels */
678 * Type "Path" is used as-is for sequential-scan paths, as well as some other
679 * simple plan types that we don't need any extra information in the path for.
680 * For other path types it is the first component of a larger struct.
682 * "pathtype" is the NodeTag of the Plan node we could build from this Path.
683 * It is partially redundant with the Path's NodeTag, but allows us to use
684 * the same Path type for multiple Plan types when there is no need to
685 * distinguish the Plan type during path processing.
687 * "param_info", if not NULL, links to a ParamPathInfo that identifies outer
688 * relation(s) that provide parameter values to each scan of this path.
689 * That means this path can only be joined to those rels by means of nestloop
690 * joins with this path on the inside. Also note that a parameterized path
691 * is responsible for testing all "movable" joinclauses involving this rel
692 * and the specified outer rel(s).
694 * "rows" is the same as parent->rows in simple paths, but in parameterized
695 * paths and UniquePaths it can be less than parent->rows, reflecting the
696 * fact that we've filtered by extra join conditions or removed duplicates.
698 * "pathkeys" is a List of PathKey nodes (see above), describing the sort
699 * ordering of the path's output rows.
705 NodeTag pathtype; /* tag identifying scan/join method */
707 RelOptInfo *parent; /* the relation this path can build */
708 ParamPathInfo *param_info; /* parameterization info, or NULL if none */
710 /* estimated size/costs for path (see costsize.c for more info) */
711 double rows; /* estimated number of result tuples */
712 Cost startup_cost; /* cost expended before fetching any tuples */
713 Cost total_cost; /* total cost (assuming all tuples fetched) */
715 List *pathkeys; /* sort ordering of path's output */
716 /* pathkeys is a List of PathKey nodes; see above */
719 /* Macro for extracting a path's parameterization relids; beware double eval */
720 #define PATH_REQ_OUTER(path) \
721 ((path)->param_info ? (path)->param_info->ppi_req_outer : (Relids) NULL)
724 * IndexPath represents an index scan over a single index.
726 * This struct is used for both regular indexscans and index-only scans;
727 * path.pathtype is T_IndexScan or T_IndexOnlyScan to show which is meant.
729 * 'indexinfo' is the index to be scanned.
731 * 'indexclauses' is a list of index qualification clauses, with implicit
732 * AND semantics across the list. Each clause is a RestrictInfo node from
733 * the query's WHERE or JOIN conditions. An empty list implies a full
736 * 'indexquals' has the same structure as 'indexclauses', but it contains
737 * the actual index qual conditions that can be used with the index.
738 * In simple cases this is identical to 'indexclauses', but when special
739 * indexable operators appear in 'indexclauses', they are replaced by the
740 * derived indexscannable conditions in 'indexquals'.
742 * 'indexqualcols' is an integer list of index column numbers (zero-based)
743 * of the same length as 'indexquals', showing which index column each qual
744 * is meant to be used with. 'indexquals' is required to be ordered by
745 * index column, so 'indexqualcols' must form a nondecreasing sequence.
746 * (The order of multiple quals for the same index column is unspecified.)
748 * 'indexorderbys', if not NIL, is a list of ORDER BY expressions that have
749 * been found to be usable as ordering operators for an amcanorderbyop index.
750 * The list must match the path's pathkeys, ie, one expression per pathkey
751 * in the same order. These are not RestrictInfos, just bare expressions,
752 * since they generally won't yield booleans. Also, unlike the case for
753 * quals, it's guaranteed that each expression has the index key on the left
754 * side of the operator.
756 * 'indexorderbycols' is an integer list of index column numbers (zero-based)
757 * of the same length as 'indexorderbys', showing which index column each
758 * ORDER BY expression is meant to be used with. (There is no restriction
759 * on which index column each ORDER BY can be used with.)
761 * 'indexscandir' is one of:
762 * ForwardScanDirection: forward scan of an ordered index
763 * BackwardScanDirection: backward scan of an ordered index
764 * NoMovementScanDirection: scan of an unordered index, or don't care
765 * (The executor doesn't care whether it gets ForwardScanDirection or
766 * NoMovementScanDirection for an indexscan, but the planner wants to
767 * distinguish ordered from unordered indexes for building pathkeys.)
769 * 'indextotalcost' and 'indexselectivity' are saved in the IndexPath so that
770 * we need not recompute them when considering using the same index in a
771 * bitmap index/heap scan (see BitmapHeapPath). The costs of the IndexPath
772 * itself represent the costs of an IndexScan or IndexOnlyScan plan type.
775 typedef struct IndexPath
778 IndexOptInfo *indexinfo;
783 List *indexorderbycols;
784 ScanDirection indexscandir;
786 Selectivity indexselectivity;
790 * BitmapHeapPath represents one or more indexscans that generate TID bitmaps
791 * instead of directly accessing the heap, followed by AND/OR combinations
792 * to produce a single bitmap, followed by a heap scan that uses the bitmap.
793 * Note that the output is always considered unordered, since it will come
794 * out in physical heap order no matter what the underlying indexes did.
796 * The individual indexscans are represented by IndexPath nodes, and any
797 * logic on top of them is represented by a tree of BitmapAndPath and
798 * BitmapOrPath nodes. Notice that we can use the same IndexPath node both
799 * to represent a regular (or index-only) index scan plan, and as the child
800 * of a BitmapHeapPath that represents scanning the same index using a
801 * BitmapIndexScan. The startup_cost and total_cost figures of an IndexPath
802 * always represent the costs to use it as a regular (or index-only)
803 * IndexScan. The costs of a BitmapIndexScan can be computed using the
804 * IndexPath's indextotalcost and indexselectivity.
806 typedef struct BitmapHeapPath
809 Path *bitmapqual; /* IndexPath, BitmapAndPath, BitmapOrPath */
813 * BitmapAndPath represents a BitmapAnd plan node; it can only appear as
814 * part of the substructure of a BitmapHeapPath. The Path structure is
815 * a bit more heavyweight than we really need for this, but for simplicity
816 * we make it a derivative of Path anyway.
818 typedef struct BitmapAndPath
821 List *bitmapquals; /* IndexPaths and BitmapOrPaths */
822 Selectivity bitmapselectivity;
826 * BitmapOrPath represents a BitmapOr plan node; it can only appear as
827 * part of the substructure of a BitmapHeapPath. The Path structure is
828 * a bit more heavyweight than we really need for this, but for simplicity
829 * we make it a derivative of Path anyway.
831 typedef struct BitmapOrPath
834 List *bitmapquals; /* IndexPaths and BitmapAndPaths */
835 Selectivity bitmapselectivity;
839 * TidPath represents a scan by TID
841 * tidquals is an implicitly OR'ed list of qual expressions of the form
842 * "CTID = pseudoconstant" or "CTID = ANY(pseudoconstant_array)".
843 * Note they are bare expressions, not RestrictInfos.
845 typedef struct TidPath
848 List *tidquals; /* qual(s) involving CTID = something */
852 * ForeignPath represents a potential scan of a foreign table
854 * fdw_private stores FDW private data about the scan. While fdw_private is
855 * not actually touched by the core code during normal operations, it's
856 * generally a good idea to use a representation that can be dumped by
857 * nodeToString(), so that you can examine the structure during debugging
858 * with tools like pprint().
860 typedef struct ForeignPath
867 * AppendPath represents an Append plan, ie, successive execution of
868 * several member plans.
870 * Note: it is possible for "subpaths" to contain only one, or even no,
871 * elements. These cases are optimized during create_append_plan.
872 * In particular, an AppendPath with no subpaths is a "dummy" path that
873 * is created to represent the case that a relation is provably empty.
875 typedef struct AppendPath
878 List *subpaths; /* list of component Paths */
881 #define IS_DUMMY_PATH(p) \
882 (IsA((p), AppendPath) && ((AppendPath *) (p))->subpaths == NIL)
884 /* A relation that's been proven empty will have one path that is dummy */
885 #define IS_DUMMY_REL(r) \
886 ((r)->cheapest_total_path != NULL && \
887 IS_DUMMY_PATH((r)->cheapest_total_path))
890 * MergeAppendPath represents a MergeAppend plan, ie, the merging of sorted
891 * results from several member plans to produce similarly-sorted output.
893 typedef struct MergeAppendPath
896 List *subpaths; /* list of component Paths */
897 double limit_tuples; /* hard limit on output tuples, or -1 */
901 * ResultPath represents use of a Result plan node to compute a variable-free
902 * targetlist with no underlying tables (a "SELECT expressions" query).
903 * The query could have a WHERE clause, too, represented by "quals".
905 * Note that quals is a list of bare clauses, not RestrictInfos.
907 typedef struct ResultPath
914 * MaterialPath represents use of a Material plan node, i.e., caching of
915 * the output of its subpath. This is used when the subpath is expensive
916 * and needs to be scanned repeatedly, or when we need mark/restore ability
917 * and the subpath doesn't have it.
919 typedef struct MaterialPath
926 * UniquePath represents elimination of distinct rows from the output of
929 * This is unlike the other Path nodes in that it can actually generate
930 * different plans: either hash-based or sort-based implementation, or a
931 * no-op if the input path can be proven distinct already. The decision
932 * is sufficiently localized that it's not worth having separate Path node
933 * types. (Note: in the no-op case, we could eliminate the UniquePath node
934 * entirely and just return the subpath; but it's convenient to have a
935 * UniquePath in the path tree to signal upper-level routines that the input
936 * is known distinct.)
940 UNIQUE_PATH_NOOP, /* input is known unique already */
941 UNIQUE_PATH_HASH, /* use hashing */
942 UNIQUE_PATH_SORT /* use sorting */
945 typedef struct UniquePath
949 UniquePathMethod umethod;
950 List *in_operators; /* equality operators of the IN clause */
951 List *uniq_exprs; /* expressions to be made unique */
955 * All join-type paths share these fields.
958 typedef struct JoinPath
964 Path *outerjoinpath; /* path for the outer side of the join */
965 Path *innerjoinpath; /* path for the inner side of the join */
967 List *joinrestrictinfo; /* RestrictInfos to apply to join */
970 * See the notes for RelOptInfo and ParamPathInfo to understand why
971 * joinrestrictinfo is needed in JoinPath, and can't be merged into the
977 * A nested-loop path needs no special fields.
980 typedef JoinPath NestPath;
983 * A mergejoin path has these fields.
985 * Unlike other path types, a MergePath node doesn't represent just a single
986 * run-time plan node: it can represent up to four. Aside from the MergeJoin
987 * node itself, there can be a Sort node for the outer input, a Sort node
988 * for the inner input, and/or a Material node for the inner input. We could
989 * represent these nodes by separate path nodes, but considering how many
990 * different merge paths are investigated during a complex join problem,
991 * it seems better to avoid unnecessary palloc overhead.
993 * path_mergeclauses lists the clauses (in the form of RestrictInfos)
994 * that will be used in the merge.
996 * Note that the mergeclauses are a subset of the parent relation's
997 * restriction-clause list. Any join clauses that are not mergejoinable
998 * appear only in the parent's restrict list, and must be checked by a
999 * qpqual at execution time.
1001 * outersortkeys (resp. innersortkeys) is NIL if the outer path
1002 * (resp. inner path) is already ordered appropriately for the
1003 * mergejoin. If it is not NIL then it is a PathKeys list describing
1004 * the ordering that must be created by an explicit Sort node.
1006 * materialize_inner is TRUE if a Material node should be placed atop the
1007 * inner input. This may appear with or without an inner Sort step.
1010 typedef struct MergePath
1013 List *path_mergeclauses; /* join clauses to be used for merge */
1014 List *outersortkeys; /* keys for explicit sort, if any */
1015 List *innersortkeys; /* keys for explicit sort, if any */
1016 bool materialize_inner; /* add Materialize to inner? */
1020 * A hashjoin path has these fields.
1022 * The remarks above for mergeclauses apply for hashclauses as well.
1024 * Hashjoin does not care what order its inputs appear in, so we have
1025 * no need for sortkeys.
1028 typedef struct HashPath
1031 List *path_hashclauses; /* join clauses used for hashing */
1032 int num_batches; /* number of batches expected */
1036 * Restriction clause info.
1038 * We create one of these for each AND sub-clause of a restriction condition
1039 * (WHERE or JOIN/ON clause). Since the restriction clauses are logically
1040 * ANDed, we can use any one of them or any subset of them to filter out
1041 * tuples, without having to evaluate the rest. The RestrictInfo node itself
1042 * stores data used by the optimizer while choosing the best query plan.
1044 * If a restriction clause references a single base relation, it will appear
1045 * in the baserestrictinfo list of the RelOptInfo for that base rel.
1047 * If a restriction clause references more than one base rel, it will
1048 * appear in the joininfo list of every RelOptInfo that describes a strict
1049 * subset of the base rels mentioned in the clause. The joininfo lists are
1050 * used to drive join tree building by selecting plausible join candidates.
1051 * The clause cannot actually be applied until we have built a join rel
1052 * containing all the base rels it references, however.
1054 * When we construct a join rel that includes all the base rels referenced
1055 * in a multi-relation restriction clause, we place that clause into the
1056 * joinrestrictinfo lists of paths for the join rel, if neither left nor
1057 * right sub-path includes all base rels referenced in the clause. The clause
1058 * will be applied at that join level, and will not propagate any further up
1059 * the join tree. (Note: the "predicate migration" code was once intended to
1060 * push restriction clauses up and down the plan tree based on evaluation
1061 * costs, but it's dead code and is unlikely to be resurrected in the
1062 * foreseeable future.)
1064 * Note that in the presence of more than two rels, a multi-rel restriction
1065 * might reach different heights in the join tree depending on the join
1066 * sequence we use. So, these clauses cannot be associated directly with
1067 * the join RelOptInfo, but must be kept track of on a per-join-path basis.
1069 * RestrictInfos that represent equivalence conditions (i.e., mergejoinable
1070 * equalities that are not outerjoin-delayed) are handled a bit differently.
1071 * Initially we attach them to the EquivalenceClasses that are derived from
1072 * them. When we construct a scan or join path, we look through all the
1073 * EquivalenceClasses and generate derived RestrictInfos representing the
1074 * minimal set of conditions that need to be checked for this particular scan
1075 * or join to enforce that all members of each EquivalenceClass are in fact
1076 * equal in all rows emitted by the scan or join.
1078 * When dealing with outer joins we have to be very careful about pushing qual
1079 * clauses up and down the tree. An outer join's own JOIN/ON conditions must
1080 * be evaluated exactly at that join node, unless they are "degenerate"
1081 * conditions that reference only Vars from the nullable side of the join.
1082 * Quals appearing in WHERE or in a JOIN above the outer join cannot be pushed
1083 * down below the outer join, if they reference any nullable Vars.
1084 * RestrictInfo nodes contain a flag to indicate whether a qual has been
1085 * pushed down to a lower level than its original syntactic placement in the
1086 * join tree would suggest. If an outer join prevents us from pushing a qual
1087 * down to its "natural" semantic level (the level associated with just the
1088 * base rels used in the qual) then we mark the qual with a "required_relids"
1089 * value including more than just the base rels it actually uses. By
1090 * pretending that the qual references all the rels required to form the outer
1091 * join, we prevent it from being evaluated below the outer join's joinrel.
1092 * When we do form the outer join's joinrel, we still need to distinguish
1093 * those quals that are actually in that join's JOIN/ON condition from those
1094 * that appeared elsewhere in the tree and were pushed down to the join rel
1095 * because they used no other rels. That's what the is_pushed_down flag is
1096 * for; it tells us that a qual is not an OUTER JOIN qual for the set of base
1097 * rels listed in required_relids. A clause that originally came from WHERE
1098 * or an INNER JOIN condition will *always* have its is_pushed_down flag set.
1099 * It's possible for an OUTER JOIN clause to be marked is_pushed_down too,
1100 * if we decide that it can be pushed down into the nullable side of the join.
1101 * In that case it acts as a plain filter qual for wherever it gets evaluated.
1102 * (In short, is_pushed_down is only false for non-degenerate outer join
1103 * conditions. Possibly we should rename it to reflect that meaning?)
1105 * RestrictInfo nodes also contain an outerjoin_delayed flag, which is true
1106 * if the clause's applicability must be delayed due to any outer joins
1107 * appearing below it (ie, it has to be postponed to some join level higher
1108 * than the set of relations it actually references).
1110 * There is also an outer_relids field, which is NULL except for outer join
1111 * clauses; for those, it is the set of relids on the outer side of the
1112 * clause's outer join. (These are rels that the clause cannot be applied to
1113 * in parameterized scans, since pushing it into the join's outer side would
1114 * lead to wrong answers.)
1116 * There is also a nullable_relids field, which is the set of rels the clause
1117 * references that can be forced null by some outer join below the clause.
1119 * outerjoin_delayed = true is subtly different from nullable_relids != NULL:
1120 * a clause might reference some nullable rels and yet not be
1121 * outerjoin_delayed because it also references all the other rels of the
1122 * outer join(s). A clause that is not outerjoin_delayed can be enforced
1123 * anywhere it is computable.
1125 * In general, the referenced clause might be arbitrarily complex. The
1126 * kinds of clauses we can handle as indexscan quals, mergejoin clauses,
1127 * or hashjoin clauses are limited (e.g., no volatile functions). The code
1128 * for each kind of path is responsible for identifying the restrict clauses
1129 * it can use and ignoring the rest. Clauses not implemented by an indexscan,
1130 * mergejoin, or hashjoin will be placed in the plan qual or joinqual field
1131 * of the finished Plan node, where they will be enforced by general-purpose
1132 * qual-expression-evaluation code. (But we are still entitled to count
1133 * their selectivity when estimating the result tuple count, if we
1134 * can guess what it is...)
1136 * When the referenced clause is an OR clause, we generate a modified copy
1137 * in which additional RestrictInfo nodes are inserted below the top-level
1138 * OR/AND structure. This is a convenience for OR indexscan processing:
1139 * indexquals taken from either the top level or an OR subclause will have
1140 * associated RestrictInfo nodes.
1142 * The can_join flag is set true if the clause looks potentially useful as
1143 * a merge or hash join clause, that is if it is a binary opclause with
1144 * nonoverlapping sets of relids referenced in the left and right sides.
1145 * (Whether the operator is actually merge or hash joinable isn't checked,
1148 * The pseudoconstant flag is set true if the clause contains no Vars of
1149 * the current query level and no volatile functions. Such a clause can be
1150 * pulled out and used as a one-time qual in a gating Result node. We keep
1151 * pseudoconstant clauses in the same lists as other RestrictInfos so that
1152 * the regular clause-pushing machinery can assign them to the correct join
1153 * level, but they need to be treated specially for cost and selectivity
1154 * estimates. Note that a pseudoconstant clause can never be an indexqual
1155 * or merge or hash join clause, so it's of no interest to large parts of
1158 * When join clauses are generated from EquivalenceClasses, there may be
1159 * several equally valid ways to enforce join equivalence, of which we need
1160 * apply only one. We mark clauses of this kind by setting parent_ec to
1161 * point to the generating EquivalenceClass. Multiple clauses with the same
1162 * parent_ec in the same join are redundant.
1165 typedef struct RestrictInfo
1169 Expr *clause; /* the represented clause of WHERE or JOIN */
1171 bool is_pushed_down; /* TRUE if clause was pushed down in level */
1173 bool outerjoin_delayed; /* TRUE if delayed by lower outer join */
1175 bool can_join; /* see comment above */
1177 bool pseudoconstant; /* see comment above */
1179 /* The set of relids (varnos) actually referenced in the clause: */
1180 Relids clause_relids;
1182 /* The set of relids required to evaluate the clause: */
1183 Relids required_relids;
1185 /* If an outer-join clause, the outer-side relations, else NULL: */
1186 Relids outer_relids;
1188 /* The relids used in the clause that are nullable by lower outer joins: */
1189 Relids nullable_relids;
1191 /* These fields are set for any binary opclause: */
1192 Relids left_relids; /* relids in left side of clause */
1193 Relids right_relids; /* relids in right side of clause */
1195 /* This field is NULL unless clause is an OR clause: */
1196 Expr *orclause; /* modified clause with RestrictInfos */
1198 /* This field is NULL unless clause is potentially redundant: */
1199 EquivalenceClass *parent_ec; /* generating EquivalenceClass */
1201 /* cache space for cost and selectivity */
1202 QualCost eval_cost; /* eval cost of clause; -1 if not yet set */
1203 Selectivity norm_selec; /* selectivity for "normal" (JOIN_INNER)
1204 * semantics; -1 if not yet set; >1 means a
1205 * redundant clause */
1206 Selectivity outer_selec; /* selectivity for outer join semantics; -1 if
1209 /* valid if clause is mergejoinable, else NIL */
1210 List *mergeopfamilies; /* opfamilies containing clause operator */
1212 /* cache space for mergeclause processing; NULL if not yet set */
1213 EquivalenceClass *left_ec; /* EquivalenceClass containing lefthand */
1214 EquivalenceClass *right_ec; /* EquivalenceClass containing righthand */
1215 EquivalenceMember *left_em; /* EquivalenceMember for lefthand */
1216 EquivalenceMember *right_em; /* EquivalenceMember for righthand */
1217 List *scansel_cache; /* list of MergeScanSelCache structs */
1219 /* transient workspace for use while considering a specific join path */
1220 bool outer_is_left; /* T = outer var on left, F = on right */
1222 /* valid if clause is hashjoinable, else InvalidOid: */
1223 Oid hashjoinoperator; /* copy of clause operator */
1225 /* cache space for hashclause processing; -1 if not yet set */
1226 Selectivity left_bucketsize; /* avg bucketsize of left side */
1227 Selectivity right_bucketsize; /* avg bucketsize of right side */
1231 * Since mergejoinscansel() is a relatively expensive function, and would
1232 * otherwise be invoked many times while planning a large join tree,
1233 * we go out of our way to cache its results. Each mergejoinable
1234 * RestrictInfo carries a list of the specific sort orderings that have
1235 * been considered for use with it, and the resulting selectivities.
1237 typedef struct MergeScanSelCache
1239 /* Ordering details (cache lookup key) */
1240 Oid opfamily; /* btree opfamily defining the ordering */
1241 Oid collation; /* collation for the ordering */
1242 int strategy; /* sort direction (ASC or DESC) */
1243 bool nulls_first; /* do NULLs come before normal values? */
1245 Selectivity leftstartsel; /* first-join fraction for clause left side */
1246 Selectivity leftendsel; /* last-join fraction for clause left side */
1247 Selectivity rightstartsel; /* first-join fraction for clause right side */
1248 Selectivity rightendsel; /* last-join fraction for clause right side */
1249 } MergeScanSelCache;
1252 * Placeholder node for an expression to be evaluated below the top level
1253 * of a plan tree. This is used during planning to represent the contained
1254 * expression. At the end of the planning process it is replaced by either
1255 * the contained expression or a Var referring to a lower-level evaluation of
1256 * the contained expression. Typically the evaluation occurs below an outer
1257 * join, and Var references above the outer join might thereby yield NULL
1258 * instead of the expression value.
1260 * Although the planner treats this as an expression node type, it is not
1261 * recognized by the parser or executor, so we declare it here rather than
1265 typedef struct PlaceHolderVar
1268 Expr *phexpr; /* the represented expression */
1269 Relids phrels; /* base relids syntactically within expr src */
1270 Index phid; /* ID for PHV (unique within planner run) */
1271 Index phlevelsup; /* > 0 if PHV belongs to outer query */
1275 * "Special join" info.
1277 * One-sided outer joins constrain the order of joining partially but not
1278 * completely. We flatten such joins into the planner's top-level list of
1279 * relations to join, but record information about each outer join in a
1280 * SpecialJoinInfo struct. These structs are kept in the PlannerInfo node's
1283 * Similarly, semijoins and antijoins created by flattening IN (subselect)
1284 * and EXISTS(subselect) clauses create partial constraints on join order.
1285 * These are likewise recorded in SpecialJoinInfo structs.
1287 * We make SpecialJoinInfos for FULL JOINs even though there is no flexibility
1288 * of planning for them, because this simplifies make_join_rel()'s API.
1290 * min_lefthand and min_righthand are the sets of base relids that must be
1291 * available on each side when performing the special join. lhs_strict is
1292 * true if the special join's condition cannot succeed when the LHS variables
1293 * are all NULL (this means that an outer join can commute with upper-level
1294 * outer joins even if it appears in their RHS). We don't bother to set
1295 * lhs_strict for FULL JOINs, however.
1297 * It is not valid for either min_lefthand or min_righthand to be empty sets;
1298 * if they were, this would break the logic that enforces join order.
1300 * syn_lefthand and syn_righthand are the sets of base relids that are
1301 * syntactically below this special join. (These are needed to help compute
1302 * min_lefthand and min_righthand for higher joins.)
1304 * delay_upper_joins is set TRUE if we detect a pushed-down clause that has
1305 * to be evaluated after this join is formed (because it references the RHS).
1306 * Any outer joins that have such a clause and this join in their RHS cannot
1307 * commute with this join, because that would leave noplace to check the
1308 * pushed-down clause. (We don't track this for FULL JOINs, either.)
1310 * join_quals is an implicit-AND list of the quals syntactically associated
1311 * with the join (they may or may not end up being applied at the join level).
1312 * This is just a side list and does not drive actual application of quals.
1313 * For JOIN_SEMI joins, this is cleared to NIL in create_unique_path() if
1314 * the join is found not to be suitable for a uniqueify-the-RHS plan.
1316 * jointype is never JOIN_RIGHT; a RIGHT JOIN is handled by switching
1317 * the inputs to make it a LEFT JOIN. So the allowed values of jointype
1318 * in a join_info_list member are only LEFT, FULL, SEMI, or ANTI.
1320 * For purposes of join selectivity estimation, we create transient
1321 * SpecialJoinInfo structures for regular inner joins; so it is possible
1322 * to have jointype == JOIN_INNER in such a structure, even though this is
1323 * not allowed within join_info_list. We also create transient
1324 * SpecialJoinInfos with jointype == JOIN_INNER for outer joins, since for
1325 * cost estimation purposes it is sometimes useful to know the join size under
1326 * plain innerjoin semantics. Note that lhs_strict, delay_upper_joins, and
1327 * join_quals are not set meaningfully within such structs.
1330 typedef struct SpecialJoinInfo
1333 Relids min_lefthand; /* base relids in minimum LHS for join */
1334 Relids min_righthand; /* base relids in minimum RHS for join */
1335 Relids syn_lefthand; /* base relids syntactically within LHS */
1336 Relids syn_righthand; /* base relids syntactically within RHS */
1337 JoinType jointype; /* always INNER, LEFT, FULL, SEMI, or ANTI */
1338 bool lhs_strict; /* joinclause is strict for some LHS rel */
1339 bool delay_upper_joins; /* can't commute with upper RHS */
1340 List *join_quals; /* join quals, in implicit-AND list format */
1344 * "Lateral join" info.
1346 * Lateral references in subqueries constrain the join order in a way that's
1347 * somewhat like outer joins, though different in detail. We construct one or
1348 * more LateralJoinInfos for each RTE with lateral references, and add them to
1349 * the PlannerInfo node's lateral_info_list.
1351 * lateral_rhs is the relid of a baserel with lateral references, and
1352 * lateral_lhs is a set of relids of baserels it references, all of which
1353 * must be present on the LHS to compute a parameter needed by the RHS.
1354 * Typically, lateral_lhs is a singleton, but it can include multiple rels
1355 * if the RHS references a PlaceHolderVar with a multi-rel ph_eval_at level.
1356 * We disallow joining to only part of the LHS in such cases, since that would
1357 * result in a join tree with no convenient place to compute the PHV.
1359 * When an appendrel contains lateral references (eg "LATERAL (SELECT x.col1
1360 * UNION ALL SELECT y.col2)"), the LateralJoinInfos reference the parent
1361 * baserel not the member otherrels, since it is the parent relid that is
1362 * considered for joining purposes.
1365 typedef struct LateralJoinInfo
1368 Index lateral_rhs; /* a baserel containing lateral refs */
1369 Relids lateral_lhs; /* some base relids it references */
1373 * Append-relation info.
1375 * When we expand an inheritable table or a UNION-ALL subselect into an
1376 * "append relation" (essentially, a list of child RTEs), we build an
1377 * AppendRelInfo for each child RTE. The list of AppendRelInfos indicates
1378 * which child RTEs must be included when expanding the parent, and each
1379 * node carries information needed to translate Vars referencing the parent
1380 * into Vars referencing that child.
1382 * These structs are kept in the PlannerInfo node's append_rel_list.
1383 * Note that we just throw all the structs into one list, and scan the
1384 * whole list when desiring to expand any one parent. We could have used
1385 * a more complex data structure (eg, one list per parent), but this would
1386 * be harder to update during operations such as pulling up subqueries,
1387 * and not really any easier to scan. Considering that typical queries
1388 * will not have many different append parents, it doesn't seem worthwhile
1389 * to complicate things.
1391 * Note: after completion of the planner prep phase, any given RTE is an
1392 * append parent having entries in append_rel_list if and only if its
1393 * "inh" flag is set. We clear "inh" for plain tables that turn out not
1394 * to have inheritance children, and (in an abuse of the original meaning
1395 * of the flag) we set "inh" for subquery RTEs that turn out to be
1396 * flattenable UNION ALL queries. This lets us avoid useless searches
1397 * of append_rel_list.
1399 * Note: the data structure assumes that append-rel members are single
1400 * baserels. This is OK for inheritance, but it prevents us from pulling
1401 * up a UNION ALL member subquery if it contains a join. While that could
1402 * be fixed with a more complex data structure, at present there's not much
1403 * point because no improvement in the plan could result.
1406 typedef struct AppendRelInfo
1411 * These fields uniquely identify this append relationship. There can be
1412 * (in fact, always should be) multiple AppendRelInfos for the same
1413 * parent_relid, but never more than one per child_relid, since a given
1414 * RTE cannot be a child of more than one append parent.
1416 Index parent_relid; /* RT index of append parent rel */
1417 Index child_relid; /* RT index of append child rel */
1420 * For an inheritance appendrel, the parent and child are both regular
1421 * relations, and we store their rowtype OIDs here for use in translating
1422 * whole-row Vars. For a UNION-ALL appendrel, the parent and child are
1423 * both subqueries with no named rowtype, and we store InvalidOid here.
1425 Oid parent_reltype; /* OID of parent's composite type */
1426 Oid child_reltype; /* OID of child's composite type */
1429 * The N'th element of this list is a Var or expression representing the
1430 * child column corresponding to the N'th column of the parent. This is
1431 * used to translate Vars referencing the parent rel into references to
1432 * the child. A list element is NULL if it corresponds to a dropped
1433 * column of the parent (this is only possible for inheritance cases, not
1434 * UNION ALL). The list elements are always simple Vars for inheritance
1435 * cases, but can be arbitrary expressions in UNION ALL cases.
1437 * Notice we only store entries for user columns (attno > 0). Whole-row
1438 * Vars are special-cased, and system columns (attno < 0) need no special
1439 * translation since their attnos are the same for all tables.
1441 * Caution: the Vars have varlevelsup = 0. Be careful to adjust as needed
1442 * when copying into a subquery.
1444 List *translated_vars; /* Expressions in the child's Vars */
1447 * We store the parent table's OID here for inheritance, or InvalidOid for
1448 * UNION ALL. This is only needed to help in generating error messages if
1449 * an attempt is made to reference a dropped parent column.
1451 Oid parent_reloid; /* OID of parent relation */
1455 * For each distinct placeholder expression generated during planning, we
1456 * store a PlaceHolderInfo node in the PlannerInfo node's placeholder_list.
1457 * This stores info that is needed centrally rather than in each copy of the
1458 * PlaceHolderVar. The phid fields identify which PlaceHolderInfo goes with
1459 * each PlaceHolderVar. Note that phid is unique throughout a planner run,
1460 * not just within a query level --- this is so that we need not reassign ID's
1461 * when pulling a subquery into its parent.
1463 * The idea is to evaluate the expression at (only) the ph_eval_at join level,
1464 * then allow it to bubble up like a Var until the ph_needed join level.
1465 * ph_needed has the same definition as attr_needed for a regular Var.
1467 * ph_may_need is an initial estimate of ph_needed, formed using the
1468 * syntactic locations of references to the PHV. We need this in order to
1469 * determine whether the PHV reference forces a join ordering constraint:
1470 * if the PHV has to be evaluated below the nullable side of an outer join,
1471 * and then used above that outer join, we must constrain join order to ensure
1472 * there's a valid place to evaluate the PHV below the join. The final
1473 * actual ph_needed level might be lower than ph_may_need, but we can't
1474 * determine that until later on. Fortunately this doesn't matter for what
1475 * we need ph_may_need for: if there's a PHV reference syntactically
1476 * above the outer join, it's not going to be allowed to drop below the outer
1477 * join, so we would come to the same conclusions about join order even if
1478 * we had the final ph_needed value to compare to.
1480 * We create a PlaceHolderInfo only after determining that the PlaceHolderVar
1481 * is actually referenced in the plan tree, so that unreferenced placeholders
1482 * don't result in unnecessary constraints on join order.
1485 typedef struct PlaceHolderInfo
1489 Index phid; /* ID for PH (unique within planner run) */
1490 PlaceHolderVar *ph_var; /* copy of PlaceHolderVar tree */
1491 Relids ph_eval_at; /* lowest level we can evaluate value at */
1492 Relids ph_needed; /* highest level the value is needed at */
1493 Relids ph_may_need; /* highest level it might be needed at */
1494 int32 ph_width; /* estimated attribute width */
1498 * For each potentially index-optimizable MIN/MAX aggregate function,
1499 * root->minmax_aggs stores a MinMaxAggInfo describing it.
1501 typedef struct MinMaxAggInfo
1505 Oid aggfnoid; /* pg_proc Oid of the aggregate */
1506 Oid aggsortop; /* Oid of its sort operator */
1507 Expr *target; /* expression we are aggregating on */
1508 PlannerInfo *subroot; /* modified "root" for planning the subquery */
1509 Path *path; /* access path for subquery */
1510 Cost pathcost; /* estimated cost to fetch first row */
1511 Param *param; /* param for subplan's output */
1515 * At runtime, PARAM_EXEC slots are used to pass values around from one plan
1516 * node to another. They can be used to pass values down into subqueries (for
1517 * outer references in subqueries), or up out of subqueries (for the results
1518 * of a subplan), or from a NestLoop plan node into its inner relation (when
1519 * the inner scan is parameterized with values from the outer relation).
1520 * The planner is responsible for assigning nonconflicting PARAM_EXEC IDs to
1521 * the PARAM_EXEC Params it generates.
1523 * Outer references are managed via root->plan_params, which is a list of
1524 * PlannerParamItems. While planning a subquery, each parent query level's
1525 * plan_params contains the values required from it by the current subquery.
1526 * During create_plan(), we use plan_params to track values that must be
1527 * passed from outer to inner sides of NestLoop plan nodes.
1529 * The item a PlannerParamItem represents can be one of three kinds:
1531 * A Var: the slot represents a variable of this level that must be passed
1532 * down because subqueries have outer references to it, or must be passed
1533 * from a NestLoop node to its inner scan. The varlevelsup value in the Var
1534 * will always be zero.
1536 * A PlaceHolderVar: this works much like the Var case, except that the
1537 * entry is a PlaceHolderVar node with a contained expression. The PHV
1538 * will have phlevelsup = 0, and the contained expression is adjusted
1539 * to match in level.
1541 * An Aggref (with an expression tree representing its argument): the slot
1542 * represents an aggregate expression that is an outer reference for some
1543 * subquery. The Aggref itself has agglevelsup = 0, and its argument tree
1544 * is adjusted to match in level.
1546 * Note: we detect duplicate Var and PlaceHolderVar parameters and coalesce
1547 * them into one slot, but we do not bother to do that for Aggrefs.
1548 * The scope of duplicate-elimination only extends across the set of
1549 * parameters passed from one query level into a single subquery, or for
1550 * nestloop parameters across the set of nestloop parameters used in a single
1551 * query level. So there is no possibility of a PARAM_EXEC slot being used
1552 * for conflicting purposes.
1554 * In addition, PARAM_EXEC slots are assigned for Params representing outputs
1555 * from subplans (values that are setParam items for those subplans). These
1556 * IDs need not be tracked via PlannerParamItems, since we do not need any
1557 * duplicate-elimination nor later processing of the represented expressions.
1558 * Instead, we just record the assignment of the slot number by incrementing
1559 * root->glob->nParamExec.
1561 typedef struct PlannerParamItem
1565 Node *item; /* the Var, PlaceHolderVar, or Aggref */
1566 int paramId; /* its assigned PARAM_EXEC slot number */
1570 * When making cost estimates for a SEMI or ANTI join, there are some
1571 * correction factors that are needed in both nestloop and hash joins
1572 * to account for the fact that the executor can stop scanning inner rows
1573 * as soon as it finds a match to the current outer row. These numbers
1574 * depend only on the selected outer and inner join relations, not on the
1575 * particular paths used for them, so it's worthwhile to calculate them
1576 * just once per relation pair not once per considered path. This struct
1577 * is filled by compute_semi_anti_join_factors and must be passed along
1578 * to the join cost estimation functions.
1580 * outer_match_frac is the fraction of the outer tuples that are
1581 * expected to have at least one match.
1582 * match_count is the average number of matches expected for
1583 * outer tuples that have at least one match.
1585 typedef struct SemiAntiJoinFactors
1587 Selectivity outer_match_frac;
1588 Selectivity match_count;
1589 } SemiAntiJoinFactors;
1592 * For speed reasons, cost estimation for join paths is performed in two
1593 * phases: the first phase tries to quickly derive a lower bound for the
1594 * join cost, and then we check if that's sufficient to reject the path.
1595 * If not, we come back for a more refined cost estimate. The first phase
1596 * fills a JoinCostWorkspace struct with its preliminary cost estimates
1597 * and possibly additional intermediate values. The second phase takes
1598 * these values as inputs to avoid repeating work.
1600 * (Ideally we'd declare this in cost.h, but it's also needed in pathnode.h,
1601 * so seems best to put it here.)
1603 typedef struct JoinCostWorkspace
1605 /* Preliminary cost estimates --- must not be larger than final ones! */
1606 Cost startup_cost; /* cost expended before fetching any tuples */
1607 Cost total_cost; /* total cost (assuming all tuples fetched) */
1609 /* Fields below here should be treated as private to costsize.c */
1610 Cost run_cost; /* non-startup cost components */
1612 /* private for cost_nestloop code */
1613 Cost inner_rescan_run_cost;
1614 double outer_matched_rows;
1615 Selectivity inner_scan_frac;
1617 /* private for cost_mergejoin code */
1618 Cost inner_run_cost;
1621 double outer_skip_rows;
1622 double inner_skip_rows;
1624 /* private for cost_hashjoin code */
1627 } JoinCostWorkspace;
1629 #endif /* RELATION_H */