1 /*-------------------------------------------------------------------------
4 * Definitions for planner's internal data structures.
7 * Portions Copyright (c) 1996-2018, 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 "lib/stringinfo.h"
19 #include "nodes/params.h"
20 #include "nodes/parsenodes.h"
21 #include "storage/block.h"
26 * Set of relation identifiers (indexes into the rangetable).
28 typedef Bitmapset *Relids;
31 * When looking for a "cheapest path", this enum specifies whether we want
32 * cheapest startup cost or cheapest total cost.
34 typedef enum CostSelector
36 STARTUP_COST, TOTAL_COST
40 * The cost estimate produced by cost_qual_eval() includes both a one-time
41 * (startup) cost, and a per-tuple cost.
43 typedef struct QualCost
45 Cost startup; /* one-time cost */
46 Cost per_tuple; /* per-evaluation cost */
50 * Costing aggregate function execution requires these statistics about
51 * the aggregates to be executed by a given Agg node. Note that the costs
52 * include the execution costs of the aggregates' argument expressions as
53 * well as the aggregate functions themselves. Also, the fields must be
54 * defined so that initializing the struct to zeroes with memset is correct.
56 typedef struct AggClauseCosts
58 int numAggs; /* total number of aggregate functions */
59 int numOrderedAggs; /* number w/ DISTINCT/ORDER BY/WITHIN GROUP */
60 bool hasNonPartial; /* does any agg not support partial mode? */
61 bool hasNonSerial; /* is any partial agg non-serializable? */
62 QualCost transCost; /* total per-input-row execution costs */
63 Cost finalCost; /* total per-aggregated-row costs */
64 Size transitionSpace; /* space for pass-by-ref transition data */
68 * This enum identifies the different types of "upper" (post-scan/join)
69 * relations that we might deal with during planning.
71 typedef enum UpperRelationKind
73 UPPERREL_SETOP, /* result of UNION/INTERSECT/EXCEPT, if any */
74 UPPERREL_PARTIAL_GROUP_AGG, /* result of partial grouping/aggregation, if
76 UPPERREL_GROUP_AGG, /* result of grouping/aggregation, if any */
77 UPPERREL_WINDOW, /* result of window functions, if any */
78 UPPERREL_DISTINCT, /* result of "SELECT DISTINCT", if any */
79 UPPERREL_ORDERED, /* result of ORDER BY, if any */
80 UPPERREL_FINAL /* result of any remaining top-level actions */
81 /* NB: UPPERREL_FINAL must be last enum entry; it's used to size arrays */
87 * Global information for planning/optimization
89 * PlannerGlobal holds state for an entire planner invocation; this state
90 * is shared across all levels of sub-Queries that exist in the command being
94 typedef struct PlannerGlobal
98 ParamListInfo boundParams; /* Param values provided to planner() */
100 List *subplans; /* Plans for SubPlan nodes */
102 List *subroots; /* PlannerInfos for SubPlan nodes */
104 Bitmapset *rewindPlanIDs; /* indices of subplans that require REWIND */
106 List *finalrtable; /* "flat" rangetable for executor */
108 List *finalrowmarks; /* "flat" list of PlanRowMarks */
110 List *resultRelations; /* "flat" list of integer RT indexes */
112 List *nonleafResultRelations; /* "flat" list of integer RT indexes */
113 List *rootResultRelations; /* "flat" list of integer RT indexes */
115 List *relationOids; /* OIDs of relations the plan depends on */
117 List *invalItems; /* other dependencies, as PlanInvalItems */
119 List *paramExecTypes; /* type OIDs for PARAM_EXEC Params */
121 Index lastPHId; /* highest PlaceHolderVar ID assigned */
123 Index lastRowMarkId; /* highest PlanRowMark ID assigned */
125 int lastPlanNodeId; /* highest plan node ID assigned */
127 bool transientPlan; /* redo plan when TransactionXmin changes? */
129 bool dependsOnRole; /* is plan specific to current role? */
131 bool parallelModeOK; /* parallel mode potentially OK? */
133 bool parallelModeNeeded; /* parallel mode actually required? */
135 char maxParallelHazard; /* worst PROPARALLEL hazard level */
138 /* macro for fetching the Plan associated with a SubPlan node */
139 #define planner_subplan_get_plan(root, subplan) \
140 ((Plan *) list_nth((root)->glob->subplans, (subplan)->plan_id - 1))
145 * Per-query information for planning/optimization
147 * This struct is conventionally called "root" in all the planner routines.
148 * It holds links to all of the planner's working state, in addition to the
149 * original Query. Note that at present the planner extensively modifies
150 * the passed-in Query data structure; someday that should stop.
153 typedef struct PlannerInfo
157 Query *parse; /* the Query being planned */
159 PlannerGlobal *glob; /* global info for current planner run */
161 Index query_level; /* 1 at the outermost Query */
163 struct PlannerInfo *parent_root; /* NULL at outermost Query */
166 * plan_params contains the expressions that this query level needs to
167 * make available to a lower query level that is currently being planned.
168 * outer_params contains the paramIds of PARAM_EXEC Params that outer
169 * query levels will make available to this query level.
171 List *plan_params; /* list of PlannerParamItems, see below */
172 Bitmapset *outer_params;
175 * simple_rel_array holds pointers to "base rels" and "other rels" (see
176 * comments for RelOptInfo for more info). It is indexed by rangetable
177 * index (so entry 0 is always wasted). Entries can be NULL when an RTE
178 * does not correspond to a base relation, such as a join RTE or an
179 * unreferenced view RTE; or if the RelOptInfo hasn't been made yet.
181 struct RelOptInfo **simple_rel_array; /* All 1-rel RelOptInfos */
182 int simple_rel_array_size; /* allocated size of array */
185 * simple_rte_array is the same length as simple_rel_array and holds
186 * pointers to the associated rangetable entries. This lets us avoid
187 * rt_fetch(), which can be a bit slow once large inheritance sets have
190 RangeTblEntry **simple_rte_array; /* rangetable as an array */
193 * all_baserels is a Relids set of all base relids (but not "other"
194 * relids) in the query; that is, the Relids identifier of the final join
195 * we need to form. This is computed in make_one_rel, just before we
196 * start making Paths.
201 * nullable_baserels is a Relids set of base relids that are nullable by
202 * some outer join in the jointree; these are rels that are potentially
203 * nullable below the WHERE clause, SELECT targetlist, etc. This is
204 * computed in deconstruct_jointree.
206 Relids nullable_baserels;
209 * join_rel_list is a list of all join-relation RelOptInfos we have
210 * considered in this planning run. For small problems we just scan the
211 * list to do lookups, but when there are many join relations we build a
212 * hash table for faster lookups. The hash table is present and valid
213 * when join_rel_hash is not NULL. Note that we still maintain the list
214 * even when using the hash table for lookups; this simplifies life for
217 List *join_rel_list; /* list of join-relation RelOptInfos */
218 struct HTAB *join_rel_hash; /* optional hashtable for join relations */
221 * When doing a dynamic-programming-style join search, join_rel_level[k]
222 * is a list of all join-relation RelOptInfos of level k, and
223 * join_cur_level is the current level. New join-relation RelOptInfos are
224 * automatically added to the join_rel_level[join_cur_level] list.
225 * join_rel_level is NULL if not in use.
227 List **join_rel_level; /* lists of join-relation RelOptInfos */
228 int join_cur_level; /* index of list being extended */
230 List *init_plans; /* init SubPlans for query */
232 List *cte_plan_ids; /* per-CTE-item list of subplan IDs */
234 List *multiexpr_params; /* List of Lists of Params for MULTIEXPR
235 * subquery outputs */
237 List *eq_classes; /* list of active EquivalenceClasses */
239 List *canon_pathkeys; /* list of "canonical" PathKeys */
241 List *left_join_clauses; /* list of RestrictInfos for mergejoinable
242 * outer join clauses w/nonnullable var on
245 List *right_join_clauses; /* list of RestrictInfos for mergejoinable
246 * outer join clauses w/nonnullable var on
249 List *full_join_clauses; /* list of RestrictInfos for mergejoinable
250 * full join clauses */
252 List *join_info_list; /* list of SpecialJoinInfos */
254 List *append_rel_list; /* list of AppendRelInfos */
256 List *pcinfo_list; /* list of PartitionedChildRelInfos */
258 List *rowMarks; /* list of PlanRowMarks */
260 List *placeholder_list; /* list of PlaceHolderInfos */
262 List *fkey_list; /* list of ForeignKeyOptInfos */
264 List *query_pathkeys; /* desired pathkeys for query_planner() */
266 List *group_pathkeys; /* groupClause pathkeys, if any */
267 List *window_pathkeys; /* pathkeys of bottom window, if any */
268 List *distinct_pathkeys; /* distinctClause pathkeys, if any */
269 List *sort_pathkeys; /* sortClause pathkeys, if any */
271 List *part_schemes; /* Canonicalised partition schemes used in the
274 List *initial_rels; /* RelOptInfos we are now trying to join */
276 /* Use fetch_upper_rel() to get any particular upper rel */
277 List *upper_rels[UPPERREL_FINAL + 1]; /* upper-rel RelOptInfos */
279 /* Result tlists chosen by grouping_planner for upper-stage processing */
280 struct PathTarget *upper_targets[UPPERREL_FINAL + 1];
283 * grouping_planner passes back its final processed targetlist here, for
284 * use in relabeling the topmost tlist of the finished Plan.
286 List *processed_tlist;
288 /* Fields filled during create_plan() for use in setrefs.c */
289 AttrNumber *grouping_map; /* for GroupingFunc fixup */
290 List *minmax_aggs; /* List of MinMaxAggInfos */
292 MemoryContext planner_cxt; /* context holding PlannerInfo */
294 double total_table_pages; /* # of pages in all tables of query */
296 double tuple_fraction; /* tuple_fraction passed to query_planner */
297 double limit_tuples; /* limit_tuples passed to query_planner */
299 Index qual_security_level; /* minimum security_level for quals */
300 /* Note: qual_security_level is zero if there are no securityQuals */
302 bool hasInheritedTarget; /* true if parse->resultRelation is an
303 * inheritance child rel */
304 bool hasJoinRTEs; /* true if any RTEs are RTE_JOIN kind */
305 bool hasLateralRTEs; /* true if any RTEs are marked LATERAL */
306 bool hasDeletedRTEs; /* true if any RTE was deleted from jointree */
307 bool hasHavingQual; /* true if havingQual was non-null */
308 bool hasPseudoConstantQuals; /* true if any RestrictInfo has
309 * pseudoconstant = true */
310 bool hasRecursion; /* true if planning a recursive WITH item */
312 /* These fields are used only when hasRecursion is true: */
313 int wt_param_id; /* PARAM_EXEC ID for the work table */
314 struct Path *non_recursive_path; /* a path for non-recursive term */
316 /* These fields are workspace for createplan.c */
317 Relids curOuterRels; /* outer rels above current node */
318 List *curOuterParams; /* not-yet-assigned NestLoopParams */
320 /* optional private data for join_search_hook, e.g., GEQO */
321 void *join_search_private;
326 * In places where it's known that simple_rte_array[] must have been prepared
327 * already, we just index into it to fetch RTEs. In code that might be
328 * executed before or after entering query_planner(), use this macro.
330 #define planner_rt_fetch(rti, root) \
331 ((root)->simple_rte_array ? (root)->simple_rte_array[rti] : \
332 rt_fetch(rti, (root)->parse->rtable))
335 * If multiple relations are partitioned the same way, all such partitions
336 * will have a pointer to the same PartitionScheme. A list of PartitionScheme
337 * objects is attached to the PlannerInfo. By design, the partition scheme
338 * incorporates only the general properties of the partition method (LIST vs.
339 * RANGE, number of partitioning columns and the type information for each)
340 * and not the specific bounds.
342 * We store the opclass-declared input data types instead of the partition key
343 * datatypes since the former rather than the latter are used to compare
344 * partition bounds. Since partition key data types and the opclass declared
345 * input data types are expected to be binary compatible (per ResolveOpClass),
346 * both of those should have same byval and length properties.
348 typedef struct PartitionSchemeData
350 char strategy; /* partition strategy */
351 int16 partnatts; /* number of partition attributes */
352 Oid *partopfamily; /* OIDs of operator families */
353 Oid *partopcintype; /* OIDs of opclass declared input data types */
354 Oid *partcollation; /* OIDs of partitioning collations */
356 /* Cached information about partition key data types. */
359 } PartitionSchemeData;
361 typedef struct PartitionSchemeData *PartitionScheme;
365 * Per-relation information for planning/optimization
367 * For planning purposes, a "base rel" is either a plain relation (a table)
368 * or the output of a sub-SELECT or function that appears in the range table.
369 * In either case it is uniquely identified by an RT index. A "joinrel"
370 * is the joining of two or more base rels. A joinrel is identified by
371 * the set of RT indexes for its component baserels. We create RelOptInfo
372 * nodes for each baserel and joinrel, and store them in the PlannerInfo's
373 * simple_rel_array and join_rel_list respectively.
375 * Note that there is only one joinrel for any given set of component
376 * baserels, no matter what order we assemble them in; so an unordered
377 * set is the right datatype to identify it with.
379 * We also have "other rels", which are like base rels in that they refer to
380 * single RT indexes; but they are not part of the join tree, and are given
381 * a different RelOptKind to identify them.
382 * Currently the only kind of otherrels are those made for member relations
383 * of an "append relation", that is an inheritance set or UNION ALL subquery.
384 * An append relation has a parent RTE that is a base rel, which represents
385 * the entire append relation. The member RTEs are otherrels. The parent
386 * is present in the query join tree but the members are not. The member
387 * RTEs and otherrels are used to plan the scans of the individual tables or
388 * subqueries of the append set; then the parent baserel is given Append
389 * and/or MergeAppend paths comprising the best paths for the individual
390 * member rels. (See comments for AppendRelInfo for more information.)
392 * At one time we also made otherrels to represent join RTEs, for use in
393 * handling join alias Vars. Currently this is not needed because all join
394 * alias Vars are expanded to non-aliased form during preprocess_expression.
396 * We also have relations representing joins between child relations of
397 * different partitioned tables. These relations are not added to
398 * join_rel_level lists as they are not joined directly by the dynamic
399 * programming algorithm.
401 * There is also a RelOptKind for "upper" relations, which are RelOptInfos
402 * that describe post-scan/join processing steps, such as aggregation.
403 * Many of the fields in these RelOptInfos are meaningless, but their Path
404 * fields always hold Paths showing ways to do that processing step.
406 * Lastly, there is a RelOptKind for "dead" relations, which are base rels
407 * that we have proven we don't need to join after all.
409 * Parts of this data structure are specific to various scan and join
410 * mechanisms. It didn't seem worth creating new node types for them.
412 * relids - Set of base-relation identifiers; it is a base relation
413 * if there is just one, a join relation if more than one
414 * rows - estimated number of tuples in the relation after restriction
415 * clauses have been applied (ie, output rows of a plan for it)
416 * consider_startup - true if there is any value in keeping plain paths for
417 * this rel on the basis of having cheap startup cost
418 * consider_param_startup - the same for parameterized paths
419 * reltarget - Default Path output tlist for this rel; normally contains
420 * Var and PlaceHolderVar nodes for the values we need to
421 * output from this relation.
422 * List is in no particular order, but all rels of an
423 * appendrel set must use corresponding orders.
424 * NOTE: in an appendrel child relation, may contain
425 * arbitrary expressions pulled up from a subquery!
426 * pathlist - List of Path nodes, one for each potentially useful
427 * method of generating the relation
428 * ppilist - ParamPathInfo nodes for parameterized Paths, if any
429 * cheapest_startup_path - the pathlist member with lowest startup cost
430 * (regardless of ordering) among the unparameterized paths;
431 * or NULL if there is no unparameterized path
432 * cheapest_total_path - the pathlist member with lowest total cost
433 * (regardless of ordering) among the unparameterized paths;
434 * or if there is no unparameterized path, the path with lowest
435 * total cost among the paths with minimum parameterization
436 * cheapest_unique_path - for caching cheapest path to produce unique
437 * (no duplicates) output from relation; NULL if not yet requested
438 * cheapest_parameterized_paths - best paths for their parameterizations;
439 * always includes cheapest_total_path, even if that's unparameterized
440 * direct_lateral_relids - rels this rel has direct LATERAL references to
441 * lateral_relids - required outer rels for LATERAL, as a Relids set
442 * (includes both direct and indirect lateral references)
444 * If the relation is a base relation it will have these fields set:
446 * relid - RTE index (this is redundant with the relids field, but
447 * is provided for convenience of access)
448 * rtekind - copy of RTE's rtekind field
449 * min_attr, max_attr - range of valid AttrNumbers for rel
450 * attr_needed - array of bitmapsets indicating the highest joinrel
451 * in which each attribute is needed; if bit 0 is set then
452 * the attribute is needed as part of final targetlist
453 * attr_widths - cache space for per-attribute width estimates;
454 * zero means not computed yet
455 * lateral_vars - lateral cross-references of rel, if any (list of
456 * Vars and PlaceHolderVars)
457 * lateral_referencers - relids of rels that reference this one laterally
458 * (includes both direct and indirect lateral references)
459 * indexlist - list of IndexOptInfo nodes for relation's indexes
460 * (always NIL if it's not a table)
461 * pages - number of disk pages in relation (zero if not a table)
462 * tuples - number of tuples in relation (not considering restrictions)
463 * allvisfrac - fraction of disk pages that are marked all-visible
464 * subroot - PlannerInfo for subquery (NULL if it's not a subquery)
465 * subplan_params - list of PlannerParamItems to be passed to subquery
467 * Note: for a subquery, tuples and subroot are not set immediately
468 * upon creation of the RelOptInfo object; they are filled in when
469 * set_subquery_pathlist processes the object.
471 * For otherrels that are appendrel members, these fields are filled
472 * in just as for a baserel, except we don't bother with lateral_vars.
474 * If the relation is either a foreign table or a join of foreign tables that
475 * all belong to the same foreign server and are assigned to the same user to
476 * check access permissions as (cf checkAsUser), these fields will be set:
478 * serverid - OID of foreign server, if foreign table (else InvalidOid)
479 * userid - OID of user to check access as (InvalidOid means current user)
480 * useridiscurrent - we've assumed that userid equals current user
481 * fdwroutine - function hooks for FDW, if foreign table (else NULL)
482 * fdw_private - private state for FDW, if foreign table (else NULL)
484 * Two fields are used to cache knowledge acquired during the join search
485 * about whether this rel is provably unique when being joined to given other
486 * relation(s), ie, it can have at most one row matching any given row from
487 * that join relation. Currently we only attempt such proofs, and thus only
488 * populate these fields, for base rels; but someday they might be used for
491 * unique_for_rels - list of Relid sets, each one being a set of other
492 * rels for which this one has been proven unique
493 * non_unique_for_rels - list of Relid sets, each one being a set of
494 * other rels for which we have tried and failed to prove
497 * The presence of the following fields depends on the restrictions
498 * and joins that the relation participates in:
500 * baserestrictinfo - List of RestrictInfo nodes, containing info about
501 * each non-join qualification clause in which this relation
502 * participates (only used for base rels)
503 * baserestrictcost - Estimated cost of evaluating the baserestrictinfo
504 * clauses at a single tuple (only used for base rels)
505 * baserestrict_min_security - Smallest security_level found among
506 * clauses in baserestrictinfo
507 * joininfo - List of RestrictInfo nodes, containing info about each
508 * join clause in which this relation participates (but
509 * note this excludes clauses that might be derivable from
510 * EquivalenceClasses)
511 * has_eclass_joins - flag that EquivalenceClass joins are possible
513 * Note: Keeping a restrictinfo list in the RelOptInfo is useful only for
514 * base rels, because for a join rel the set of clauses that are treated as
515 * restrict clauses varies depending on which sub-relations we choose to join.
516 * (For example, in a 3-base-rel join, a clause relating rels 1 and 2 must be
517 * treated as a restrictclause if we join {1} and {2 3} to make {1 2 3}; but
518 * if we join {1 2} and {3} then that clause will be a restrictclause in {1 2}
519 * and should not be processed again at the level of {1 2 3}.) Therefore,
520 * the restrictinfo list in the join case appears in individual JoinPaths
521 * (field joinrestrictinfo), not in the parent relation. But it's OK for
522 * the RelOptInfo to store the joininfo list, because that is the same
523 * for a given rel no matter how we form it.
525 * We store baserestrictcost in the RelOptInfo (for base relations) because
526 * we know we will need it at least once (to price the sequential scan)
527 * and may need it multiple times to price index scans.
529 * If the relation is partitioned, these fields will be set:
531 * part_scheme - Partitioning scheme of the relation
532 * boundinfo - Partition bounds
533 * nparts - Number of partitions
534 * part_rels - RelOptInfos for each partition
535 * partexprs, nullable_partexprs - Partition key expressions
537 * Note: A base relation always has only one set of partition keys, but a join
538 * relation may have as many sets of partition keys as the number of relations
539 * being joined. partexprs and nullable_partexprs are arrays containing
540 * part_scheme->partnatts elements each. Each of these elements is a list of
541 * partition key expressions. For a base relation each list in partexprs
542 * contains only one expression and nullable_partexprs is not populated. For a
543 * join relation, partexprs and nullable_partexprs contain partition key
544 * expressions from non-nullable and nullable relations resp. Lists at any
545 * given position in those arrays together contain as many elements as the
546 * number of joining relations.
549 typedef enum RelOptKind
553 RELOPT_OTHER_MEMBER_REL,
554 RELOPT_OTHER_JOINREL,
556 RELOPT_OTHER_UPPER_REL,
561 * Is the given relation a simple relation i.e a base or "other" member
564 #define IS_SIMPLE_REL(rel) \
565 ((rel)->reloptkind == RELOPT_BASEREL || \
566 (rel)->reloptkind == RELOPT_OTHER_MEMBER_REL)
568 /* Is the given relation a join relation? */
569 #define IS_JOIN_REL(rel) \
570 ((rel)->reloptkind == RELOPT_JOINREL || \
571 (rel)->reloptkind == RELOPT_OTHER_JOINREL)
573 /* Is the given relation an upper relation? */
574 #define IS_UPPER_REL(rel) \
575 ((rel)->reloptkind == RELOPT_UPPER_REL || \
576 (rel)->reloptkind == RELOPT_OTHER_UPPER_REL)
578 /* Is the given relation an "other" relation? */
579 #define IS_OTHER_REL(rel) \
580 ((rel)->reloptkind == RELOPT_OTHER_MEMBER_REL || \
581 (rel)->reloptkind == RELOPT_OTHER_JOINREL || \
582 (rel)->reloptkind == RELOPT_OTHER_UPPER_REL)
584 typedef struct RelOptInfo
588 RelOptKind reloptkind;
590 /* all relations included in this RelOptInfo */
591 Relids relids; /* set of base relids (rangetable indexes) */
593 /* size estimates generated by planner */
594 double rows; /* estimated number of result tuples */
596 /* per-relation planner control flags */
597 bool consider_startup; /* keep cheap-startup-cost paths? */
598 bool consider_param_startup; /* ditto, for parameterized paths? */
599 bool consider_parallel; /* consider parallel paths? */
601 /* default result targetlist for Paths scanning this relation */
602 struct PathTarget *reltarget; /* list of Vars/Exprs, cost, width */
604 /* materialization information */
605 List *pathlist; /* Path structures */
606 List *ppilist; /* ParamPathInfos used in pathlist */
607 List *partial_pathlist; /* partial Paths */
608 struct Path *cheapest_startup_path;
609 struct Path *cheapest_total_path;
610 struct Path *cheapest_unique_path;
611 List *cheapest_parameterized_paths;
613 /* parameterization information needed for both base rels and join rels */
614 /* (see also lateral_vars and lateral_referencers) */
615 Relids direct_lateral_relids; /* rels directly laterally referenced */
616 Relids lateral_relids; /* minimum parameterization of rel */
618 /* information about a base rel (not set for join rels!) */
620 Oid reltablespace; /* containing tablespace */
621 RTEKind rtekind; /* RELATION, SUBQUERY, FUNCTION, etc */
622 AttrNumber min_attr; /* smallest attrno of rel (often <0) */
623 AttrNumber max_attr; /* largest attrno of rel */
624 Relids *attr_needed; /* array indexed [min_attr .. max_attr] */
625 int32 *attr_widths; /* array indexed [min_attr .. max_attr] */
626 List *lateral_vars; /* LATERAL Vars and PHVs referenced by rel */
627 Relids lateral_referencers; /* rels that reference me laterally */
628 List *indexlist; /* list of IndexOptInfo */
629 List *statlist; /* list of StatisticExtInfo */
630 BlockNumber pages; /* size estimates derived from pg_class */
633 PlannerInfo *subroot; /* if subquery */
634 List *subplan_params; /* if subquery */
635 int rel_parallel_workers; /* wanted number of parallel workers */
637 /* Information about foreign tables and foreign joins */
638 Oid serverid; /* identifies server for the table or join */
639 Oid userid; /* identifies user to check access as */
640 bool useridiscurrent; /* join is only valid for current user */
641 /* use "struct FdwRoutine" to avoid including fdwapi.h here */
642 struct FdwRoutine *fdwroutine;
645 /* cache space for remembering if we have proven this relation unique */
646 List *unique_for_rels; /* known unique for these other relid
648 List *non_unique_for_rels; /* known not unique for these set(s) */
650 /* used by various scans and joins: */
651 List *baserestrictinfo; /* RestrictInfo structures (if base rel) */
652 QualCost baserestrictcost; /* cost of evaluating the above */
653 Index baserestrict_min_security; /* min security_level found in
654 * baserestrictinfo */
655 List *joininfo; /* RestrictInfo structures for join clauses
656 * involving this rel */
657 bool has_eclass_joins; /* T means joininfo is incomplete */
659 /* used by "other" relations */
660 Relids top_parent_relids; /* Relids of topmost parents */
662 /* used for partitioned relations */
663 PartitionScheme part_scheme; /* Partitioning scheme. */
664 int nparts; /* number of partitions */
665 struct PartitionBoundInfoData *boundinfo; /* Partition bounds */
666 struct RelOptInfo **part_rels; /* Array of RelOptInfos of partitions,
667 * stored in the same order of bounds */
668 List **partexprs; /* Non-nullable partition key expressions. */
669 List **nullable_partexprs; /* Nullable partition key expressions. */
673 * Is given relation partitioned?
675 * It's not enough to test whether rel->part_scheme is set, because it might
676 * be that the basic partitioning properties of the input relations matched
677 * but the partition bounds did not.
679 * We treat dummy relations as unpartitioned. We could alternatively
680 * treat them as partitioned, but it's not clear whether that's a useful thing
683 #define IS_PARTITIONED_REL(rel) \
684 ((rel)->part_scheme && (rel)->boundinfo && (rel)->nparts > 0 && \
685 (rel)->part_rels && !(IS_DUMMY_REL(rel)))
688 * Convenience macro to make sure that a partitioned relation has all the
689 * required members set.
691 #define REL_HAS_ALL_PART_PROPS(rel) \
692 ((rel)->part_scheme && (rel)->boundinfo && (rel)->nparts > 0 && \
693 (rel)->part_rels && (rel)->partexprs && (rel)->nullable_partexprs)
697 * Per-index information for planning/optimization
699 * indexkeys[], indexcollations[], opfamily[], and opcintype[]
700 * each have ncolumns entries.
702 * sortopfamily[], reverse_sort[], and nulls_first[] likewise have
703 * ncolumns entries, if the index is ordered; but if it is unordered,
704 * those pointers are NULL.
706 * Zeroes in the indexkeys[] array indicate index columns that are
707 * expressions; there is one element in indexprs for each such column.
709 * For an ordered index, reverse_sort[] and nulls_first[] describe the
710 * sort ordering of a forward indexscan; we can also consider a backward
711 * indexscan, which will generate the reverse ordering.
713 * The indexprs and indpred expressions have been run through
714 * prepqual.c and eval_const_expressions() for ease of matching to
715 * WHERE clauses. indpred is in implicit-AND form.
717 * indextlist is a TargetEntry list representing the index columns.
718 * It provides an equivalent base-relation Var for each simple column,
719 * and links to the matching indexprs element for each expression column.
721 * While most of these fields are filled when the IndexOptInfo is created
722 * (by plancat.c), indrestrictinfo and predOK are set later, in
723 * check_index_predicates().
725 typedef struct IndexOptInfo
729 Oid indexoid; /* OID of the index relation */
730 Oid reltablespace; /* tablespace of index (not table) */
731 RelOptInfo *rel; /* back-link to index's table */
733 /* index-size statistics (from pg_class and elsewhere) */
734 BlockNumber pages; /* number of disk pages in index */
735 double tuples; /* number of index tuples in index */
736 int tree_height; /* index tree height, or -1 if unknown */
738 /* index descriptor information */
739 int ncolumns; /* number of columns in index */
740 int *indexkeys; /* column numbers of index's keys, or 0 */
741 Oid *indexcollations; /* OIDs of collations of index columns */
742 Oid *opfamily; /* OIDs of operator families for columns */
743 Oid *opcintype; /* OIDs of opclass declared input data types */
744 Oid *sortopfamily; /* OIDs of btree opfamilies, if orderable */
745 bool *reverse_sort; /* is sort order descending? */
746 bool *nulls_first; /* do NULLs come first in the sort order? */
747 bool *canreturn; /* which index cols can be returned in an
748 * index-only scan? */
749 Oid relam; /* OID of the access method (in pg_am) */
751 List *indexprs; /* expressions for non-simple index columns */
752 List *indpred; /* predicate if a partial index, else NIL */
754 List *indextlist; /* targetlist representing index columns */
756 List *indrestrictinfo; /* parent relation's baserestrictinfo
757 * list, less any conditions implied by
758 * the index's predicate (unless it's a
759 * target rel, see comments in
760 * check_index_predicates()) */
762 bool predOK; /* true if index predicate matches query */
763 bool unique; /* true if a unique index */
764 bool immediate; /* is uniqueness enforced immediately? */
765 bool hypothetical; /* true if index doesn't really exist */
767 /* Remaining fields are copied from the index AM's API struct: */
768 bool amcanorderbyop; /* does AM support order by operator result? */
769 bool amoptionalkey; /* can query omit key for the first column? */
770 bool amsearcharray; /* can AM handle ScalarArrayOpExpr quals? */
771 bool amsearchnulls; /* can AM search for NULL/NOT NULL entries? */
772 bool amhasgettuple; /* does AM have amgettuple interface? */
773 bool amhasgetbitmap; /* does AM have amgetbitmap interface? */
774 bool amcanparallel; /* does AM support parallel scan? */
775 /* Rather than include amapi.h here, we declare amcostestimate like this */
776 void (*amcostestimate) (); /* AM's cost estimator */
781 * Per-foreign-key information for planning/optimization
783 * The per-FK-column arrays can be fixed-size because we allow at most
784 * INDEX_MAX_KEYS columns in a foreign key constraint. Each array has
785 * nkeys valid entries.
787 typedef struct ForeignKeyOptInfo
791 /* Basic data about the foreign key (fetched from catalogs): */
792 Index con_relid; /* RT index of the referencing table */
793 Index ref_relid; /* RT index of the referenced table */
794 int nkeys; /* number of columns in the foreign key */
795 AttrNumber conkey[INDEX_MAX_KEYS]; /* cols in referencing table */
796 AttrNumber confkey[INDEX_MAX_KEYS]; /* cols in referenced table */
797 Oid conpfeqop[INDEX_MAX_KEYS]; /* PK = FK operator OIDs */
799 /* Derived info about whether FK's equality conditions match the query: */
800 int nmatched_ec; /* # of FK cols matched by ECs */
801 int nmatched_rcols; /* # of FK cols matched by non-EC rinfos */
802 int nmatched_ri; /* total # of non-EC rinfos matched to FK */
803 /* Pointer to eclass matching each column's condition, if there is one */
804 struct EquivalenceClass *eclass[INDEX_MAX_KEYS];
805 /* List of non-EC RestrictInfos matching each column's condition */
806 List *rinfos[INDEX_MAX_KEYS];
811 * Information about extended statistics for planning/optimization
813 * Each pg_statistic_ext row is represented by one or more nodes of this
814 * type, or even zero if ANALYZE has not computed them.
816 typedef struct StatisticExtInfo
820 Oid statOid; /* OID of the statistics row */
821 RelOptInfo *rel; /* back-link to statistic's table */
822 char kind; /* statistic kind of this entry */
823 Bitmapset *keys; /* attnums of the columns covered */
829 * Whenever we can determine that a mergejoinable equality clause A = B is
830 * not delayed by any outer join, we create an EquivalenceClass containing
831 * the expressions A and B to record this knowledge. If we later find another
832 * equivalence B = C, we add C to the existing EquivalenceClass; this may
833 * require merging two existing EquivalenceClasses. At the end of the qual
834 * distribution process, we have sets of values that are known all transitively
835 * equal to each other, where "equal" is according to the rules of the btree
836 * operator family(s) shown in ec_opfamilies, as well as the collation shown
837 * by ec_collation. (We restrict an EC to contain only equalities whose
838 * operators belong to the same set of opfamilies. This could probably be
839 * relaxed, but for now it's not worth the trouble, since nearly all equality
840 * operators belong to only one btree opclass anyway. Similarly, we suppose
841 * that all or none of the input datatypes are collatable, so that a single
842 * collation value is sufficient.)
844 * We also use EquivalenceClasses as the base structure for PathKeys, letting
845 * us represent knowledge about different sort orderings being equivalent.
846 * Since every PathKey must reference an EquivalenceClass, we will end up
847 * with single-member EquivalenceClasses whenever a sort key expression has
848 * not been equivalenced to anything else. It is also possible that such an
849 * EquivalenceClass will contain a volatile expression ("ORDER BY random()"),
850 * which is a case that can't arise otherwise since clauses containing
851 * volatile functions are never considered mergejoinable. We mark such
852 * EquivalenceClasses specially to prevent them from being merged with
853 * ordinary EquivalenceClasses. Also, for volatile expressions we have
854 * to be careful to match the EquivalenceClass to the correct targetlist
855 * entry: consider SELECT random() AS a, random() AS b ... ORDER BY b,a.
856 * So we record the SortGroupRef of the originating sort clause.
858 * We allow equality clauses appearing below the nullable side of an outer join
859 * to form EquivalenceClasses, but these have a slightly different meaning:
860 * the included values might be all NULL rather than all the same non-null
861 * values. See src/backend/optimizer/README for more on that point.
863 * NB: if ec_merged isn't NULL, this class has been merged into another, and
864 * should be ignored in favor of using the pointed-to class.
866 typedef struct EquivalenceClass
870 List *ec_opfamilies; /* btree operator family OIDs */
871 Oid ec_collation; /* collation, if datatypes are collatable */
872 List *ec_members; /* list of EquivalenceMembers */
873 List *ec_sources; /* list of generating RestrictInfos */
874 List *ec_derives; /* list of derived RestrictInfos */
875 Relids ec_relids; /* all relids appearing in ec_members, except
876 * for child members (see below) */
877 bool ec_has_const; /* any pseudoconstants in ec_members? */
878 bool ec_has_volatile; /* the (sole) member is a volatile expr */
879 bool ec_below_outer_join; /* equivalence applies below an OJ */
880 bool ec_broken; /* failed to generate needed clauses? */
881 Index ec_sortref; /* originating sortclause label, or 0 */
882 Index ec_min_security; /* minimum security_level in ec_sources */
883 Index ec_max_security; /* maximum security_level in ec_sources */
884 struct EquivalenceClass *ec_merged; /* set if merged into another EC */
888 * If an EC contains a const and isn't below-outer-join, any PathKey depending
889 * on it must be redundant, since there's only one possible value of the key.
891 #define EC_MUST_BE_REDUNDANT(eclass) \
892 ((eclass)->ec_has_const && !(eclass)->ec_below_outer_join)
895 * EquivalenceMember - one member expression of an EquivalenceClass
897 * em_is_child signifies that this element was built by transposing a member
898 * for an appendrel parent relation to represent the corresponding expression
899 * for an appendrel child. These members are used for determining the
900 * pathkeys of scans on the child relation and for explicitly sorting the
901 * child when necessary to build a MergeAppend path for the whole appendrel
902 * tree. An em_is_child member has no impact on the properties of the EC as a
903 * whole; in particular the EC's ec_relids field does NOT include the child
904 * relation. An em_is_child member should never be marked em_is_const nor
905 * cause ec_has_const or ec_has_volatile to be set, either. Thus, em_is_child
906 * members are not really full-fledged members of the EC, but just reflections
907 * or doppelgangers of real members. Most operations on EquivalenceClasses
908 * should ignore em_is_child members, and those that don't should test
909 * em_relids to make sure they only consider relevant members.
911 * em_datatype is usually the same as exprType(em_expr), but can be
912 * different when dealing with a binary-compatible opfamily; in particular
913 * anyarray_ops would never work without this. Use em_datatype when
914 * looking up a specific btree operator to work with this expression.
916 typedef struct EquivalenceMember
920 Expr *em_expr; /* the expression represented */
921 Relids em_relids; /* all relids appearing in em_expr */
922 Relids em_nullable_relids; /* nullable by lower outer joins */
923 bool em_is_const; /* expression is pseudoconstant? */
924 bool em_is_child; /* derived version for a child relation? */
925 Oid em_datatype; /* the "nominal type" used by the opfamily */
931 * The sort ordering of a path is represented by a list of PathKey nodes.
932 * An empty list implies no known ordering. Otherwise the first item
933 * represents the primary sort key, the second the first secondary sort key,
934 * etc. The value being sorted is represented by linking to an
935 * EquivalenceClass containing that value and including pk_opfamily among its
936 * ec_opfamilies. The EquivalenceClass tells which collation to use, too.
937 * This is a convenient method because it makes it trivial to detect
938 * equivalent and closely-related orderings. (See optimizer/README for more
941 * Note: pk_strategy is either BTLessStrategyNumber (for ASC) or
942 * BTGreaterStrategyNumber (for DESC). We assume that all ordering-capable
943 * index types will use btree-compatible strategy numbers.
945 typedef struct PathKey
949 EquivalenceClass *pk_eclass; /* the value that is ordered */
950 Oid pk_opfamily; /* btree opfamily defining the ordering */
951 int pk_strategy; /* sort direction (ASC or DESC) */
952 bool pk_nulls_first; /* do NULLs come before normal values? */
959 * This struct contains what we need to know during planning about the
960 * targetlist (output columns) that a Path will compute. Each RelOptInfo
961 * includes a default PathTarget, which its individual Paths may simply
962 * reference. However, in some cases a Path may compute outputs different
963 * from other Paths, and in that case we make a custom PathTarget for it.
964 * For example, an indexscan might return index expressions that would
965 * otherwise need to be explicitly calculated. (Note also that "upper"
966 * relations generally don't have useful default PathTargets.)
968 * exprs contains bare expressions; they do not have TargetEntry nodes on top,
969 * though those will appear in finished Plans.
971 * sortgrouprefs[] is an array of the same length as exprs, containing the
972 * corresponding sort/group refnos, or zeroes for expressions not referenced
973 * by sort/group clauses. If sortgrouprefs is NULL (which it generally is in
974 * RelOptInfo.reltarget targets; only upper-level Paths contain this info),
975 * we have not identified sort/group columns in this tlist. This allows us to
976 * deal with sort/group refnos when needed with less expense than including
977 * TargetEntry nodes in the exprs list.
979 typedef struct PathTarget
982 List *exprs; /* list of expressions to be computed */
983 Index *sortgrouprefs; /* corresponding sort/group refnos, or 0 */
984 QualCost cost; /* cost of evaluating the expressions */
985 int width; /* estimated avg width of result tuples */
988 /* Convenience macro to get a sort/group refno from a PathTarget */
989 #define get_pathtarget_sortgroupref(target, colno) \
990 ((target)->sortgrouprefs ? (target)->sortgrouprefs[colno] : (Index) 0)
996 * All parameterized paths for a given relation with given required outer rels
997 * link to a single ParamPathInfo, which stores common information such as
998 * the estimated rowcount for this parameterization. We do this partly to
999 * avoid recalculations, but mostly to ensure that the estimated rowcount
1000 * is in fact the same for every such path.
1002 * Note: ppi_clauses is only used in ParamPathInfos for base relation paths;
1003 * in join cases it's NIL because the set of relevant clauses varies depending
1004 * on how the join is formed. The relevant clauses will appear in each
1005 * parameterized join path's joinrestrictinfo list, instead.
1007 typedef struct ParamPathInfo
1011 Relids ppi_req_outer; /* rels supplying parameters used by path */
1012 double ppi_rows; /* estimated number of result tuples */
1013 List *ppi_clauses; /* join clauses available from outer rels */
1018 * Type "Path" is used as-is for sequential-scan paths, as well as some other
1019 * simple plan types that we don't need any extra information in the path for.
1020 * For other path types it is the first component of a larger struct.
1022 * "pathtype" is the NodeTag of the Plan node we could build from this Path.
1023 * It is partially redundant with the Path's NodeTag, but allows us to use
1024 * the same Path type for multiple Plan types when there is no need to
1025 * distinguish the Plan type during path processing.
1027 * "parent" identifies the relation this Path scans, and "pathtarget"
1028 * describes the precise set of output columns the Path would compute.
1029 * In simple cases all Paths for a given rel share the same targetlist,
1030 * which we represent by having path->pathtarget equal to parent->reltarget.
1032 * "param_info", if not NULL, links to a ParamPathInfo that identifies outer
1033 * relation(s) that provide parameter values to each scan of this path.
1034 * That means this path can only be joined to those rels by means of nestloop
1035 * joins with this path on the inside. Also note that a parameterized path
1036 * is responsible for testing all "movable" joinclauses involving this rel
1037 * and the specified outer rel(s).
1039 * "rows" is the same as parent->rows in simple paths, but in parameterized
1040 * paths and UniquePaths it can be less than parent->rows, reflecting the
1041 * fact that we've filtered by extra join conditions or removed duplicates.
1043 * "pathkeys" is a List of PathKey nodes (see above), describing the sort
1044 * ordering of the path's output rows.
1050 NodeTag pathtype; /* tag identifying scan/join method */
1052 RelOptInfo *parent; /* the relation this path can build */
1053 PathTarget *pathtarget; /* list of Vars/Exprs, cost, width */
1055 ParamPathInfo *param_info; /* parameterization info, or NULL if none */
1057 bool parallel_aware; /* engage parallel-aware logic? */
1058 bool parallel_safe; /* OK to use as part of parallel plan? */
1059 int parallel_workers; /* desired # of workers; 0 = not parallel */
1061 /* estimated size/costs for path (see costsize.c for more info) */
1062 double rows; /* estimated number of result tuples */
1063 Cost startup_cost; /* cost expended before fetching any tuples */
1064 Cost total_cost; /* total cost (assuming all tuples fetched) */
1066 List *pathkeys; /* sort ordering of path's output */
1067 /* pathkeys is a List of PathKey nodes; see above */
1070 /* Macro for extracting a path's parameterization relids; beware double eval */
1071 #define PATH_REQ_OUTER(path) \
1072 ((path)->param_info ? (path)->param_info->ppi_req_outer : (Relids) NULL)
1075 * IndexPath represents an index scan over a single index.
1077 * This struct is used for both regular indexscans and index-only scans;
1078 * path.pathtype is T_IndexScan or T_IndexOnlyScan to show which is meant.
1080 * 'indexinfo' is the index to be scanned.
1082 * 'indexclauses' is a list of index qualification clauses, with implicit
1083 * AND semantics across the list. Each clause is a RestrictInfo node from
1084 * the query's WHERE or JOIN conditions. An empty list implies a full
1087 * 'indexquals' has the same structure as 'indexclauses', but it contains
1088 * the actual index qual conditions that can be used with the index.
1089 * In simple cases this is identical to 'indexclauses', but when special
1090 * indexable operators appear in 'indexclauses', they are replaced by the
1091 * derived indexscannable conditions in 'indexquals'.
1093 * 'indexqualcols' is an integer list of index column numbers (zero-based)
1094 * of the same length as 'indexquals', showing which index column each qual
1095 * is meant to be used with. 'indexquals' is required to be ordered by
1096 * index column, so 'indexqualcols' must form a nondecreasing sequence.
1097 * (The order of multiple quals for the same index column is unspecified.)
1099 * 'indexorderbys', if not NIL, is a list of ORDER BY expressions that have
1100 * been found to be usable as ordering operators for an amcanorderbyop index.
1101 * The list must match the path's pathkeys, ie, one expression per pathkey
1102 * in the same order. These are not RestrictInfos, just bare expressions,
1103 * since they generally won't yield booleans. Also, unlike the case for
1104 * quals, it's guaranteed that each expression has the index key on the left
1105 * side of the operator.
1107 * 'indexorderbycols' is an integer list of index column numbers (zero-based)
1108 * of the same length as 'indexorderbys', showing which index column each
1109 * ORDER BY expression is meant to be used with. (There is no restriction
1110 * on which index column each ORDER BY can be used with.)
1112 * 'indexscandir' is one of:
1113 * ForwardScanDirection: forward scan of an ordered index
1114 * BackwardScanDirection: backward scan of an ordered index
1115 * NoMovementScanDirection: scan of an unordered index, or don't care
1116 * (The executor doesn't care whether it gets ForwardScanDirection or
1117 * NoMovementScanDirection for an indexscan, but the planner wants to
1118 * distinguish ordered from unordered indexes for building pathkeys.)
1120 * 'indextotalcost' and 'indexselectivity' are saved in the IndexPath so that
1121 * we need not recompute them when considering using the same index in a
1122 * bitmap index/heap scan (see BitmapHeapPath). The costs of the IndexPath
1123 * itself represent the costs of an IndexScan or IndexOnlyScan plan type.
1126 typedef struct IndexPath
1129 IndexOptInfo *indexinfo;
1132 List *indexqualcols;
1133 List *indexorderbys;
1134 List *indexorderbycols;
1135 ScanDirection indexscandir;
1136 Cost indextotalcost;
1137 Selectivity indexselectivity;
1141 * BitmapHeapPath represents one or more indexscans that generate TID bitmaps
1142 * instead of directly accessing the heap, followed by AND/OR combinations
1143 * to produce a single bitmap, followed by a heap scan that uses the bitmap.
1144 * Note that the output is always considered unordered, since it will come
1145 * out in physical heap order no matter what the underlying indexes did.
1147 * The individual indexscans are represented by IndexPath nodes, and any
1148 * logic on top of them is represented by a tree of BitmapAndPath and
1149 * BitmapOrPath nodes. Notice that we can use the same IndexPath node both
1150 * to represent a regular (or index-only) index scan plan, and as the child
1151 * of a BitmapHeapPath that represents scanning the same index using a
1152 * BitmapIndexScan. The startup_cost and total_cost figures of an IndexPath
1153 * always represent the costs to use it as a regular (or index-only)
1154 * IndexScan. The costs of a BitmapIndexScan can be computed using the
1155 * IndexPath's indextotalcost and indexselectivity.
1157 typedef struct BitmapHeapPath
1160 Path *bitmapqual; /* IndexPath, BitmapAndPath, BitmapOrPath */
1164 * BitmapAndPath represents a BitmapAnd plan node; it can only appear as
1165 * part of the substructure of a BitmapHeapPath. The Path structure is
1166 * a bit more heavyweight than we really need for this, but for simplicity
1167 * we make it a derivative of Path anyway.
1169 typedef struct BitmapAndPath
1172 List *bitmapquals; /* IndexPaths and BitmapOrPaths */
1173 Selectivity bitmapselectivity;
1177 * BitmapOrPath represents a BitmapOr plan node; it can only appear as
1178 * part of the substructure of a BitmapHeapPath. The Path structure is
1179 * a bit more heavyweight than we really need for this, but for simplicity
1180 * we make it a derivative of Path anyway.
1182 typedef struct BitmapOrPath
1185 List *bitmapquals; /* IndexPaths and BitmapAndPaths */
1186 Selectivity bitmapselectivity;
1190 * TidPath represents a scan by TID
1192 * tidquals is an implicitly OR'ed list of qual expressions of the form
1193 * "CTID = pseudoconstant" or "CTID = ANY(pseudoconstant_array)".
1194 * Note they are bare expressions, not RestrictInfos.
1196 typedef struct TidPath
1199 List *tidquals; /* qual(s) involving CTID = something */
1203 * SubqueryScanPath represents a scan of an unflattened subquery-in-FROM
1205 * Note that the subpath comes from a different planning domain; for example
1206 * RTE indexes within it mean something different from those known to the
1207 * SubqueryScanPath. path.parent->subroot is the planning context needed to
1208 * interpret the subpath.
1210 typedef struct SubqueryScanPath
1213 Path *subpath; /* path representing subquery execution */
1217 * ForeignPath represents a potential scan of a foreign table, foreign join
1218 * or foreign upper-relation.
1220 * fdw_private stores FDW private data about the scan. While fdw_private is
1221 * not actually touched by the core code during normal operations, it's
1222 * generally a good idea to use a representation that can be dumped by
1223 * nodeToString(), so that you can examine the structure during debugging
1224 * with tools like pprint().
1226 typedef struct ForeignPath
1229 Path *fdw_outerpath;
1234 * CustomPath represents a table scan done by some out-of-core extension.
1236 * We provide a set of hooks here - which the provider must take care to set
1237 * up correctly - to allow extensions to supply their own methods of scanning
1238 * a relation. For example, a provider might provide GPU acceleration, a
1239 * cache-based scan, or some other kind of logic we haven't dreamed up yet.
1241 * CustomPaths can be injected into the planning process for a relation by
1242 * set_rel_pathlist_hook functions.
1244 * Core code must avoid assuming that the CustomPath is only as large as
1245 * the structure declared here; providers are allowed to make it the first
1246 * element in a larger structure. (Since the planner never copies Paths,
1247 * this doesn't add any complication.) However, for consistency with the
1248 * FDW case, we provide a "custom_private" field in CustomPath; providers
1249 * may prefer to use that rather than define another struct type.
1252 struct CustomPathMethods;
1254 typedef struct CustomPath
1257 uint32 flags; /* mask of CUSTOMPATH_* flags, see
1258 * nodes/extensible.h */
1259 List *custom_paths; /* list of child Path nodes, if any */
1260 List *custom_private;
1261 const struct CustomPathMethods *methods;
1265 * AppendPath represents an Append plan, ie, successive execution of
1266 * several member plans.
1268 * For partial Append, 'subpaths' contains non-partial subpaths followed by
1271 * Note: it is possible for "subpaths" to contain only one, or even no,
1272 * elements. These cases are optimized during create_append_plan.
1273 * In particular, an AppendPath with no subpaths is a "dummy" path that
1274 * is created to represent the case that a relation is provably empty.
1276 typedef struct AppendPath
1279 /* RT indexes of non-leaf tables in a partition tree */
1280 List *partitioned_rels;
1281 List *subpaths; /* list of component Paths */
1283 /* Index of first partial path in subpaths */
1284 int first_partial_path;
1287 #define IS_DUMMY_PATH(p) \
1288 (IsA((p), AppendPath) && ((AppendPath *) (p))->subpaths == NIL)
1290 /* A relation that's been proven empty will have one path that is dummy */
1291 #define IS_DUMMY_REL(r) \
1292 ((r)->cheapest_total_path != NULL && \
1293 IS_DUMMY_PATH((r)->cheapest_total_path))
1296 * MergeAppendPath represents a MergeAppend plan, ie, the merging of sorted
1297 * results from several member plans to produce similarly-sorted output.
1299 typedef struct MergeAppendPath
1302 /* RT indexes of non-leaf tables in a partition tree */
1303 List *partitioned_rels;
1304 List *subpaths; /* list of component Paths */
1305 double limit_tuples; /* hard limit on output tuples, or -1 */
1309 * ResultPath represents use of a Result plan node to compute a variable-free
1310 * targetlist with no underlying tables (a "SELECT expressions" query).
1311 * The query could have a WHERE clause, too, represented by "quals".
1313 * Note that quals is a list of bare clauses, not RestrictInfos.
1315 typedef struct ResultPath
1322 * MaterialPath represents use of a Material plan node, i.e., caching of
1323 * the output of its subpath. This is used when the subpath is expensive
1324 * and needs to be scanned repeatedly, or when we need mark/restore ability
1325 * and the subpath doesn't have it.
1327 typedef struct MaterialPath
1334 * UniquePath represents elimination of distinct rows from the output of
1337 * This can represent significantly different plans: either hash-based or
1338 * sort-based implementation, or a no-op if the input path can be proven
1339 * distinct already. The decision is sufficiently localized that it's not
1340 * worth having separate Path node types. (Note: in the no-op case, we could
1341 * eliminate the UniquePath node entirely and just return the subpath; but
1342 * it's convenient to have a UniquePath in the path tree to signal upper-level
1343 * routines that the input is known distinct.)
1347 UNIQUE_PATH_NOOP, /* input is known unique already */
1348 UNIQUE_PATH_HASH, /* use hashing */
1349 UNIQUE_PATH_SORT /* use sorting */
1352 typedef struct UniquePath
1356 UniquePathMethod umethod;
1357 List *in_operators; /* equality operators of the IN clause */
1358 List *uniq_exprs; /* expressions to be made unique */
1362 * GatherPath runs several copies of a plan in parallel and collects the
1363 * results. The parallel leader may also execute the plan, unless the
1364 * single_copy flag is set.
1366 typedef struct GatherPath
1369 Path *subpath; /* path for each worker */
1370 bool single_copy; /* don't execute path more than once */
1371 int num_workers; /* number of workers sought to help */
1375 * GatherMergePath runs several copies of a plan in parallel and collects
1376 * the results, preserving their common sort order. For gather merge, the
1377 * parallel leader always executes the plan too, so we don't need single_copy.
1379 typedef struct GatherMergePath
1382 Path *subpath; /* path for each worker */
1383 int num_workers; /* number of workers sought to help */
1388 * All join-type paths share these fields.
1391 typedef struct JoinPath
1397 bool inner_unique; /* each outer tuple provably matches no more
1398 * than one inner tuple */
1400 Path *outerjoinpath; /* path for the outer side of the join */
1401 Path *innerjoinpath; /* path for the inner side of the join */
1403 List *joinrestrictinfo; /* RestrictInfos to apply to join */
1406 * See the notes for RelOptInfo and ParamPathInfo to understand why
1407 * joinrestrictinfo is needed in JoinPath, and can't be merged into the
1408 * parent RelOptInfo.
1413 * A nested-loop path needs no special fields.
1416 typedef JoinPath NestPath;
1419 * A mergejoin path has these fields.
1421 * Unlike other path types, a MergePath node doesn't represent just a single
1422 * run-time plan node: it can represent up to four. Aside from the MergeJoin
1423 * node itself, there can be a Sort node for the outer input, a Sort node
1424 * for the inner input, and/or a Material node for the inner input. We could
1425 * represent these nodes by separate path nodes, but considering how many
1426 * different merge paths are investigated during a complex join problem,
1427 * it seems better to avoid unnecessary palloc overhead.
1429 * path_mergeclauses lists the clauses (in the form of RestrictInfos)
1430 * that will be used in the merge.
1432 * Note that the mergeclauses are a subset of the parent relation's
1433 * restriction-clause list. Any join clauses that are not mergejoinable
1434 * appear only in the parent's restrict list, and must be checked by a
1435 * qpqual at execution time.
1437 * outersortkeys (resp. innersortkeys) is NIL if the outer path
1438 * (resp. inner path) is already ordered appropriately for the
1439 * mergejoin. If it is not NIL then it is a PathKeys list describing
1440 * the ordering that must be created by an explicit Sort node.
1442 * skip_mark_restore is true if the executor need not do mark/restore calls.
1443 * Mark/restore overhead is usually required, but can be skipped if we know
1444 * that the executor need find only one match per outer tuple, and that the
1445 * mergeclauses are sufficient to identify a match. In such cases the
1446 * executor can immediately advance the outer relation after processing a
1447 * match, and therefoere it need never back up the inner relation.
1449 * materialize_inner is true if a Material node should be placed atop the
1450 * inner input. This may appear with or without an inner Sort step.
1453 typedef struct MergePath
1456 List *path_mergeclauses; /* join clauses to be used for merge */
1457 List *outersortkeys; /* keys for explicit sort, if any */
1458 List *innersortkeys; /* keys for explicit sort, if any */
1459 bool skip_mark_restore; /* can executor skip mark/restore? */
1460 bool materialize_inner; /* add Materialize to inner? */
1464 * A hashjoin path has these fields.
1466 * The remarks above for mergeclauses apply for hashclauses as well.
1468 * Hashjoin does not care what order its inputs appear in, so we have
1469 * no need for sortkeys.
1472 typedef struct HashPath
1475 List *path_hashclauses; /* join clauses used for hashing */
1476 int num_batches; /* number of batches expected */
1477 double inner_rows_total; /* total inner rows expected */
1481 * ProjectionPath represents a projection (that is, targetlist computation)
1483 * Nominally, this path node represents using a Result plan node to do a
1484 * projection step. However, if the input plan node supports projection,
1485 * we can just modify its output targetlist to do the required calculations
1486 * directly, and not need a Result. In some places in the planner we can just
1487 * jam the desired PathTarget into the input path node (and adjust its cost
1488 * accordingly), so we don't need a ProjectionPath. But in other places
1489 * it's necessary to not modify the input path node, so we need a separate
1490 * ProjectionPath node, which is marked dummy to indicate that we intend to
1491 * assign the work to the input plan node. The estimated cost for the
1492 * ProjectionPath node will account for whether a Result will be used or not.
1494 typedef struct ProjectionPath
1497 Path *subpath; /* path representing input source */
1498 bool dummypp; /* true if no separate Result is needed */
1502 * ProjectSetPath represents evaluation of a targetlist that includes
1503 * set-returning function(s), which will need to be implemented by a
1504 * ProjectSet plan node.
1506 typedef struct ProjectSetPath
1509 Path *subpath; /* path representing input source */
1513 * SortPath represents an explicit sort step
1515 * The sort keys are, by definition, the same as path.pathkeys.
1517 * Note: the Sort plan node cannot project, so path.pathtarget must be the
1518 * same as the input's pathtarget.
1520 typedef struct SortPath
1523 Path *subpath; /* path representing input source */
1527 * GroupPath represents grouping (of presorted input)
1529 * groupClause represents the columns to be grouped on; the input path
1530 * must be at least that well sorted.
1532 * We can also apply a qual to the grouped rows (equivalent of HAVING)
1534 typedef struct GroupPath
1537 Path *subpath; /* path representing input source */
1538 List *groupClause; /* a list of SortGroupClause's */
1539 List *qual; /* quals (HAVING quals), if any */
1543 * UpperUniquePath represents adjacent-duplicate removal (in presorted input)
1545 * The columns to be compared are the first numkeys columns of the path's
1546 * pathkeys. The input is presumed already sorted that way.
1548 typedef struct UpperUniquePath
1551 Path *subpath; /* path representing input source */
1552 int numkeys; /* number of pathkey columns to compare */
1556 * AggPath represents generic computation of aggregate functions
1558 * This may involve plain grouping (but not grouping sets), using either
1559 * sorted or hashed grouping; for the AGG_SORTED case, the input must be
1560 * appropriately presorted.
1562 typedef struct AggPath
1565 Path *subpath; /* path representing input source */
1566 AggStrategy aggstrategy; /* basic strategy, see nodes.h */
1567 AggSplit aggsplit; /* agg-splitting mode, see nodes.h */
1568 double numGroups; /* estimated number of groups in input */
1569 List *groupClause; /* a list of SortGroupClause's */
1570 List *qual; /* quals (HAVING quals), if any */
1574 * Various annotations used for grouping sets in the planner.
1577 typedef struct GroupingSetData
1580 List *set; /* grouping set as list of sortgrouprefs */
1581 double numGroups; /* est. number of result groups */
1584 typedef struct RollupData
1587 List *groupClause; /* applicable subset of parse->groupClause */
1588 List *gsets; /* lists of integer indexes into groupClause */
1589 List *gsets_data; /* list of GroupingSetData */
1590 double numGroups; /* est. number of result groups */
1591 bool hashable; /* can be hashed */
1592 bool is_hashed; /* to be implemented as a hashagg */
1596 * GroupingSetsPath represents a GROUPING SETS aggregation
1599 typedef struct GroupingSetsPath
1602 Path *subpath; /* path representing input source */
1603 AggStrategy aggstrategy; /* basic strategy */
1604 List *rollups; /* list of RollupData */
1605 List *qual; /* quals (HAVING quals), if any */
1609 * MinMaxAggPath represents computation of MIN/MAX aggregates from indexes
1611 typedef struct MinMaxAggPath
1614 List *mmaggregates; /* list of MinMaxAggInfo */
1615 List *quals; /* HAVING quals, if any */
1619 * WindowAggPath represents generic computation of window functions
1621 * Note: winpathkeys is separate from path.pathkeys because the actual sort
1622 * order might be an extension of winpathkeys; but createplan.c needs to
1623 * know exactly how many pathkeys match the window clause.
1625 typedef struct WindowAggPath
1628 Path *subpath; /* path representing input source */
1629 WindowClause *winclause; /* WindowClause we'll be using */
1630 List *winpathkeys; /* PathKeys for PARTITION keys + ORDER keys */
1634 * SetOpPath represents a set-operation, that is INTERSECT or EXCEPT
1636 typedef struct SetOpPath
1639 Path *subpath; /* path representing input source */
1640 SetOpCmd cmd; /* what to do, see nodes.h */
1641 SetOpStrategy strategy; /* how to do it, see nodes.h */
1642 List *distinctList; /* SortGroupClauses identifying target cols */
1643 AttrNumber flagColIdx; /* where is the flag column, if any */
1644 int firstFlag; /* flag value for first input relation */
1645 double numGroups; /* estimated number of groups in input */
1649 * RecursiveUnionPath represents a recursive UNION node
1651 typedef struct RecursiveUnionPath
1654 Path *leftpath; /* paths representing input sources */
1656 List *distinctList; /* SortGroupClauses identifying target cols */
1657 int wtParam; /* ID of Param representing work table */
1658 double numGroups; /* estimated number of groups in input */
1659 } RecursiveUnionPath;
1662 * LockRowsPath represents acquiring row locks for SELECT FOR UPDATE/SHARE
1664 typedef struct LockRowsPath
1667 Path *subpath; /* path representing input source */
1668 List *rowMarks; /* a list of PlanRowMark's */
1669 int epqParam; /* ID of Param for EvalPlanQual re-eval */
1673 * ModifyTablePath represents performing INSERT/UPDATE/DELETE modifications
1675 * We represent most things that will be in the ModifyTable plan node
1676 * literally, except we have child Path(s) not Plan(s). But analysis of the
1677 * OnConflictExpr is deferred to createplan.c, as is collection of FDW data.
1679 typedef struct ModifyTablePath
1682 CmdType operation; /* INSERT, UPDATE, or DELETE */
1683 bool canSetTag; /* do we set the command tag/es_processed? */
1684 Index nominalRelation; /* Parent RT index for use of EXPLAIN */
1685 /* RT indexes of non-leaf tables in a partition tree */
1686 List *partitioned_rels;
1687 bool partColsUpdated; /* some part key in hierarchy updated */
1688 List *resultRelations; /* integer list of RT indexes */
1689 List *subpaths; /* Path(s) producing source data */
1690 List *subroots; /* per-target-table PlannerInfos */
1691 List *withCheckOptionLists; /* per-target-table WCO lists */
1692 List *returningLists; /* per-target-table RETURNING tlists */
1693 List *rowMarks; /* PlanRowMarks (non-locking only) */
1694 OnConflictExpr *onconflict; /* ON CONFLICT clause, or NULL */
1695 int epqParam; /* ID of Param for EvalPlanQual re-eval */
1699 * LimitPath represents applying LIMIT/OFFSET restrictions
1701 typedef struct LimitPath
1704 Path *subpath; /* path representing input source */
1705 Node *limitOffset; /* OFFSET parameter, or NULL if none */
1706 Node *limitCount; /* COUNT parameter, or NULL if none */
1711 * Restriction clause info.
1713 * We create one of these for each AND sub-clause of a restriction condition
1714 * (WHERE or JOIN/ON clause). Since the restriction clauses are logically
1715 * ANDed, we can use any one of them or any subset of them to filter out
1716 * tuples, without having to evaluate the rest. The RestrictInfo node itself
1717 * stores data used by the optimizer while choosing the best query plan.
1719 * If a restriction clause references a single base relation, it will appear
1720 * in the baserestrictinfo list of the RelOptInfo for that base rel.
1722 * If a restriction clause references more than one base rel, it will
1723 * appear in the joininfo list of every RelOptInfo that describes a strict
1724 * subset of the base rels mentioned in the clause. The joininfo lists are
1725 * used to drive join tree building by selecting plausible join candidates.
1726 * The clause cannot actually be applied until we have built a join rel
1727 * containing all the base rels it references, however.
1729 * When we construct a join rel that includes all the base rels referenced
1730 * in a multi-relation restriction clause, we place that clause into the
1731 * joinrestrictinfo lists of paths for the join rel, if neither left nor
1732 * right sub-path includes all base rels referenced in the clause. The clause
1733 * will be applied at that join level, and will not propagate any further up
1734 * the join tree. (Note: the "predicate migration" code was once intended to
1735 * push restriction clauses up and down the plan tree based on evaluation
1736 * costs, but it's dead code and is unlikely to be resurrected in the
1737 * foreseeable future.)
1739 * Note that in the presence of more than two rels, a multi-rel restriction
1740 * might reach different heights in the join tree depending on the join
1741 * sequence we use. So, these clauses cannot be associated directly with
1742 * the join RelOptInfo, but must be kept track of on a per-join-path basis.
1744 * RestrictInfos that represent equivalence conditions (i.e., mergejoinable
1745 * equalities that are not outerjoin-delayed) are handled a bit differently.
1746 * Initially we attach them to the EquivalenceClasses that are derived from
1747 * them. When we construct a scan or join path, we look through all the
1748 * EquivalenceClasses and generate derived RestrictInfos representing the
1749 * minimal set of conditions that need to be checked for this particular scan
1750 * or join to enforce that all members of each EquivalenceClass are in fact
1751 * equal in all rows emitted by the scan or join.
1753 * When dealing with outer joins we have to be very careful about pushing qual
1754 * clauses up and down the tree. An outer join's own JOIN/ON conditions must
1755 * be evaluated exactly at that join node, unless they are "degenerate"
1756 * conditions that reference only Vars from the nullable side of the join.
1757 * Quals appearing in WHERE or in a JOIN above the outer join cannot be pushed
1758 * down below the outer join, if they reference any nullable Vars.
1759 * RestrictInfo nodes contain a flag to indicate whether a qual has been
1760 * pushed down to a lower level than its original syntactic placement in the
1761 * join tree would suggest. If an outer join prevents us from pushing a qual
1762 * down to its "natural" semantic level (the level associated with just the
1763 * base rels used in the qual) then we mark the qual with a "required_relids"
1764 * value including more than just the base rels it actually uses. By
1765 * pretending that the qual references all the rels required to form the outer
1766 * join, we prevent it from being evaluated below the outer join's joinrel.
1767 * When we do form the outer join's joinrel, we still need to distinguish
1768 * those quals that are actually in that join's JOIN/ON condition from those
1769 * that appeared elsewhere in the tree and were pushed down to the join rel
1770 * because they used no other rels. That's what the is_pushed_down flag is
1771 * for; it tells us that a qual is not an OUTER JOIN qual for the set of base
1772 * rels listed in required_relids. A clause that originally came from WHERE
1773 * or an INNER JOIN condition will *always* have its is_pushed_down flag set.
1774 * It's possible for an OUTER JOIN clause to be marked is_pushed_down too,
1775 * if we decide that it can be pushed down into the nullable side of the join.
1776 * In that case it acts as a plain filter qual for wherever it gets evaluated.
1777 * (In short, is_pushed_down is only false for non-degenerate outer join
1778 * conditions. Possibly we should rename it to reflect that meaning?)
1780 * RestrictInfo nodes also contain an outerjoin_delayed flag, which is true
1781 * if the clause's applicability must be delayed due to any outer joins
1782 * appearing below it (ie, it has to be postponed to some join level higher
1783 * than the set of relations it actually references).
1785 * There is also an outer_relids field, which is NULL except for outer join
1786 * clauses; for those, it is the set of relids on the outer side of the
1787 * clause's outer join. (These are rels that the clause cannot be applied to
1788 * in parameterized scans, since pushing it into the join's outer side would
1789 * lead to wrong answers.)
1791 * There is also a nullable_relids field, which is the set of rels the clause
1792 * references that can be forced null by some outer join below the clause.
1794 * outerjoin_delayed = true is subtly different from nullable_relids != NULL:
1795 * a clause might reference some nullable rels and yet not be
1796 * outerjoin_delayed because it also references all the other rels of the
1797 * outer join(s). A clause that is not outerjoin_delayed can be enforced
1798 * anywhere it is computable.
1800 * To handle security-barrier conditions efficiently, we mark RestrictInfo
1801 * nodes with a security_level field, in which higher values identify clauses
1802 * coming from less-trusted sources. The exact semantics are that a clause
1803 * cannot be evaluated before another clause with a lower security_level value
1804 * unless the first clause is leakproof. As with outer-join clauses, this
1805 * creates a reason for clauses to sometimes need to be evaluated higher in
1806 * the join tree than their contents would suggest; and even at a single plan
1807 * node, this rule constrains the order of application of clauses.
1809 * In general, the referenced clause might be arbitrarily complex. The
1810 * kinds of clauses we can handle as indexscan quals, mergejoin clauses,
1811 * or hashjoin clauses are limited (e.g., no volatile functions). The code
1812 * for each kind of path is responsible for identifying the restrict clauses
1813 * it can use and ignoring the rest. Clauses not implemented by an indexscan,
1814 * mergejoin, or hashjoin will be placed in the plan qual or joinqual field
1815 * of the finished Plan node, where they will be enforced by general-purpose
1816 * qual-expression-evaluation code. (But we are still entitled to count
1817 * their selectivity when estimating the result tuple count, if we
1818 * can guess what it is...)
1820 * When the referenced clause is an OR clause, we generate a modified copy
1821 * in which additional RestrictInfo nodes are inserted below the top-level
1822 * OR/AND structure. This is a convenience for OR indexscan processing:
1823 * indexquals taken from either the top level or an OR subclause will have
1824 * associated RestrictInfo nodes.
1826 * The can_join flag is set true if the clause looks potentially useful as
1827 * a merge or hash join clause, that is if it is a binary opclause with
1828 * nonoverlapping sets of relids referenced in the left and right sides.
1829 * (Whether the operator is actually merge or hash joinable isn't checked,
1832 * The pseudoconstant flag is set true if the clause contains no Vars of
1833 * the current query level and no volatile functions. Such a clause can be
1834 * pulled out and used as a one-time qual in a gating Result node. We keep
1835 * pseudoconstant clauses in the same lists as other RestrictInfos so that
1836 * the regular clause-pushing machinery can assign them to the correct join
1837 * level, but they need to be treated specially for cost and selectivity
1838 * estimates. Note that a pseudoconstant clause can never be an indexqual
1839 * or merge or hash join clause, so it's of no interest to large parts of
1842 * When join clauses are generated from EquivalenceClasses, there may be
1843 * several equally valid ways to enforce join equivalence, of which we need
1844 * apply only one. We mark clauses of this kind by setting parent_ec to
1845 * point to the generating EquivalenceClass. Multiple clauses with the same
1846 * parent_ec in the same join are redundant.
1849 typedef struct RestrictInfo
1853 Expr *clause; /* the represented clause of WHERE or JOIN */
1855 bool is_pushed_down; /* true if clause was pushed down in level */
1857 bool outerjoin_delayed; /* true if delayed by lower outer join */
1859 bool can_join; /* see comment above */
1861 bool pseudoconstant; /* see comment above */
1863 bool leakproof; /* true if known to contain no leaked Vars */
1865 Index security_level; /* see comment above */
1867 /* The set of relids (varnos) actually referenced in the clause: */
1868 Relids clause_relids;
1870 /* The set of relids required to evaluate the clause: */
1871 Relids required_relids;
1873 /* If an outer-join clause, the outer-side relations, else NULL: */
1874 Relids outer_relids;
1876 /* The relids used in the clause that are nullable by lower outer joins: */
1877 Relids nullable_relids;
1879 /* These fields are set for any binary opclause: */
1880 Relids left_relids; /* relids in left side of clause */
1881 Relids right_relids; /* relids in right side of clause */
1883 /* This field is NULL unless clause is an OR clause: */
1884 Expr *orclause; /* modified clause with RestrictInfos */
1886 /* This field is NULL unless clause is potentially redundant: */
1887 EquivalenceClass *parent_ec; /* generating EquivalenceClass */
1889 /* cache space for cost and selectivity */
1890 QualCost eval_cost; /* eval cost of clause; -1 if not yet set */
1891 Selectivity norm_selec; /* selectivity for "normal" (JOIN_INNER)
1892 * semantics; -1 if not yet set; >1 means a
1893 * redundant clause */
1894 Selectivity outer_selec; /* selectivity for outer join semantics; -1 if
1897 /* valid if clause is mergejoinable, else NIL */
1898 List *mergeopfamilies; /* opfamilies containing clause operator */
1900 /* cache space for mergeclause processing; NULL if not yet set */
1901 EquivalenceClass *left_ec; /* EquivalenceClass containing lefthand */
1902 EquivalenceClass *right_ec; /* EquivalenceClass containing righthand */
1903 EquivalenceMember *left_em; /* EquivalenceMember for lefthand */
1904 EquivalenceMember *right_em; /* EquivalenceMember for righthand */
1905 List *scansel_cache; /* list of MergeScanSelCache structs */
1907 /* transient workspace for use while considering a specific join path */
1908 bool outer_is_left; /* T = outer var on left, F = on right */
1910 /* valid if clause is hashjoinable, else InvalidOid: */
1911 Oid hashjoinoperator; /* copy of clause operator */
1913 /* cache space for hashclause processing; -1 if not yet set */
1914 Selectivity left_bucketsize; /* avg bucketsize of left side */
1915 Selectivity right_bucketsize; /* avg bucketsize of right side */
1916 Selectivity left_mcvfreq; /* left side's most common val's freq */
1917 Selectivity right_mcvfreq; /* right side's most common val's freq */
1921 * Since mergejoinscansel() is a relatively expensive function, and would
1922 * otherwise be invoked many times while planning a large join tree,
1923 * we go out of our way to cache its results. Each mergejoinable
1924 * RestrictInfo carries a list of the specific sort orderings that have
1925 * been considered for use with it, and the resulting selectivities.
1927 typedef struct MergeScanSelCache
1929 /* Ordering details (cache lookup key) */
1930 Oid opfamily; /* btree opfamily defining the ordering */
1931 Oid collation; /* collation for the ordering */
1932 int strategy; /* sort direction (ASC or DESC) */
1933 bool nulls_first; /* do NULLs come before normal values? */
1935 Selectivity leftstartsel; /* first-join fraction for clause left side */
1936 Selectivity leftendsel; /* last-join fraction for clause left side */
1937 Selectivity rightstartsel; /* first-join fraction for clause right side */
1938 Selectivity rightendsel; /* last-join fraction for clause right side */
1939 } MergeScanSelCache;
1942 * Placeholder node for an expression to be evaluated below the top level
1943 * of a plan tree. This is used during planning to represent the contained
1944 * expression. At the end of the planning process it is replaced by either
1945 * the contained expression or a Var referring to a lower-level evaluation of
1946 * the contained expression. Typically the evaluation occurs below an outer
1947 * join, and Var references above the outer join might thereby yield NULL
1948 * instead of the expression value.
1950 * Although the planner treats this as an expression node type, it is not
1951 * recognized by the parser or executor, so we declare it here rather than
1955 typedef struct PlaceHolderVar
1958 Expr *phexpr; /* the represented expression */
1959 Relids phrels; /* base relids syntactically within expr src */
1960 Index phid; /* ID for PHV (unique within planner run) */
1961 Index phlevelsup; /* > 0 if PHV belongs to outer query */
1965 * "Special join" info.
1967 * One-sided outer joins constrain the order of joining partially but not
1968 * completely. We flatten such joins into the planner's top-level list of
1969 * relations to join, but record information about each outer join in a
1970 * SpecialJoinInfo struct. These structs are kept in the PlannerInfo node's
1973 * Similarly, semijoins and antijoins created by flattening IN (subselect)
1974 * and EXISTS(subselect) clauses create partial constraints on join order.
1975 * These are likewise recorded in SpecialJoinInfo structs.
1977 * We make SpecialJoinInfos for FULL JOINs even though there is no flexibility
1978 * of planning for them, because this simplifies make_join_rel()'s API.
1980 * min_lefthand and min_righthand are the sets of base relids that must be
1981 * available on each side when performing the special join. lhs_strict is
1982 * true if the special join's condition cannot succeed when the LHS variables
1983 * are all NULL (this means that an outer join can commute with upper-level
1984 * outer joins even if it appears in their RHS). We don't bother to set
1985 * lhs_strict for FULL JOINs, however.
1987 * It is not valid for either min_lefthand or min_righthand to be empty sets;
1988 * if they were, this would break the logic that enforces join order.
1990 * syn_lefthand and syn_righthand are the sets of base relids that are
1991 * syntactically below this special join. (These are needed to help compute
1992 * min_lefthand and min_righthand for higher joins.)
1994 * delay_upper_joins is set true if we detect a pushed-down clause that has
1995 * to be evaluated after this join is formed (because it references the RHS).
1996 * Any outer joins that have such a clause and this join in their RHS cannot
1997 * commute with this join, because that would leave noplace to check the
1998 * pushed-down clause. (We don't track this for FULL JOINs, either.)
2000 * For a semijoin, we also extract the join operators and their RHS arguments
2001 * and set semi_operators, semi_rhs_exprs, semi_can_btree, and semi_can_hash.
2002 * This is done in support of possibly unique-ifying the RHS, so we don't
2003 * bother unless at least one of semi_can_btree and semi_can_hash can be set
2004 * true. (You might expect that this information would be computed during
2005 * join planning; but it's helpful to have it available during planning of
2006 * parameterized table scans, so we store it in the SpecialJoinInfo structs.)
2008 * jointype is never JOIN_RIGHT; a RIGHT JOIN is handled by switching
2009 * the inputs to make it a LEFT JOIN. So the allowed values of jointype
2010 * in a join_info_list member are only LEFT, FULL, SEMI, or ANTI.
2012 * For purposes of join selectivity estimation, we create transient
2013 * SpecialJoinInfo structures for regular inner joins; so it is possible
2014 * to have jointype == JOIN_INNER in such a structure, even though this is
2015 * not allowed within join_info_list. We also create transient
2016 * SpecialJoinInfos with jointype == JOIN_INNER for outer joins, since for
2017 * cost estimation purposes it is sometimes useful to know the join size under
2018 * plain innerjoin semantics. Note that lhs_strict, delay_upper_joins, and
2019 * of course the semi_xxx fields are not set meaningfully within such structs.
2022 typedef struct SpecialJoinInfo
2025 Relids min_lefthand; /* base relids in minimum LHS for join */
2026 Relids min_righthand; /* base relids in minimum RHS for join */
2027 Relids syn_lefthand; /* base relids syntactically within LHS */
2028 Relids syn_righthand; /* base relids syntactically within RHS */
2029 JoinType jointype; /* always INNER, LEFT, FULL, SEMI, or ANTI */
2030 bool lhs_strict; /* joinclause is strict for some LHS rel */
2031 bool delay_upper_joins; /* can't commute with upper RHS */
2032 /* Remaining fields are set only for JOIN_SEMI jointype: */
2033 bool semi_can_btree; /* true if semi_operators are all btree */
2034 bool semi_can_hash; /* true if semi_operators are all hash */
2035 List *semi_operators; /* OIDs of equality join operators */
2036 List *semi_rhs_exprs; /* righthand-side expressions of these ops */
2040 * Append-relation info.
2042 * When we expand an inheritable table or a UNION-ALL subselect into an
2043 * "append relation" (essentially, a list of child RTEs), we build an
2044 * AppendRelInfo for each child RTE. The list of AppendRelInfos indicates
2045 * which child RTEs must be included when expanding the parent, and each node
2046 * carries information needed to translate Vars referencing the parent into
2047 * Vars referencing that child.
2049 * These structs are kept in the PlannerInfo node's append_rel_list.
2050 * Note that we just throw all the structs into one list, and scan the
2051 * whole list when desiring to expand any one parent. We could have used
2052 * a more complex data structure (eg, one list per parent), but this would
2053 * be harder to update during operations such as pulling up subqueries,
2054 * and not really any easier to scan. Considering that typical queries
2055 * will not have many different append parents, it doesn't seem worthwhile
2056 * to complicate things.
2058 * Note: after completion of the planner prep phase, any given RTE is an
2059 * append parent having entries in append_rel_list if and only if its
2060 * "inh" flag is set. We clear "inh" for plain tables that turn out not
2061 * to have inheritance children, and (in an abuse of the original meaning
2062 * of the flag) we set "inh" for subquery RTEs that turn out to be
2063 * flattenable UNION ALL queries. This lets us avoid useless searches
2064 * of append_rel_list.
2066 * Note: the data structure assumes that append-rel members are single
2067 * baserels. This is OK for inheritance, but it prevents us from pulling
2068 * up a UNION ALL member subquery if it contains a join. While that could
2069 * be fixed with a more complex data structure, at present there's not much
2070 * point because no improvement in the plan could result.
2073 typedef struct AppendRelInfo
2078 * These fields uniquely identify this append relationship. There can be
2079 * (in fact, always should be) multiple AppendRelInfos for the same
2080 * parent_relid, but never more than one per child_relid, since a given
2081 * RTE cannot be a child of more than one append parent.
2083 Index parent_relid; /* RT index of append parent rel */
2084 Index child_relid; /* RT index of append child rel */
2087 * For an inheritance appendrel, the parent and child are both regular
2088 * relations, and we store their rowtype OIDs here for use in translating
2089 * whole-row Vars. For a UNION-ALL appendrel, the parent and child are
2090 * both subqueries with no named rowtype, and we store InvalidOid here.
2092 Oid parent_reltype; /* OID of parent's composite type */
2093 Oid child_reltype; /* OID of child's composite type */
2096 * The N'th element of this list is a Var or expression representing the
2097 * child column corresponding to the N'th column of the parent. This is
2098 * used to translate Vars referencing the parent rel into references to
2099 * the child. A list element is NULL if it corresponds to a dropped
2100 * column of the parent (this is only possible for inheritance cases, not
2101 * UNION ALL). The list elements are always simple Vars for inheritance
2102 * cases, but can be arbitrary expressions in UNION ALL cases.
2104 * Notice we only store entries for user columns (attno > 0). Whole-row
2105 * Vars are special-cased, and system columns (attno < 0) need no special
2106 * translation since their attnos are the same for all tables.
2108 * Caution: the Vars have varlevelsup = 0. Be careful to adjust as needed
2109 * when copying into a subquery.
2111 List *translated_vars; /* Expressions in the child's Vars */
2114 * We store the parent table's OID here for inheritance, or InvalidOid for
2115 * UNION ALL. This is only needed to help in generating error messages if
2116 * an attempt is made to reference a dropped parent column.
2118 Oid parent_reloid; /* OID of parent relation */
2122 * For a partitioned table, this maps its RT index to the list of RT indexes
2123 * of the partitioned child tables in the partition tree. We need to
2124 * separately store this information, because we do not create AppendRelInfos
2125 * for the partitioned child tables of a parent table, since AppendRelInfos
2126 * contain information that is unnecessary for the partitioned child tables.
2127 * The child_rels list must contain at least one element, because the parent
2128 * partitioned table is itself counted as a child.
2130 * These structs are kept in the PlannerInfo node's pcinfo_list.
2132 typedef struct PartitionedChildRelInfo
2138 bool part_cols_updated; /* is the partition key of any of
2139 * the partitioned tables updated? */
2140 } PartitionedChildRelInfo;
2143 * For each distinct placeholder expression generated during planning, we
2144 * store a PlaceHolderInfo node in the PlannerInfo node's placeholder_list.
2145 * This stores info that is needed centrally rather than in each copy of the
2146 * PlaceHolderVar. The phid fields identify which PlaceHolderInfo goes with
2147 * each PlaceHolderVar. Note that phid is unique throughout a planner run,
2148 * not just within a query level --- this is so that we need not reassign ID's
2149 * when pulling a subquery into its parent.
2151 * The idea is to evaluate the expression at (only) the ph_eval_at join level,
2152 * then allow it to bubble up like a Var until the ph_needed join level.
2153 * ph_needed has the same definition as attr_needed for a regular Var.
2155 * The PlaceHolderVar's expression might contain LATERAL references to vars
2156 * coming from outside its syntactic scope. If so, those rels are *not*
2157 * included in ph_eval_at, but they are recorded in ph_lateral.
2159 * Notice that when ph_eval_at is a join rather than a single baserel, the
2160 * PlaceHolderInfo may create constraints on join order: the ph_eval_at join
2161 * has to be formed below any outer joins that should null the PlaceHolderVar.
2163 * We create a PlaceHolderInfo only after determining that the PlaceHolderVar
2164 * is actually referenced in the plan tree, so that unreferenced placeholders
2165 * don't result in unnecessary constraints on join order.
2168 typedef struct PlaceHolderInfo
2172 Index phid; /* ID for PH (unique within planner run) */
2173 PlaceHolderVar *ph_var; /* copy of PlaceHolderVar tree */
2174 Relids ph_eval_at; /* lowest level we can evaluate value at */
2175 Relids ph_lateral; /* relids of contained lateral refs, if any */
2176 Relids ph_needed; /* highest level the value is needed at */
2177 int32 ph_width; /* estimated attribute width */
2181 * This struct describes one potentially index-optimizable MIN/MAX aggregate
2182 * function. MinMaxAggPath contains a list of these, and if we accept that
2183 * path, the list is stored into root->minmax_aggs for use during setrefs.c.
2185 typedef struct MinMaxAggInfo
2189 Oid aggfnoid; /* pg_proc Oid of the aggregate */
2190 Oid aggsortop; /* Oid of its sort operator */
2191 Expr *target; /* expression we are aggregating on */
2192 PlannerInfo *subroot; /* modified "root" for planning the subquery */
2193 Path *path; /* access path for subquery */
2194 Cost pathcost; /* estimated cost to fetch first row */
2195 Param *param; /* param for subplan's output */
2199 * At runtime, PARAM_EXEC slots are used to pass values around from one plan
2200 * node to another. They can be used to pass values down into subqueries (for
2201 * outer references in subqueries), or up out of subqueries (for the results
2202 * of a subplan), or from a NestLoop plan node into its inner relation (when
2203 * the inner scan is parameterized with values from the outer relation).
2204 * The planner is responsible for assigning nonconflicting PARAM_EXEC IDs to
2205 * the PARAM_EXEC Params it generates.
2207 * Outer references are managed via root->plan_params, which is a list of
2208 * PlannerParamItems. While planning a subquery, each parent query level's
2209 * plan_params contains the values required from it by the current subquery.
2210 * During create_plan(), we use plan_params to track values that must be
2211 * passed from outer to inner sides of NestLoop plan nodes.
2213 * The item a PlannerParamItem represents can be one of three kinds:
2215 * A Var: the slot represents a variable of this level that must be passed
2216 * down because subqueries have outer references to it, or must be passed
2217 * from a NestLoop node to its inner scan. The varlevelsup value in the Var
2218 * will always be zero.
2220 * A PlaceHolderVar: this works much like the Var case, except that the
2221 * entry is a PlaceHolderVar node with a contained expression. The PHV
2222 * will have phlevelsup = 0, and the contained expression is adjusted
2223 * to match in level.
2225 * An Aggref (with an expression tree representing its argument): the slot
2226 * represents an aggregate expression that is an outer reference for some
2227 * subquery. The Aggref itself has agglevelsup = 0, and its argument tree
2228 * is adjusted to match in level.
2230 * Note: we detect duplicate Var and PlaceHolderVar parameters and coalesce
2231 * them into one slot, but we do not bother to do that for Aggrefs.
2232 * The scope of duplicate-elimination only extends across the set of
2233 * parameters passed from one query level into a single subquery, or for
2234 * nestloop parameters across the set of nestloop parameters used in a single
2235 * query level. So there is no possibility of a PARAM_EXEC slot being used
2236 * for conflicting purposes.
2238 * In addition, PARAM_EXEC slots are assigned for Params representing outputs
2239 * from subplans (values that are setParam items for those subplans). These
2240 * IDs need not be tracked via PlannerParamItems, since we do not need any
2241 * duplicate-elimination nor later processing of the represented expressions.
2242 * Instead, we just record the assignment of the slot number by appending to
2243 * root->glob->paramExecTypes.
2245 typedef struct PlannerParamItem
2249 Node *item; /* the Var, PlaceHolderVar, or Aggref */
2250 int paramId; /* its assigned PARAM_EXEC slot number */
2254 * When making cost estimates for a SEMI/ANTI/inner_unique join, there are
2255 * some correction factors that are needed in both nestloop and hash joins
2256 * to account for the fact that the executor can stop scanning inner rows
2257 * as soon as it finds a match to the current outer row. These numbers
2258 * depend only on the selected outer and inner join relations, not on the
2259 * particular paths used for them, so it's worthwhile to calculate them
2260 * just once per relation pair not once per considered path. This struct
2261 * is filled by compute_semi_anti_join_factors and must be passed along
2262 * to the join cost estimation functions.
2264 * outer_match_frac is the fraction of the outer tuples that are
2265 * expected to have at least one match.
2266 * match_count is the average number of matches expected for
2267 * outer tuples that have at least one match.
2269 typedef struct SemiAntiJoinFactors
2271 Selectivity outer_match_frac;
2272 Selectivity match_count;
2273 } SemiAntiJoinFactors;
2276 * Struct for extra information passed to subroutines of add_paths_to_joinrel
2278 * restrictlist contains all of the RestrictInfo nodes for restriction
2279 * clauses that apply to this join
2280 * mergeclause_list is a list of RestrictInfo nodes for available
2281 * mergejoin clauses in this join
2282 * inner_unique is true if each outer tuple provably matches no more
2283 * than one inner tuple
2284 * sjinfo is extra info about special joins for selectivity estimation
2285 * semifactors is as shown above (only valid for SEMI/ANTI/inner_unique joins)
2286 * param_source_rels are OK targets for parameterization of result paths
2288 typedef struct JoinPathExtraData
2291 List *mergeclause_list;
2293 SpecialJoinInfo *sjinfo;
2294 SemiAntiJoinFactors semifactors;
2295 Relids param_source_rels;
2296 } JoinPathExtraData;
2299 * Various flags indicating what kinds of grouping are possible.
2301 * GROUPING_CAN_USE_SORT should be set if it's possible to perform
2302 * sort-based implementations of grouping. When grouping sets are in use,
2303 * this will be true if sorting is potentially usable for any of the grouping
2304 * sets, even if it's not usable for all of them.
2306 * GROUPING_CAN_USE_HASH should be set if it's possible to perform
2307 * hash-based implementations of grouping.
2309 * GROUPING_CAN_PARTIAL_AGG should be set if the aggregation is of a type
2310 * for which we support partial aggregation (not, for example, grouping sets).
2311 * It says nothing about parallel-safety or the availability of suitable paths.
2313 #define GROUPING_CAN_USE_SORT 0x0001
2314 #define GROUPING_CAN_USE_HASH 0x0002
2315 #define GROUPING_CAN_PARTIAL_AGG 0x0004
2318 * What kind of partitionwise aggregation is in use?
2320 * PARTITIONWISE_AGGREGATE_NONE: Not used.
2322 * PARTITIONWISE_AGGREGATE_FULL: Aggregate each partition separately, and
2323 * append the results.
2325 * PARTITIONWISE_AGGREGATE_PARTIAL: Partially aggregate each partition
2326 * separately, append the results, and then finalize aggregation.
2330 PARTITIONWISE_AGGREGATE_NONE,
2331 PARTITIONWISE_AGGREGATE_FULL,
2332 PARTITIONWISE_AGGREGATE_PARTIAL
2333 } PartitionwiseAggregateType;
2336 * Struct for extra information passed to subroutines of create_grouping_paths
2338 * flags indicating what kinds of grouping are possible.
2339 * partial_costs_set is true if the agg_partial_costs and agg_final_costs
2340 * have been initialized.
2341 * agg_partial_costs gives partial aggregation costs.
2342 * agg_final_costs gives finalization costs.
2343 * target_parallel_safe is true if target is parallel safe.
2344 * havingQual gives list of quals to be applied after aggregation.
2345 * targetList gives list of columns to be projected.
2346 * patype is the type of partitionwise aggregation that is being performed.
2350 /* Data which remains constant once set. */
2352 bool partial_costs_set;
2353 AggClauseCosts agg_partial_costs;
2354 AggClauseCosts agg_final_costs;
2356 /* Data which may differ across partitions. */
2357 bool target_parallel_safe;
2360 PartitionwiseAggregateType patype;
2361 } GroupPathExtraData;
2364 * For speed reasons, cost estimation for join paths is performed in two
2365 * phases: the first phase tries to quickly derive a lower bound for the
2366 * join cost, and then we check if that's sufficient to reject the path.
2367 * If not, we come back for a more refined cost estimate. The first phase
2368 * fills a JoinCostWorkspace struct with its preliminary cost estimates
2369 * and possibly additional intermediate values. The second phase takes
2370 * these values as inputs to avoid repeating work.
2372 * (Ideally we'd declare this in cost.h, but it's also needed in pathnode.h,
2373 * so seems best to put it here.)
2375 typedef struct JoinCostWorkspace
2377 /* Preliminary cost estimates --- must not be larger than final ones! */
2378 Cost startup_cost; /* cost expended before fetching any tuples */
2379 Cost total_cost; /* total cost (assuming all tuples fetched) */
2381 /* Fields below here should be treated as private to costsize.c */
2382 Cost run_cost; /* non-startup cost components */
2384 /* private for cost_nestloop code */
2385 Cost inner_run_cost; /* also used by cost_mergejoin code */
2386 Cost inner_rescan_run_cost;
2388 /* private for cost_mergejoin code */
2391 double outer_skip_rows;
2392 double inner_skip_rows;
2394 /* private for cost_hashjoin code */
2397 double inner_rows_total;
2398 } JoinCostWorkspace;
2400 #endif /* RELATION_H */