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