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