Debian Codegraph @

src/include/nodes/pathnodes.h

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