]> granicus.if.org Git - postgresql/blob - src/include/nodes/relation.h
Add support for index-only scans in GiST.
[postgresql] / src / include / nodes / relation.h
1 /*-------------------------------------------------------------------------
2  *
3  * relation.h
4  *        Definitions for planner's internal data structures.
5  *
6  *
7  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/nodes/relation.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef RELATION_H
15 #define RELATION_H
16
17 #include "access/sdir.h"
18 #include "lib/stringinfo.h"
19 #include "nodes/params.h"
20 #include "nodes/parsenodes.h"
21 #include "storage/block.h"
22
23
24 /*
25  * Relids
26  *              Set of relation identifiers (indexes into the rangetable).
27  */
28 typedef Bitmapset *Relids;
29
30 /*
31  * When looking for a "cheapest path", this enum specifies whether we want
32  * cheapest startup cost or cheapest total cost.
33  */
34 typedef enum CostSelector
35 {
36         STARTUP_COST, TOTAL_COST
37 } CostSelector;
38
39 /*
40  * The cost estimate produced by cost_qual_eval() includes both a one-time
41  * (startup) cost, and a per-tuple cost.
42  */
43 typedef struct QualCost
44 {
45         Cost            startup;                /* one-time cost */
46         Cost            per_tuple;              /* per-evaluation cost */
47 } QualCost;
48
49 /*
50  * Costing aggregate function execution requires these statistics about
51  * the aggregates to be executed by a given Agg node.  Note that the costs
52  * include the execution costs of the aggregates' argument expressions as
53  * well as the aggregate functions themselves.
54  */
55 typedef struct AggClauseCosts
56 {
57         int                     numAggs;                /* total number of aggregate functions */
58         int                     numOrderedAggs; /* number w/ DISTINCT/ORDER BY/WITHIN GROUP */
59         QualCost        transCost;              /* total per-input-row execution costs */
60         Cost            finalCost;              /* total per-aggregated-row costs */
61         Size            transitionSpace;        /* space for pass-by-ref transition data */
62 } AggClauseCosts;
63
64
65 /*----------
66  * PlannerGlobal
67  *              Global information for planning/optimization
68  *
69  * PlannerGlobal holds state for an entire planner invocation; this state
70  * is shared across all levels of sub-Queries that exist in the command being
71  * planned.
72  *----------
73  */
74 typedef struct PlannerGlobal
75 {
76         NodeTag         type;
77
78         ParamListInfo boundParams;      /* Param values provided to planner() */
79
80         List       *subplans;           /* Plans for SubPlan nodes */
81
82         List       *subroots;           /* PlannerInfos for SubPlan nodes */
83
84         Bitmapset  *rewindPlanIDs;      /* indices of subplans that require REWIND */
85
86         List       *finalrtable;        /* "flat" rangetable for executor */
87
88         List       *finalrowmarks;      /* "flat" list of PlanRowMarks */
89
90         List       *resultRelations;    /* "flat" list of integer RT indexes */
91
92         List       *relationOids;       /* OIDs of relations the plan depends on */
93
94         List       *invalItems;         /* other dependencies, as PlanInvalItems */
95
96         int                     nParamExec;             /* number of PARAM_EXEC Params used */
97
98         Index           lastPHId;               /* highest PlaceHolderVar ID assigned */
99
100         Index           lastRowMarkId;  /* highest PlanRowMark ID assigned */
101
102         bool            transientPlan;  /* redo plan when TransactionXmin changes? */
103
104         bool            hasRowSecurity; /* row security applied? */
105 } PlannerGlobal;
106
107 /* macro for fetching the Plan associated with a SubPlan node */
108 #define planner_subplan_get_plan(root, subplan) \
109         ((Plan *) list_nth((root)->glob->subplans, (subplan)->plan_id - 1))
110
111
112 /*----------
113  * PlannerInfo
114  *              Per-query information for planning/optimization
115  *
116  * This struct is conventionally called "root" in all the planner routines.
117  * It holds links to all of the planner's working state, in addition to the
118  * original Query.  Note that at present the planner extensively modifies
119  * the passed-in Query data structure; someday that should stop.
120  *----------
121  */
122 typedef struct PlannerInfo
123 {
124         NodeTag         type;
125
126         Query      *parse;                      /* the Query being planned */
127
128         PlannerGlobal *glob;            /* global info for current planner run */
129
130         Index           query_level;    /* 1 at the outermost Query */
131
132         struct PlannerInfo *parent_root;        /* NULL at outermost Query */
133
134         List       *plan_params;        /* list of PlannerParamItems, see below */
135
136         /*
137          * simple_rel_array holds pointers to "base rels" and "other rels" (see
138          * comments for RelOptInfo for more info).  It is indexed by rangetable
139          * index (so entry 0 is always wasted).  Entries can be NULL when an RTE
140          * does not correspond to a base relation, such as a join RTE or an
141          * unreferenced view RTE; or if the RelOptInfo hasn't been made yet.
142          */
143         struct RelOptInfo **simple_rel_array;           /* All 1-rel RelOptInfos */
144         int                     simple_rel_array_size;  /* allocated size of array */
145
146         /*
147          * simple_rte_array is the same length as simple_rel_array and holds
148          * pointers to the associated rangetable entries.  This lets us avoid
149          * rt_fetch(), which can be a bit slow once large inheritance sets have
150          * been expanded.
151          */
152         RangeTblEntry **simple_rte_array;       /* rangetable as an array */
153
154         /*
155          * all_baserels is a Relids set of all base relids (but not "other"
156          * relids) in the query; that is, the Relids identifier of the final join
157          * we need to form.  This is computed in make_one_rel, just before we
158          * start making Paths.
159          */
160         Relids          all_baserels;
161
162         /*
163          * nullable_baserels is a Relids set of base relids that are nullable by
164          * some outer join in the jointree; these are rels that are potentially
165          * nullable below the WHERE clause, SELECT targetlist, etc.  This is
166          * computed in deconstruct_jointree.
167          */
168         Relids          nullable_baserels;
169
170         /*
171          * join_rel_list is a list of all join-relation RelOptInfos we have
172          * considered in this planning run.  For small problems we just scan the
173          * list to do lookups, but when there are many join relations we build a
174          * hash table for faster lookups.  The hash table is present and valid
175          * when join_rel_hash is not NULL.  Note that we still maintain the list
176          * even when using the hash table for lookups; this simplifies life for
177          * GEQO.
178          */
179         List       *join_rel_list;      /* list of join-relation RelOptInfos */
180         struct HTAB *join_rel_hash; /* optional hashtable for join relations */
181
182         /*
183          * When doing a dynamic-programming-style join search, join_rel_level[k]
184          * is a list of all join-relation RelOptInfos of level k, and
185          * join_cur_level is the current level.  New join-relation RelOptInfos are
186          * automatically added to the join_rel_level[join_cur_level] list.
187          * join_rel_level is NULL if not in use.
188          */
189         List      **join_rel_level; /* lists of join-relation RelOptInfos */
190         int                     join_cur_level; /* index of list being extended */
191
192         List       *init_plans;         /* init SubPlans for query */
193
194         List       *cte_plan_ids;       /* per-CTE-item list of subplan IDs */
195
196         List       *multiexpr_params;           /* List of Lists of Params for
197                                                                                  * MULTIEXPR subquery outputs */
198
199         List       *eq_classes;         /* list of active EquivalenceClasses */
200
201         List       *canon_pathkeys; /* list of "canonical" PathKeys */
202
203         List       *left_join_clauses;          /* list of RestrictInfos for
204                                                                                  * mergejoinable outer join clauses
205                                                                                  * w/nonnullable var on left */
206
207         List       *right_join_clauses;         /* list of RestrictInfos for
208                                                                                  * mergejoinable outer join clauses
209                                                                                  * w/nonnullable var on right */
210
211         List       *full_join_clauses;          /* list of RestrictInfos for
212                                                                                  * mergejoinable full join clauses */
213
214         List       *join_info_list; /* list of SpecialJoinInfos */
215
216         List       *lateral_info_list;          /* list of LateralJoinInfos */
217
218         List       *append_rel_list;    /* list of AppendRelInfos */
219
220         List       *rowMarks;           /* list of PlanRowMarks */
221
222         List       *placeholder_list;           /* list of PlaceHolderInfos */
223
224         List       *query_pathkeys; /* desired pathkeys for query_planner(), and
225                                                                  * actual pathkeys after planning */
226
227         List       *group_pathkeys; /* groupClause pathkeys, if any */
228         List       *window_pathkeys;    /* pathkeys of bottom window, if any */
229         List       *distinct_pathkeys;          /* distinctClause pathkeys, if any */
230         List       *sort_pathkeys;      /* sortClause pathkeys, if any */
231
232         List       *minmax_aggs;        /* List of MinMaxAggInfos */
233
234         List       *initial_rels;       /* RelOptInfos we are now trying to join */
235
236         MemoryContext planner_cxt;      /* context holding PlannerInfo */
237
238         double          total_table_pages;              /* # of pages in all tables of query */
239
240         double          tuple_fraction; /* tuple_fraction passed to query_planner */
241         double          limit_tuples;   /* limit_tuples passed to query_planner */
242
243         bool            hasInheritedTarget;             /* true if parse->resultRelation is an
244                                                                                  * inheritance child rel */
245         bool            hasJoinRTEs;    /* true if any RTEs are RTE_JOIN kind */
246         bool            hasLateralRTEs; /* true if any RTEs are marked LATERAL */
247         bool            hasDeletedRTEs; /* true if any RTE was deleted from jointree */
248         bool            hasHavingQual;  /* true if havingQual was non-null */
249         bool            hasPseudoConstantQuals; /* true if any RestrictInfo has
250                                                                                  * pseudoconstant = true */
251         bool            hasRecursion;   /* true if planning a recursive WITH item */
252
253         /* These fields are used only when hasRecursion is true: */
254         int                     wt_param_id;    /* PARAM_EXEC ID for the work table */
255         struct Plan *non_recursive_plan;        /* plan for non-recursive term */
256
257         /* These fields are workspace for createplan.c */
258         Relids          curOuterRels;   /* outer rels above current node */
259         List       *curOuterParams; /* not-yet-assigned NestLoopParams */
260
261         /* optional private data for join_search_hook, e.g., GEQO */
262         void       *join_search_private;
263 } PlannerInfo;
264
265
266 /*
267  * In places where it's known that simple_rte_array[] must have been prepared
268  * already, we just index into it to fetch RTEs.  In code that might be
269  * executed before or after entering query_planner(), use this macro.
270  */
271 #define planner_rt_fetch(rti, root) \
272         ((root)->simple_rte_array ? (root)->simple_rte_array[rti] : \
273          rt_fetch(rti, (root)->parse->rtable))
274
275
276 /*----------
277  * RelOptInfo
278  *              Per-relation information for planning/optimization
279  *
280  * For planning purposes, a "base rel" is either a plain relation (a table)
281  * or the output of a sub-SELECT or function that appears in the range table.
282  * In either case it is uniquely identified by an RT index.  A "joinrel"
283  * is the joining of two or more base rels.  A joinrel is identified by
284  * the set of RT indexes for its component baserels.  We create RelOptInfo
285  * nodes for each baserel and joinrel, and store them in the PlannerInfo's
286  * simple_rel_array and join_rel_list respectively.
287  *
288  * Note that there is only one joinrel for any given set of component
289  * baserels, no matter what order we assemble them in; so an unordered
290  * set is the right datatype to identify it with.
291  *
292  * We also have "other rels", which are like base rels in that they refer to
293  * single RT indexes; but they are not part of the join tree, and are given
294  * a different RelOptKind to identify them.  Lastly, there is a RelOptKind
295  * for "dead" relations, which are base rels that we have proven we don't
296  * need to join after all.
297  *
298  * Currently the only kind of otherrels are those made for member relations
299  * of an "append relation", that is an inheritance set or UNION ALL subquery.
300  * An append relation has a parent RTE that is a base rel, which represents
301  * the entire append relation.  The member RTEs are otherrels.  The parent
302  * is present in the query join tree but the members are not.  The member
303  * RTEs and otherrels are used to plan the scans of the individual tables or
304  * subqueries of the append set; then the parent baserel is given Append
305  * and/or MergeAppend paths comprising the best paths for the individual
306  * member rels.  (See comments for AppendRelInfo for more information.)
307  *
308  * At one time we also made otherrels to represent join RTEs, for use in
309  * handling join alias Vars.  Currently this is not needed because all join
310  * alias Vars are expanded to non-aliased form during preprocess_expression.
311  *
312  * Parts of this data structure are specific to various scan and join
313  * mechanisms.  It didn't seem worth creating new node types for them.
314  *
315  *              relids - Set of base-relation identifiers; it is a base relation
316  *                              if there is just one, a join relation if more than one
317  *              rows - estimated number of tuples in the relation after restriction
318  *                         clauses have been applied (ie, output rows of a plan for it)
319  *              width - avg. number of bytes per tuple in the relation after the
320  *                              appropriate projections have been done (ie, output width)
321  *              consider_startup - true if there is any value in keeping paths for
322  *                                                 this rel on the basis of having cheap startup cost
323  *              reltargetlist - List of Var and PlaceHolderVar nodes for the values
324  *                                              we need to output from this relation.
325  *                                              List is in no particular order, but all rels of an
326  *                                              appendrel set must use corresponding orders.
327  *                                              NOTE: in an appendrel child relation, may contain
328  *                                              arbitrary expressions pulled up from a subquery!
329  *              pathlist - List of Path nodes, one for each potentially useful
330  *                                 method of generating the relation
331  *              ppilist - ParamPathInfo nodes for parameterized Paths, if any
332  *              cheapest_startup_path - the pathlist member with lowest startup cost
333  *                      (regardless of ordering) among the unparameterized paths;
334  *                      or NULL if there is no unparameterized path
335  *              cheapest_total_path - the pathlist member with lowest total cost
336  *                      (regardless of ordering) among the unparameterized paths;
337  *                      or if there is no unparameterized path, the path with lowest
338  *                      total cost among the paths with minimum parameterization
339  *              cheapest_unique_path - for caching cheapest path to produce unique
340  *                      (no duplicates) output from relation; NULL if not yet requested
341  *              cheapest_parameterized_paths - best paths for their parameterizations;
342  *                      always includes cheapest_total_path, even if that's unparameterized
343  *
344  * If the relation is a base relation it will have these fields set:
345  *
346  *              relid - RTE index (this is redundant with the relids field, but
347  *                              is provided for convenience of access)
348  *              rtekind - distinguishes plain relation, subquery, or function RTE
349  *              min_attr, max_attr - range of valid AttrNumbers for rel
350  *              attr_needed - array of bitmapsets indicating the highest joinrel
351  *                              in which each attribute is needed; if bit 0 is set then
352  *                              the attribute is needed as part of final targetlist
353  *              attr_widths - cache space for per-attribute width estimates;
354  *                                        zero means not computed yet
355  *              lateral_vars - lateral cross-references of rel, if any (list of
356  *                                         Vars and PlaceHolderVars)
357  *              lateral_relids - required outer rels for LATERAL, as a Relids set
358  *                                               (for child rels this can be more than lateral_vars)
359  *              lateral_referencers - relids of rels that reference this one laterally
360  *              indexlist - list of IndexOptInfo nodes for relation's indexes
361  *                                      (always NIL if it's not a table)
362  *              pages - number of disk pages in relation (zero if not a table)
363  *              tuples - number of tuples in relation (not considering restrictions)
364  *              allvisfrac - fraction of disk pages that are marked all-visible
365  *              subplan - plan for subquery (NULL if it's not a subquery)
366  *              subroot - PlannerInfo for subquery (NULL if it's not a subquery)
367  *              subplan_params - list of PlannerParamItems to be passed to subquery
368  *              fdwroutine - function hooks for FDW, if foreign table (else NULL)
369  *              fdw_private - private state for FDW, if foreign table (else NULL)
370  *
371  *              Note: for a subquery, tuples, subplan, subroot are not set immediately
372  *              upon creation of the RelOptInfo object; they are filled in when
373  *              set_subquery_pathlist processes the object.  Likewise, fdwroutine
374  *              and fdw_private are filled during initial path creation.
375  *
376  *              For otherrels that are appendrel members, these fields are filled
377  *              in just as for a baserel.
378  *
379  * The presence of the remaining fields depends on the restrictions
380  * and joins that the relation participates in:
381  *
382  *              baserestrictinfo - List of RestrictInfo nodes, containing info about
383  *                                      each non-join qualification clause in which this relation
384  *                                      participates (only used for base rels)
385  *              baserestrictcost - Estimated cost of evaluating the baserestrictinfo
386  *                                      clauses at a single tuple (only used for base rels)
387  *              joininfo  - List of RestrictInfo nodes, containing info about each
388  *                                      join clause in which this relation participates (but
389  *                                      note this excludes clauses that might be derivable from
390  *                                      EquivalenceClasses)
391  *              has_eclass_joins - flag that EquivalenceClass joins are possible
392  *
393  * Note: Keeping a restrictinfo list in the RelOptInfo is useful only for
394  * base rels, because for a join rel the set of clauses that are treated as
395  * restrict clauses varies depending on which sub-relations we choose to join.
396  * (For example, in a 3-base-rel join, a clause relating rels 1 and 2 must be
397  * treated as a restrictclause if we join {1} and {2 3} to make {1 2 3}; but
398  * if we join {1 2} and {3} then that clause will be a restrictclause in {1 2}
399  * and should not be processed again at the level of {1 2 3}.)  Therefore,
400  * the restrictinfo list in the join case appears in individual JoinPaths
401  * (field joinrestrictinfo), not in the parent relation.  But it's OK for
402  * the RelOptInfo to store the joininfo list, because that is the same
403  * for a given rel no matter how we form it.
404  *
405  * We store baserestrictcost in the RelOptInfo (for base relations) because
406  * we know we will need it at least once (to price the sequential scan)
407  * and may need it multiple times to price index scans.
408  *----------
409  */
410 typedef enum RelOptKind
411 {
412         RELOPT_BASEREL,
413         RELOPT_JOINREL,
414         RELOPT_OTHER_MEMBER_REL,
415         RELOPT_DEADREL
416 } RelOptKind;
417
418 typedef struct RelOptInfo
419 {
420         NodeTag         type;
421
422         RelOptKind      reloptkind;
423
424         /* all relations included in this RelOptInfo */
425         Relids          relids;                 /* set of base relids (rangetable indexes) */
426
427         /* size estimates generated by planner */
428         double          rows;                   /* estimated number of result tuples */
429         int                     width;                  /* estimated avg width of result tuples */
430
431         /* per-relation planner control flags */
432         bool            consider_startup;               /* keep cheap-startup-cost paths? */
433
434         /* materialization information */
435         List       *reltargetlist;      /* Vars to be output by scan of relation */
436         List       *pathlist;           /* Path structures */
437         List       *ppilist;            /* ParamPathInfos used in pathlist */
438         struct Path *cheapest_startup_path;
439         struct Path *cheapest_total_path;
440         struct Path *cheapest_unique_path;
441         List       *cheapest_parameterized_paths;
442
443         /* information about a base rel (not set for join rels!) */
444         Index           relid;
445         Oid                     reltablespace;  /* containing tablespace */
446         RTEKind         rtekind;                /* RELATION, SUBQUERY, or FUNCTION */
447         AttrNumber      min_attr;               /* smallest attrno of rel (often <0) */
448         AttrNumber      max_attr;               /* largest attrno of rel */
449         Relids     *attr_needed;        /* array indexed [min_attr .. max_attr] */
450         int32      *attr_widths;        /* array indexed [min_attr .. max_attr] */
451         List       *lateral_vars;       /* LATERAL Vars and PHVs referenced by rel */
452         Relids          lateral_relids; /* minimum parameterization of rel */
453         Relids          lateral_referencers;    /* rels that reference me laterally */
454         List       *indexlist;          /* list of IndexOptInfo */
455         BlockNumber pages;                      /* size estimates derived from pg_class */
456         double          tuples;
457         double          allvisfrac;
458         /* use "struct Plan" to avoid including plannodes.h here */
459         struct Plan *subplan;           /* if subquery */
460         PlannerInfo *subroot;           /* if subquery */
461         List       *subplan_params; /* if subquery */
462         /* use "struct FdwRoutine" to avoid including fdwapi.h here */
463         struct FdwRoutine *fdwroutine;          /* if foreign table */
464         void       *fdw_private;        /* if foreign table */
465
466         /* used by various scans and joins: */
467         List       *baserestrictinfo;           /* RestrictInfo structures (if base
468                                                                                  * rel) */
469         QualCost        baserestrictcost;               /* cost of evaluating the above */
470         List       *joininfo;           /* RestrictInfo structures for join clauses
471                                                                  * involving this rel */
472         bool            has_eclass_joins;               /* T means joininfo is incomplete */
473 } RelOptInfo;
474
475 /*
476  * IndexOptInfo
477  *              Per-index information for planning/optimization
478  *
479  *              indexkeys[], indexcollations[], opfamily[], and opcintype[]
480  *              each have ncolumns entries.
481  *
482  *              sortopfamily[], reverse_sort[], and nulls_first[] likewise have
483  *              ncolumns entries, if the index is ordered; but if it is unordered,
484  *              those pointers are NULL.
485  *
486  *              Zeroes in the indexkeys[] array indicate index columns that are
487  *              expressions; there is one element in indexprs for each such column.
488  *
489  *              For an ordered index, reverse_sort[] and nulls_first[] describe the
490  *              sort ordering of a forward indexscan; we can also consider a backward
491  *              indexscan, which will generate the reverse ordering.
492  *
493  *              The indexprs and indpred expressions have been run through
494  *              prepqual.c and eval_const_expressions() for ease of matching to
495  *              WHERE clauses. indpred is in implicit-AND form.
496  *
497  *              indextlist is a TargetEntry list representing the index columns.
498  *              It provides an equivalent base-relation Var for each simple column,
499  *              and links to the matching indexprs element for each expression column.
500  */
501 typedef struct IndexOptInfo
502 {
503         NodeTag         type;
504
505         Oid                     indexoid;               /* OID of the index relation */
506         Oid                     reltablespace;  /* tablespace of index (not table) */
507         RelOptInfo *rel;                        /* back-link to index's table */
508
509         /* index-size statistics (from pg_class and elsewhere) */
510         BlockNumber pages;                      /* number of disk pages in index */
511         double          tuples;                 /* number of index tuples in index */
512         int                     tree_height;    /* index tree height, or -1 if unknown */
513
514         /* index descriptor information */
515         int                     ncolumns;               /* number of columns in index */
516         int                *indexkeys;          /* column numbers of index's keys, or 0 */
517         Oid                *indexcollations;    /* OIDs of collations of index columns */
518         Oid                *opfamily;           /* OIDs of operator families for columns */
519         Oid                *opcintype;          /* OIDs of opclass declared input data types */
520         Oid                *sortopfamily;       /* OIDs of btree opfamilies, if orderable */
521         bool       *reverse_sort;       /* is sort order descending? */
522         bool       *nulls_first;        /* do NULLs come first in the sort order? */
523         bool       *canreturn;          /* which index cols can be returned in an
524                                                                    index-only scan? */
525         Oid                     relam;                  /* OID of the access method (in pg_am) */
526
527         RegProcedure amcostestimate;    /* OID of the access method's cost fcn */
528
529         List       *indexprs;           /* expressions for non-simple index columns */
530         List       *indpred;            /* predicate if a partial index, else NIL */
531
532         List       *indextlist;         /* targetlist representing index columns */
533
534         bool            predOK;                 /* true if predicate matches query */
535         bool            unique;                 /* true if a unique index */
536         bool            immediate;              /* is uniqueness enforced immediately? */
537         bool            hypothetical;   /* true if index doesn't really exist */
538         bool            amcanorderbyop; /* does AM support order by operator result? */
539         bool            amoptionalkey;  /* can query omit key for the first column? */
540         bool            amsearcharray;  /* can AM handle ScalarArrayOpExpr quals? */
541         bool            amsearchnulls;  /* can AM search for NULL/NOT NULL entries? */
542         bool            amhasgettuple;  /* does AM have amgettuple interface? */
543         bool            amhasgetbitmap; /* does AM have amgetbitmap interface? */
544 } IndexOptInfo;
545
546
547 /*
548  * EquivalenceClasses
549  *
550  * Whenever we can determine that a mergejoinable equality clause A = B is
551  * not delayed by any outer join, we create an EquivalenceClass containing
552  * the expressions A and B to record this knowledge.  If we later find another
553  * equivalence B = C, we add C to the existing EquivalenceClass; this may
554  * require merging two existing EquivalenceClasses.  At the end of the qual
555  * distribution process, we have sets of values that are known all transitively
556  * equal to each other, where "equal" is according to the rules of the btree
557  * operator family(s) shown in ec_opfamilies, as well as the collation shown
558  * by ec_collation.  (We restrict an EC to contain only equalities whose
559  * operators belong to the same set of opfamilies.  This could probably be
560  * relaxed, but for now it's not worth the trouble, since nearly all equality
561  * operators belong to only one btree opclass anyway.  Similarly, we suppose
562  * that all or none of the input datatypes are collatable, so that a single
563  * collation value is sufficient.)
564  *
565  * We also use EquivalenceClasses as the base structure for PathKeys, letting
566  * us represent knowledge about different sort orderings being equivalent.
567  * Since every PathKey must reference an EquivalenceClass, we will end up
568  * with single-member EquivalenceClasses whenever a sort key expression has
569  * not been equivalenced to anything else.  It is also possible that such an
570  * EquivalenceClass will contain a volatile expression ("ORDER BY random()"),
571  * which is a case that can't arise otherwise since clauses containing
572  * volatile functions are never considered mergejoinable.  We mark such
573  * EquivalenceClasses specially to prevent them from being merged with
574  * ordinary EquivalenceClasses.  Also, for volatile expressions we have
575  * to be careful to match the EquivalenceClass to the correct targetlist
576  * entry: consider SELECT random() AS a, random() AS b ... ORDER BY b,a.
577  * So we record the SortGroupRef of the originating sort clause.
578  *
579  * We allow equality clauses appearing below the nullable side of an outer join
580  * to form EquivalenceClasses, but these have a slightly different meaning:
581  * the included values might be all NULL rather than all the same non-null
582  * values.  See src/backend/optimizer/README for more on that point.
583  *
584  * NB: if ec_merged isn't NULL, this class has been merged into another, and
585  * should be ignored in favor of using the pointed-to class.
586  */
587 typedef struct EquivalenceClass
588 {
589         NodeTag         type;
590
591         List       *ec_opfamilies;      /* btree operator family OIDs */
592         Oid                     ec_collation;   /* collation, if datatypes are collatable */
593         List       *ec_members;         /* list of EquivalenceMembers */
594         List       *ec_sources;         /* list of generating RestrictInfos */
595         List       *ec_derives;         /* list of derived RestrictInfos */
596         Relids          ec_relids;              /* all relids appearing in ec_members, except
597                                                                  * for child members (see below) */
598         bool            ec_has_const;   /* any pseudoconstants in ec_members? */
599         bool            ec_has_volatile;        /* the (sole) member is a volatile expr */
600         bool            ec_below_outer_join;    /* equivalence applies below an OJ */
601         bool            ec_broken;              /* failed to generate needed clauses? */
602         Index           ec_sortref;             /* originating sortclause label, or 0 */
603         struct EquivalenceClass *ec_merged; /* set if merged into another EC */
604 } EquivalenceClass;
605
606 /*
607  * If an EC contains a const and isn't below-outer-join, any PathKey depending
608  * on it must be redundant, since there's only one possible value of the key.
609  */
610 #define EC_MUST_BE_REDUNDANT(eclass)  \
611         ((eclass)->ec_has_const && !(eclass)->ec_below_outer_join)
612
613 /*
614  * EquivalenceMember - one member expression of an EquivalenceClass
615  *
616  * em_is_child signifies that this element was built by transposing a member
617  * for an appendrel parent relation to represent the corresponding expression
618  * for an appendrel child.  These members are used for determining the
619  * pathkeys of scans on the child relation and for explicitly sorting the
620  * child when necessary to build a MergeAppend path for the whole appendrel
621  * tree.  An em_is_child member has no impact on the properties of the EC as a
622  * whole; in particular the EC's ec_relids field does NOT include the child
623  * relation.  An em_is_child member should never be marked em_is_const nor
624  * cause ec_has_const or ec_has_volatile to be set, either.  Thus, em_is_child
625  * members are not really full-fledged members of the EC, but just reflections
626  * or doppelgangers of real members.  Most operations on EquivalenceClasses
627  * should ignore em_is_child members, and those that don't should test
628  * em_relids to make sure they only consider relevant members.
629  *
630  * em_datatype is usually the same as exprType(em_expr), but can be
631  * different when dealing with a binary-compatible opfamily; in particular
632  * anyarray_ops would never work without this.  Use em_datatype when
633  * looking up a specific btree operator to work with this expression.
634  */
635 typedef struct EquivalenceMember
636 {
637         NodeTag         type;
638
639         Expr       *em_expr;            /* the expression represented */
640         Relids          em_relids;              /* all relids appearing in em_expr */
641         Relids          em_nullable_relids;             /* nullable by lower outer joins */
642         bool            em_is_const;    /* expression is pseudoconstant? */
643         bool            em_is_child;    /* derived version for a child relation? */
644         Oid                     em_datatype;    /* the "nominal type" used by the opfamily */
645 } EquivalenceMember;
646
647 /*
648  * PathKeys
649  *
650  * The sort ordering of a path is represented by a list of PathKey nodes.
651  * An empty list implies no known ordering.  Otherwise the first item
652  * represents the primary sort key, the second the first secondary sort key,
653  * etc.  The value being sorted is represented by linking to an
654  * EquivalenceClass containing that value and including pk_opfamily among its
655  * ec_opfamilies.  The EquivalenceClass tells which collation to use, too.
656  * This is a convenient method because it makes it trivial to detect
657  * equivalent and closely-related orderings. (See optimizer/README for more
658  * information.)
659  *
660  * Note: pk_strategy is either BTLessStrategyNumber (for ASC) or
661  * BTGreaterStrategyNumber (for DESC).  We assume that all ordering-capable
662  * index types will use btree-compatible strategy numbers.
663  */
664 typedef struct PathKey
665 {
666         NodeTag         type;
667
668         EquivalenceClass *pk_eclass;    /* the value that is ordered */
669         Oid                     pk_opfamily;    /* btree opfamily defining the ordering */
670         int                     pk_strategy;    /* sort direction (ASC or DESC) */
671         bool            pk_nulls_first; /* do NULLs come before normal values? */
672 } PathKey;
673
674
675 /*
676  * ParamPathInfo
677  *
678  * All parameterized paths for a given relation with given required outer rels
679  * link to a single ParamPathInfo, which stores common information such as
680  * the estimated rowcount for this parameterization.  We do this partly to
681  * avoid recalculations, but mostly to ensure that the estimated rowcount
682  * is in fact the same for every such path.
683  *
684  * Note: ppi_clauses is only used in ParamPathInfos for base relation paths;
685  * in join cases it's NIL because the set of relevant clauses varies depending
686  * on how the join is formed.  The relevant clauses will appear in each
687  * parameterized join path's joinrestrictinfo list, instead.
688  */
689 typedef struct ParamPathInfo
690 {
691         NodeTag         type;
692
693         Relids          ppi_req_outer;  /* rels supplying parameters used by path */
694         double          ppi_rows;               /* estimated number of result tuples */
695         List       *ppi_clauses;        /* join clauses available from outer rels */
696 } ParamPathInfo;
697
698
699 /*
700  * Type "Path" is used as-is for sequential-scan paths, as well as some other
701  * simple plan types that we don't need any extra information in the path for.
702  * For other path types it is the first component of a larger struct.
703  *
704  * "pathtype" is the NodeTag of the Plan node we could build from this Path.
705  * It is partially redundant with the Path's NodeTag, but allows us to use
706  * the same Path type for multiple Plan types when there is no need to
707  * distinguish the Plan type during path processing.
708  *
709  * "param_info", if not NULL, links to a ParamPathInfo that identifies outer
710  * relation(s) that provide parameter values to each scan of this path.
711  * That means this path can only be joined to those rels by means of nestloop
712  * joins with this path on the inside.  Also note that a parameterized path
713  * is responsible for testing all "movable" joinclauses involving this rel
714  * and the specified outer rel(s).
715  *
716  * "rows" is the same as parent->rows in simple paths, but in parameterized
717  * paths and UniquePaths it can be less than parent->rows, reflecting the
718  * fact that we've filtered by extra join conditions or removed duplicates.
719  *
720  * "pathkeys" is a List of PathKey nodes (see above), describing the sort
721  * ordering of the path's output rows.
722  */
723 typedef struct Path
724 {
725         NodeTag         type;
726
727         NodeTag         pathtype;               /* tag identifying scan/join method */
728
729         RelOptInfo *parent;                     /* the relation this path can build */
730         ParamPathInfo *param_info;      /* parameterization info, or NULL if none */
731
732         /* estimated size/costs for path (see costsize.c for more info) */
733         double          rows;                   /* estimated number of result tuples */
734         Cost            startup_cost;   /* cost expended before fetching any tuples */
735         Cost            total_cost;             /* total cost (assuming all tuples fetched) */
736
737         List       *pathkeys;           /* sort ordering of path's output */
738         /* pathkeys is a List of PathKey nodes; see above */
739 } Path;
740
741 /* Macro for extracting a path's parameterization relids; beware double eval */
742 #define PATH_REQ_OUTER(path)  \
743         ((path)->param_info ? (path)->param_info->ppi_req_outer : (Relids) NULL)
744
745 /*----------
746  * IndexPath represents an index scan over a single index.
747  *
748  * This struct is used for both regular indexscans and index-only scans;
749  * path.pathtype is T_IndexScan or T_IndexOnlyScan to show which is meant.
750  *
751  * 'indexinfo' is the index to be scanned.
752  *
753  * 'indexclauses' is a list of index qualification clauses, with implicit
754  * AND semantics across the list.  Each clause is a RestrictInfo node from
755  * the query's WHERE or JOIN conditions.  An empty list implies a full
756  * index scan.
757  *
758  * 'indexquals' has the same structure as 'indexclauses', but it contains
759  * the actual index qual conditions that can be used with the index.
760  * In simple cases this is identical to 'indexclauses', but when special
761  * indexable operators appear in 'indexclauses', they are replaced by the
762  * derived indexscannable conditions in 'indexquals'.
763  *
764  * 'indexqualcols' is an integer list of index column numbers (zero-based)
765  * of the same length as 'indexquals', showing which index column each qual
766  * is meant to be used with.  'indexquals' is required to be ordered by
767  * index column, so 'indexqualcols' must form a nondecreasing sequence.
768  * (The order of multiple quals for the same index column is unspecified.)
769  *
770  * 'indexorderbys', if not NIL, is a list of ORDER BY expressions that have
771  * been found to be usable as ordering operators for an amcanorderbyop index.
772  * The list must match the path's pathkeys, ie, one expression per pathkey
773  * in the same order.  These are not RestrictInfos, just bare expressions,
774  * since they generally won't yield booleans.  Also, unlike the case for
775  * quals, it's guaranteed that each expression has the index key on the left
776  * side of the operator.
777  *
778  * 'indexorderbycols' is an integer list of index column numbers (zero-based)
779  * of the same length as 'indexorderbys', showing which index column each
780  * ORDER BY expression is meant to be used with.  (There is no restriction
781  * on which index column each ORDER BY can be used with.)
782  *
783  * 'indexscandir' is one of:
784  *              ForwardScanDirection: forward scan of an ordered index
785  *              BackwardScanDirection: backward scan of an ordered index
786  *              NoMovementScanDirection: scan of an unordered index, or don't care
787  * (The executor doesn't care whether it gets ForwardScanDirection or
788  * NoMovementScanDirection for an indexscan, but the planner wants to
789  * distinguish ordered from unordered indexes for building pathkeys.)
790  *
791  * 'indextotalcost' and 'indexselectivity' are saved in the IndexPath so that
792  * we need not recompute them when considering using the same index in a
793  * bitmap index/heap scan (see BitmapHeapPath).  The costs of the IndexPath
794  * itself represent the costs of an IndexScan or IndexOnlyScan plan type.
795  *----------
796  */
797 typedef struct IndexPath
798 {
799         Path            path;
800         IndexOptInfo *indexinfo;
801         List       *indexclauses;
802         List       *indexquals;
803         List       *indexqualcols;
804         List       *indexorderbys;
805         List       *indexorderbycols;
806         ScanDirection indexscandir;
807         Cost            indextotalcost;
808         Selectivity indexselectivity;
809 } IndexPath;
810
811 /*
812  * BitmapHeapPath represents one or more indexscans that generate TID bitmaps
813  * instead of directly accessing the heap, followed by AND/OR combinations
814  * to produce a single bitmap, followed by a heap scan that uses the bitmap.
815  * Note that the output is always considered unordered, since it will come
816  * out in physical heap order no matter what the underlying indexes did.
817  *
818  * The individual indexscans are represented by IndexPath nodes, and any
819  * logic on top of them is represented by a tree of BitmapAndPath and
820  * BitmapOrPath nodes.  Notice that we can use the same IndexPath node both
821  * to represent a regular (or index-only) index scan plan, and as the child
822  * of a BitmapHeapPath that represents scanning the same index using a
823  * BitmapIndexScan.  The startup_cost and total_cost figures of an IndexPath
824  * always represent the costs to use it as a regular (or index-only)
825  * IndexScan.  The costs of a BitmapIndexScan can be computed using the
826  * IndexPath's indextotalcost and indexselectivity.
827  */
828 typedef struct BitmapHeapPath
829 {
830         Path            path;
831         Path       *bitmapqual;         /* IndexPath, BitmapAndPath, BitmapOrPath */
832 } BitmapHeapPath;
833
834 /*
835  * BitmapAndPath represents a BitmapAnd plan node; it can only appear as
836  * part of the substructure of a BitmapHeapPath.  The Path structure is
837  * a bit more heavyweight than we really need for this, but for simplicity
838  * we make it a derivative of Path anyway.
839  */
840 typedef struct BitmapAndPath
841 {
842         Path            path;
843         List       *bitmapquals;        /* IndexPaths and BitmapOrPaths */
844         Selectivity bitmapselectivity;
845 } BitmapAndPath;
846
847 /*
848  * BitmapOrPath represents a BitmapOr plan node; it can only appear as
849  * part of the substructure of a BitmapHeapPath.  The Path structure is
850  * a bit more heavyweight than we really need for this, but for simplicity
851  * we make it a derivative of Path anyway.
852  */
853 typedef struct BitmapOrPath
854 {
855         Path            path;
856         List       *bitmapquals;        /* IndexPaths and BitmapAndPaths */
857         Selectivity bitmapselectivity;
858 } BitmapOrPath;
859
860 /*
861  * TidPath represents a scan by TID
862  *
863  * tidquals is an implicitly OR'ed list of qual expressions of the form
864  * "CTID = pseudoconstant" or "CTID = ANY(pseudoconstant_array)".
865  * Note they are bare expressions, not RestrictInfos.
866  */
867 typedef struct TidPath
868 {
869         Path            path;
870         List       *tidquals;           /* qual(s) involving CTID = something */
871 } TidPath;
872
873 /*
874  * ForeignPath represents a potential scan of a foreign table
875  *
876  * fdw_private stores FDW private data about the scan.  While fdw_private is
877  * not actually touched by the core code during normal operations, it's
878  * generally a good idea to use a representation that can be dumped by
879  * nodeToString(), so that you can examine the structure during debugging
880  * with tools like pprint().
881  */
882 typedef struct ForeignPath
883 {
884         Path            path;
885         List       *fdw_private;
886 } ForeignPath;
887
888 /*
889  * CustomPath represents a table scan done by some out-of-core extension.
890  *
891  * We provide a set of hooks here - which the provider must take care to set
892  * up correctly - to allow extensions to supply their own methods of scanning
893  * a relation.  For example, a provider might provide GPU acceleration, a
894  * cache-based scan, or some other kind of logic we haven't dreamed up yet.
895  *
896  * CustomPaths can be injected into the planning process for a relation by
897  * set_rel_pathlist_hook functions.
898  *
899  * Core code must avoid assuming that the CustomPath is only as large as
900  * the structure declared here; providers are allowed to make it the first
901  * element in a larger structure.  (Since the planner never copies Paths,
902  * this doesn't add any complication.)  However, for consistency with the
903  * FDW case, we provide a "custom_private" field in CustomPath; providers
904  * may prefer to use that rather than define another struct type.
905  */
906 struct CustomPath;
907
908 #define CUSTOMPATH_SUPPORT_BACKWARD_SCAN        0x0001
909 #define CUSTOMPATH_SUPPORT_MARK_RESTORE         0x0002
910
911 typedef struct CustomPathMethods
912 {
913         const char *CustomName;
914
915         /* Convert Path to a Plan */
916         struct Plan *(*PlanCustomPath) (PlannerInfo *root,
917                                                                                                 RelOptInfo *rel,
918                                                                                                 struct CustomPath *best_path,
919                                                                                                 List *tlist,
920                                                                                                 List *clauses);
921         /* Optional: print additional fields besides "private" */
922         void            (*TextOutCustomPath) (StringInfo str,
923                                                                                           const struct CustomPath *node);
924 } CustomPathMethods;
925
926 typedef struct CustomPath
927 {
928         Path            path;
929         uint32          flags;                  /* mask of CUSTOMPATH_* flags, see above */
930         List       *custom_private;
931         const CustomPathMethods *methods;
932 } CustomPath;
933
934 /*
935  * AppendPath represents an Append plan, ie, successive execution of
936  * several member plans.
937  *
938  * Note: it is possible for "subpaths" to contain only one, or even no,
939  * elements.  These cases are optimized during create_append_plan.
940  * In particular, an AppendPath with no subpaths is a "dummy" path that
941  * is created to represent the case that a relation is provably empty.
942  */
943 typedef struct AppendPath
944 {
945         Path            path;
946         List       *subpaths;           /* list of component Paths */
947 } AppendPath;
948
949 #define IS_DUMMY_PATH(p) \
950         (IsA((p), AppendPath) && ((AppendPath *) (p))->subpaths == NIL)
951
952 /* A relation that's been proven empty will have one path that is dummy */
953 #define IS_DUMMY_REL(r) \
954         ((r)->cheapest_total_path != NULL && \
955          IS_DUMMY_PATH((r)->cheapest_total_path))
956
957 /*
958  * MergeAppendPath represents a MergeAppend plan, ie, the merging of sorted
959  * results from several member plans to produce similarly-sorted output.
960  */
961 typedef struct MergeAppendPath
962 {
963         Path            path;
964         List       *subpaths;           /* list of component Paths */
965         double          limit_tuples;   /* hard limit on output tuples, or -1 */
966 } MergeAppendPath;
967
968 /*
969  * ResultPath represents use of a Result plan node to compute a variable-free
970  * targetlist with no underlying tables (a "SELECT expressions" query).
971  * The query could have a WHERE clause, too, represented by "quals".
972  *
973  * Note that quals is a list of bare clauses, not RestrictInfos.
974  */
975 typedef struct ResultPath
976 {
977         Path            path;
978         List       *quals;
979 } ResultPath;
980
981 /*
982  * MaterialPath represents use of a Material plan node, i.e., caching of
983  * the output of its subpath.  This is used when the subpath is expensive
984  * and needs to be scanned repeatedly, or when we need mark/restore ability
985  * and the subpath doesn't have it.
986  */
987 typedef struct MaterialPath
988 {
989         Path            path;
990         Path       *subpath;
991 } MaterialPath;
992
993 /*
994  * UniquePath represents elimination of distinct rows from the output of
995  * its subpath.
996  *
997  * This is unlike the other Path nodes in that it can actually generate
998  * different plans: either hash-based or sort-based implementation, or a
999  * no-op if the input path can be proven distinct already.  The decision
1000  * is sufficiently localized that it's not worth having separate Path node
1001  * types.  (Note: in the no-op case, we could eliminate the UniquePath node
1002  * entirely and just return the subpath; but it's convenient to have a
1003  * UniquePath in the path tree to signal upper-level routines that the input
1004  * is known distinct.)
1005  */
1006 typedef enum
1007 {
1008         UNIQUE_PATH_NOOP,                       /* input is known unique already */
1009         UNIQUE_PATH_HASH,                       /* use hashing */
1010         UNIQUE_PATH_SORT                        /* use sorting */
1011 } UniquePathMethod;
1012
1013 typedef struct UniquePath
1014 {
1015         Path            path;
1016         Path       *subpath;
1017         UniquePathMethod umethod;
1018         List       *in_operators;       /* equality operators of the IN clause */
1019         List       *uniq_exprs;         /* expressions to be made unique */
1020 } UniquePath;
1021
1022 /*
1023  * All join-type paths share these fields.
1024  */
1025
1026 typedef struct JoinPath
1027 {
1028         Path            path;
1029
1030         JoinType        jointype;
1031
1032         Path       *outerjoinpath;      /* path for the outer side of the join */
1033         Path       *innerjoinpath;      /* path for the inner side of the join */
1034
1035         List       *joinrestrictinfo;           /* RestrictInfos to apply to join */
1036
1037         /*
1038          * See the notes for RelOptInfo and ParamPathInfo to understand why
1039          * joinrestrictinfo is needed in JoinPath, and can't be merged into the
1040          * parent RelOptInfo.
1041          */
1042 } JoinPath;
1043
1044 /*
1045  * A nested-loop path needs no special fields.
1046  */
1047
1048 typedef JoinPath NestPath;
1049
1050 /*
1051  * A mergejoin path has these fields.
1052  *
1053  * Unlike other path types, a MergePath node doesn't represent just a single
1054  * run-time plan node: it can represent up to four.  Aside from the MergeJoin
1055  * node itself, there can be a Sort node for the outer input, a Sort node
1056  * for the inner input, and/or a Material node for the inner input.  We could
1057  * represent these nodes by separate path nodes, but considering how many
1058  * different merge paths are investigated during a complex join problem,
1059  * it seems better to avoid unnecessary palloc overhead.
1060  *
1061  * path_mergeclauses lists the clauses (in the form of RestrictInfos)
1062  * that will be used in the merge.
1063  *
1064  * Note that the mergeclauses are a subset of the parent relation's
1065  * restriction-clause list.  Any join clauses that are not mergejoinable
1066  * appear only in the parent's restrict list, and must be checked by a
1067  * qpqual at execution time.
1068  *
1069  * outersortkeys (resp. innersortkeys) is NIL if the outer path
1070  * (resp. inner path) is already ordered appropriately for the
1071  * mergejoin.  If it is not NIL then it is a PathKeys list describing
1072  * the ordering that must be created by an explicit Sort node.
1073  *
1074  * materialize_inner is TRUE if a Material node should be placed atop the
1075  * inner input.  This may appear with or without an inner Sort step.
1076  */
1077
1078 typedef struct MergePath
1079 {
1080         JoinPath        jpath;
1081         List       *path_mergeclauses;          /* join clauses to be used for merge */
1082         List       *outersortkeys;      /* keys for explicit sort, if any */
1083         List       *innersortkeys;      /* keys for explicit sort, if any */
1084         bool            materialize_inner;              /* add Materialize to inner? */
1085 } MergePath;
1086
1087 /*
1088  * A hashjoin path has these fields.
1089  *
1090  * The remarks above for mergeclauses apply for hashclauses as well.
1091  *
1092  * Hashjoin does not care what order its inputs appear in, so we have
1093  * no need for sortkeys.
1094  */
1095
1096 typedef struct HashPath
1097 {
1098         JoinPath        jpath;
1099         List       *path_hashclauses;           /* join clauses used for hashing */
1100         int                     num_batches;    /* number of batches expected */
1101 } HashPath;
1102
1103 /*
1104  * Restriction clause info.
1105  *
1106  * We create one of these for each AND sub-clause of a restriction condition
1107  * (WHERE or JOIN/ON clause).  Since the restriction clauses are logically
1108  * ANDed, we can use any one of them or any subset of them to filter out
1109  * tuples, without having to evaluate the rest.  The RestrictInfo node itself
1110  * stores data used by the optimizer while choosing the best query plan.
1111  *
1112  * If a restriction clause references a single base relation, it will appear
1113  * in the baserestrictinfo list of the RelOptInfo for that base rel.
1114  *
1115  * If a restriction clause references more than one base rel, it will
1116  * appear in the joininfo list of every RelOptInfo that describes a strict
1117  * subset of the base rels mentioned in the clause.  The joininfo lists are
1118  * used to drive join tree building by selecting plausible join candidates.
1119  * The clause cannot actually be applied until we have built a join rel
1120  * containing all the base rels it references, however.
1121  *
1122  * When we construct a join rel that includes all the base rels referenced
1123  * in a multi-relation restriction clause, we place that clause into the
1124  * joinrestrictinfo lists of paths for the join rel, if neither left nor
1125  * right sub-path includes all base rels referenced in the clause.  The clause
1126  * will be applied at that join level, and will not propagate any further up
1127  * the join tree.  (Note: the "predicate migration" code was once intended to
1128  * push restriction clauses up and down the plan tree based on evaluation
1129  * costs, but it's dead code and is unlikely to be resurrected in the
1130  * foreseeable future.)
1131  *
1132  * Note that in the presence of more than two rels, a multi-rel restriction
1133  * might reach different heights in the join tree depending on the join
1134  * sequence we use.  So, these clauses cannot be associated directly with
1135  * the join RelOptInfo, but must be kept track of on a per-join-path basis.
1136  *
1137  * RestrictInfos that represent equivalence conditions (i.e., mergejoinable
1138  * equalities that are not outerjoin-delayed) are handled a bit differently.
1139  * Initially we attach them to the EquivalenceClasses that are derived from
1140  * them.  When we construct a scan or join path, we look through all the
1141  * EquivalenceClasses and generate derived RestrictInfos representing the
1142  * minimal set of conditions that need to be checked for this particular scan
1143  * or join to enforce that all members of each EquivalenceClass are in fact
1144  * equal in all rows emitted by the scan or join.
1145  *
1146  * When dealing with outer joins we have to be very careful about pushing qual
1147  * clauses up and down the tree.  An outer join's own JOIN/ON conditions must
1148  * be evaluated exactly at that join node, unless they are "degenerate"
1149  * conditions that reference only Vars from the nullable side of the join.
1150  * Quals appearing in WHERE or in a JOIN above the outer join cannot be pushed
1151  * down below the outer join, if they reference any nullable Vars.
1152  * RestrictInfo nodes contain a flag to indicate whether a qual has been
1153  * pushed down to a lower level than its original syntactic placement in the
1154  * join tree would suggest.  If an outer join prevents us from pushing a qual
1155  * down to its "natural" semantic level (the level associated with just the
1156  * base rels used in the qual) then we mark the qual with a "required_relids"
1157  * value including more than just the base rels it actually uses.  By
1158  * pretending that the qual references all the rels required to form the outer
1159  * join, we prevent it from being evaluated below the outer join's joinrel.
1160  * When we do form the outer join's joinrel, we still need to distinguish
1161  * those quals that are actually in that join's JOIN/ON condition from those
1162  * that appeared elsewhere in the tree and were pushed down to the join rel
1163  * because they used no other rels.  That's what the is_pushed_down flag is
1164  * for; it tells us that a qual is not an OUTER JOIN qual for the set of base
1165  * rels listed in required_relids.  A clause that originally came from WHERE
1166  * or an INNER JOIN condition will *always* have its is_pushed_down flag set.
1167  * It's possible for an OUTER JOIN clause to be marked is_pushed_down too,
1168  * if we decide that it can be pushed down into the nullable side of the join.
1169  * In that case it acts as a plain filter qual for wherever it gets evaluated.
1170  * (In short, is_pushed_down is only false for non-degenerate outer join
1171  * conditions.  Possibly we should rename it to reflect that meaning?)
1172  *
1173  * RestrictInfo nodes also contain an outerjoin_delayed flag, which is true
1174  * if the clause's applicability must be delayed due to any outer joins
1175  * appearing below it (ie, it has to be postponed to some join level higher
1176  * than the set of relations it actually references).
1177  *
1178  * There is also an outer_relids field, which is NULL except for outer join
1179  * clauses; for those, it is the set of relids on the outer side of the
1180  * clause's outer join.  (These are rels that the clause cannot be applied to
1181  * in parameterized scans, since pushing it into the join's outer side would
1182  * lead to wrong answers.)
1183  *
1184  * There is also a nullable_relids field, which is the set of rels the clause
1185  * references that can be forced null by some outer join below the clause.
1186  *
1187  * outerjoin_delayed = true is subtly different from nullable_relids != NULL:
1188  * a clause might reference some nullable rels and yet not be
1189  * outerjoin_delayed because it also references all the other rels of the
1190  * outer join(s). A clause that is not outerjoin_delayed can be enforced
1191  * anywhere it is computable.
1192  *
1193  * In general, the referenced clause might be arbitrarily complex.  The
1194  * kinds of clauses we can handle as indexscan quals, mergejoin clauses,
1195  * or hashjoin clauses are limited (e.g., no volatile functions).  The code
1196  * for each kind of path is responsible for identifying the restrict clauses
1197  * it can use and ignoring the rest.  Clauses not implemented by an indexscan,
1198  * mergejoin, or hashjoin will be placed in the plan qual or joinqual field
1199  * of the finished Plan node, where they will be enforced by general-purpose
1200  * qual-expression-evaluation code.  (But we are still entitled to count
1201  * their selectivity when estimating the result tuple count, if we
1202  * can guess what it is...)
1203  *
1204  * When the referenced clause is an OR clause, we generate a modified copy
1205  * in which additional RestrictInfo nodes are inserted below the top-level
1206  * OR/AND structure.  This is a convenience for OR indexscan processing:
1207  * indexquals taken from either the top level or an OR subclause will have
1208  * associated RestrictInfo nodes.
1209  *
1210  * The can_join flag is set true if the clause looks potentially useful as
1211  * a merge or hash join clause, that is if it is a binary opclause with
1212  * nonoverlapping sets of relids referenced in the left and right sides.
1213  * (Whether the operator is actually merge or hash joinable isn't checked,
1214  * however.)
1215  *
1216  * The pseudoconstant flag is set true if the clause contains no Vars of
1217  * the current query level and no volatile functions.  Such a clause can be
1218  * pulled out and used as a one-time qual in a gating Result node.  We keep
1219  * pseudoconstant clauses in the same lists as other RestrictInfos so that
1220  * the regular clause-pushing machinery can assign them to the correct join
1221  * level, but they need to be treated specially for cost and selectivity
1222  * estimates.  Note that a pseudoconstant clause can never be an indexqual
1223  * or merge or hash join clause, so it's of no interest to large parts of
1224  * the planner.
1225  *
1226  * When join clauses are generated from EquivalenceClasses, there may be
1227  * several equally valid ways to enforce join equivalence, of which we need
1228  * apply only one.  We mark clauses of this kind by setting parent_ec to
1229  * point to the generating EquivalenceClass.  Multiple clauses with the same
1230  * parent_ec in the same join are redundant.
1231  */
1232
1233 typedef struct RestrictInfo
1234 {
1235         NodeTag         type;
1236
1237         Expr       *clause;                     /* the represented clause of WHERE or JOIN */
1238
1239         bool            is_pushed_down; /* TRUE if clause was pushed down in level */
1240
1241         bool            outerjoin_delayed;              /* TRUE if delayed by lower outer join */
1242
1243         bool            can_join;               /* see comment above */
1244
1245         bool            pseudoconstant; /* see comment above */
1246
1247         /* The set of relids (varnos) actually referenced in the clause: */
1248         Relids          clause_relids;
1249
1250         /* The set of relids required to evaluate the clause: */
1251         Relids          required_relids;
1252
1253         /* If an outer-join clause, the outer-side relations, else NULL: */
1254         Relids          outer_relids;
1255
1256         /* The relids used in the clause that are nullable by lower outer joins: */
1257         Relids          nullable_relids;
1258
1259         /* These fields are set for any binary opclause: */
1260         Relids          left_relids;    /* relids in left side of clause */
1261         Relids          right_relids;   /* relids in right side of clause */
1262
1263         /* This field is NULL unless clause is an OR clause: */
1264         Expr       *orclause;           /* modified clause with RestrictInfos */
1265
1266         /* This field is NULL unless clause is potentially redundant: */
1267         EquivalenceClass *parent_ec;    /* generating EquivalenceClass */
1268
1269         /* cache space for cost and selectivity */
1270         QualCost        eval_cost;              /* eval cost of clause; -1 if not yet set */
1271         Selectivity norm_selec;         /* selectivity for "normal" (JOIN_INNER)
1272                                                                  * semantics; -1 if not yet set; >1 means a
1273                                                                  * redundant clause */
1274         Selectivity outer_selec;        /* selectivity for outer join semantics; -1 if
1275                                                                  * not yet set */
1276
1277         /* valid if clause is mergejoinable, else NIL */
1278         List       *mergeopfamilies;    /* opfamilies containing clause operator */
1279
1280         /* cache space for mergeclause processing; NULL if not yet set */
1281         EquivalenceClass *left_ec;      /* EquivalenceClass containing lefthand */
1282         EquivalenceClass *right_ec; /* EquivalenceClass containing righthand */
1283         EquivalenceMember *left_em; /* EquivalenceMember for lefthand */
1284         EquivalenceMember *right_em;    /* EquivalenceMember for righthand */
1285         List       *scansel_cache;      /* list of MergeScanSelCache structs */
1286
1287         /* transient workspace for use while considering a specific join path */
1288         bool            outer_is_left;  /* T = outer var on left, F = on right */
1289
1290         /* valid if clause is hashjoinable, else InvalidOid: */
1291         Oid                     hashjoinoperator;               /* copy of clause operator */
1292
1293         /* cache space for hashclause processing; -1 if not yet set */
1294         Selectivity left_bucketsize;    /* avg bucketsize of left side */
1295         Selectivity right_bucketsize;           /* avg bucketsize of right side */
1296 } RestrictInfo;
1297
1298 /*
1299  * Since mergejoinscansel() is a relatively expensive function, and would
1300  * otherwise be invoked many times while planning a large join tree,
1301  * we go out of our way to cache its results.  Each mergejoinable
1302  * RestrictInfo carries a list of the specific sort orderings that have
1303  * been considered for use with it, and the resulting selectivities.
1304  */
1305 typedef struct MergeScanSelCache
1306 {
1307         /* Ordering details (cache lookup key) */
1308         Oid                     opfamily;               /* btree opfamily defining the ordering */
1309         Oid                     collation;              /* collation for the ordering */
1310         int                     strategy;               /* sort direction (ASC or DESC) */
1311         bool            nulls_first;    /* do NULLs come before normal values? */
1312         /* Results */
1313         Selectivity leftstartsel;       /* first-join fraction for clause left side */
1314         Selectivity leftendsel;         /* last-join fraction for clause left side */
1315         Selectivity rightstartsel;      /* first-join fraction for clause right side */
1316         Selectivity rightendsel;        /* last-join fraction for clause right side */
1317 } MergeScanSelCache;
1318
1319 /*
1320  * Placeholder node for an expression to be evaluated below the top level
1321  * of a plan tree.  This is used during planning to represent the contained
1322  * expression.  At the end of the planning process it is replaced by either
1323  * the contained expression or a Var referring to a lower-level evaluation of
1324  * the contained expression.  Typically the evaluation occurs below an outer
1325  * join, and Var references above the outer join might thereby yield NULL
1326  * instead of the expression value.
1327  *
1328  * Although the planner treats this as an expression node type, it is not
1329  * recognized by the parser or executor, so we declare it here rather than
1330  * in primnodes.h.
1331  */
1332
1333 typedef struct PlaceHolderVar
1334 {
1335         Expr            xpr;
1336         Expr       *phexpr;                     /* the represented expression */
1337         Relids          phrels;                 /* base relids syntactically within expr src */
1338         Index           phid;                   /* ID for PHV (unique within planner run) */
1339         Index           phlevelsup;             /* > 0 if PHV belongs to outer query */
1340 } PlaceHolderVar;
1341
1342 /*
1343  * "Special join" info.
1344  *
1345  * One-sided outer joins constrain the order of joining partially but not
1346  * completely.  We flatten such joins into the planner's top-level list of
1347  * relations to join, but record information about each outer join in a
1348  * SpecialJoinInfo struct.  These structs are kept in the PlannerInfo node's
1349  * join_info_list.
1350  *
1351  * Similarly, semijoins and antijoins created by flattening IN (subselect)
1352  * and EXISTS(subselect) clauses create partial constraints on join order.
1353  * These are likewise recorded in SpecialJoinInfo structs.
1354  *
1355  * We make SpecialJoinInfos for FULL JOINs even though there is no flexibility
1356  * of planning for them, because this simplifies make_join_rel()'s API.
1357  *
1358  * min_lefthand and min_righthand are the sets of base relids that must be
1359  * available on each side when performing the special join.  lhs_strict is
1360  * true if the special join's condition cannot succeed when the LHS variables
1361  * are all NULL (this means that an outer join can commute with upper-level
1362  * outer joins even if it appears in their RHS).  We don't bother to set
1363  * lhs_strict for FULL JOINs, however.
1364  *
1365  * It is not valid for either min_lefthand or min_righthand to be empty sets;
1366  * if they were, this would break the logic that enforces join order.
1367  *
1368  * syn_lefthand and syn_righthand are the sets of base relids that are
1369  * syntactically below this special join.  (These are needed to help compute
1370  * min_lefthand and min_righthand for higher joins.)
1371  *
1372  * delay_upper_joins is set TRUE if we detect a pushed-down clause that has
1373  * to be evaluated after this join is formed (because it references the RHS).
1374  * Any outer joins that have such a clause and this join in their RHS cannot
1375  * commute with this join, because that would leave noplace to check the
1376  * pushed-down clause.  (We don't track this for FULL JOINs, either.)
1377  *
1378  * For a semijoin, we also extract the join operators and their RHS arguments
1379  * and set semi_operators, semi_rhs_exprs, semi_can_btree, and semi_can_hash.
1380  * This is done in support of possibly unique-ifying the RHS, so we don't
1381  * bother unless at least one of semi_can_btree and semi_can_hash can be set
1382  * true.  (You might expect that this information would be computed during
1383  * join planning; but it's helpful to have it available during planning of
1384  * parameterized table scans, so we store it in the SpecialJoinInfo structs.)
1385  *
1386  * jointype is never JOIN_RIGHT; a RIGHT JOIN is handled by switching
1387  * the inputs to make it a LEFT JOIN.  So the allowed values of jointype
1388  * in a join_info_list member are only LEFT, FULL, SEMI, or ANTI.
1389  *
1390  * For purposes of join selectivity estimation, we create transient
1391  * SpecialJoinInfo structures for regular inner joins; so it is possible
1392  * to have jointype == JOIN_INNER in such a structure, even though this is
1393  * not allowed within join_info_list.  We also create transient
1394  * SpecialJoinInfos with jointype == JOIN_INNER for outer joins, since for
1395  * cost estimation purposes it is sometimes useful to know the join size under
1396  * plain innerjoin semantics.  Note that lhs_strict, delay_upper_joins, and
1397  * of course the semi_xxx fields are not set meaningfully within such structs.
1398  */
1399
1400 typedef struct SpecialJoinInfo
1401 {
1402         NodeTag         type;
1403         Relids          min_lefthand;   /* base relids in minimum LHS for join */
1404         Relids          min_righthand;  /* base relids in minimum RHS for join */
1405         Relids          syn_lefthand;   /* base relids syntactically within LHS */
1406         Relids          syn_righthand;  /* base relids syntactically within RHS */
1407         JoinType        jointype;               /* always INNER, LEFT, FULL, SEMI, or ANTI */
1408         bool            lhs_strict;             /* joinclause is strict for some LHS rel */
1409         bool            delay_upper_joins;              /* can't commute with upper RHS */
1410         /* Remaining fields are set only for JOIN_SEMI jointype: */
1411         bool            semi_can_btree; /* true if semi_operators are all btree */
1412         bool            semi_can_hash;  /* true if semi_operators are all hash */
1413         List       *semi_operators; /* OIDs of equality join operators */
1414         List       *semi_rhs_exprs; /* righthand-side expressions of these ops */
1415 } SpecialJoinInfo;
1416
1417 /*
1418  * "Lateral join" info.
1419  *
1420  * Lateral references constrain the join order in a way that's somewhat like
1421  * outer joins, though different in detail.  We construct a LateralJoinInfo
1422  * for each lateral cross-reference, placing them in the PlannerInfo node's
1423  * lateral_info_list.
1424  *
1425  * For unflattened LATERAL RTEs, we generate LateralJoinInfo(s) in which
1426  * lateral_rhs is the relid of the LATERAL baserel, and lateral_lhs is a set
1427  * of relids of baserels it references, all of which must be present on the
1428  * LHS to compute a parameter needed by the RHS.  Typically, lateral_lhs is
1429  * a singleton, but it can include multiple rels if the RHS references a
1430  * PlaceHolderVar with a multi-rel ph_eval_at level.  We disallow joining to
1431  * only part of the LHS in such cases, since that would result in a join tree
1432  * with no convenient place to compute the PHV.
1433  *
1434  * When an appendrel contains lateral references (eg "LATERAL (SELECT x.col1
1435  * UNION ALL SELECT y.col2)"), the LateralJoinInfos reference the parent
1436  * baserel not the member otherrels, since it is the parent relid that is
1437  * considered for joining purposes.
1438  *
1439  * If any LATERAL RTEs were flattened into the parent query, it is possible
1440  * that the query now contains PlaceHolderVars containing lateral references,
1441  * representing expressions that need to be evaluated at particular spots in
1442  * the jointree but contain lateral references to Vars from elsewhere.  These
1443  * give rise to LateralJoinInfos in which lateral_rhs is the evaluation point
1444  * of a PlaceHolderVar and lateral_lhs is the set of lateral rels it needs.
1445  */
1446
1447 typedef struct LateralJoinInfo
1448 {
1449         NodeTag         type;
1450         Relids          lateral_lhs;    /* rels needed to compute a lateral value */
1451         Relids          lateral_rhs;    /* rel where lateral value is needed */
1452 } LateralJoinInfo;
1453
1454 /*
1455  * Append-relation info.
1456  *
1457  * When we expand an inheritable table or a UNION-ALL subselect into an
1458  * "append relation" (essentially, a list of child RTEs), we build an
1459  * AppendRelInfo for each child RTE.  The list of AppendRelInfos indicates
1460  * which child RTEs must be included when expanding the parent, and each
1461  * node carries information needed to translate Vars referencing the parent
1462  * into Vars referencing that child.
1463  *
1464  * These structs are kept in the PlannerInfo node's append_rel_list.
1465  * Note that we just throw all the structs into one list, and scan the
1466  * whole list when desiring to expand any one parent.  We could have used
1467  * a more complex data structure (eg, one list per parent), but this would
1468  * be harder to update during operations such as pulling up subqueries,
1469  * and not really any easier to scan.  Considering that typical queries
1470  * will not have many different append parents, it doesn't seem worthwhile
1471  * to complicate things.
1472  *
1473  * Note: after completion of the planner prep phase, any given RTE is an
1474  * append parent having entries in append_rel_list if and only if its
1475  * "inh" flag is set.  We clear "inh" for plain tables that turn out not
1476  * to have inheritance children, and (in an abuse of the original meaning
1477  * of the flag) we set "inh" for subquery RTEs that turn out to be
1478  * flattenable UNION ALL queries.  This lets us avoid useless searches
1479  * of append_rel_list.
1480  *
1481  * Note: the data structure assumes that append-rel members are single
1482  * baserels.  This is OK for inheritance, but it prevents us from pulling
1483  * up a UNION ALL member subquery if it contains a join.  While that could
1484  * be fixed with a more complex data structure, at present there's not much
1485  * point because no improvement in the plan could result.
1486  */
1487
1488 typedef struct AppendRelInfo
1489 {
1490         NodeTag         type;
1491
1492         /*
1493          * These fields uniquely identify this append relationship.  There can be
1494          * (in fact, always should be) multiple AppendRelInfos for the same
1495          * parent_relid, but never more than one per child_relid, since a given
1496          * RTE cannot be a child of more than one append parent.
1497          */
1498         Index           parent_relid;   /* RT index of append parent rel */
1499         Index           child_relid;    /* RT index of append child rel */
1500
1501         /*
1502          * For an inheritance appendrel, the parent and child are both regular
1503          * relations, and we store their rowtype OIDs here for use in translating
1504          * whole-row Vars.  For a UNION-ALL appendrel, the parent and child are
1505          * both subqueries with no named rowtype, and we store InvalidOid here.
1506          */
1507         Oid                     parent_reltype; /* OID of parent's composite type */
1508         Oid                     child_reltype;  /* OID of child's composite type */
1509
1510         /*
1511          * The N'th element of this list is a Var or expression representing the
1512          * child column corresponding to the N'th column of the parent. This is
1513          * used to translate Vars referencing the parent rel into references to
1514          * the child.  A list element is NULL if it corresponds to a dropped
1515          * column of the parent (this is only possible for inheritance cases, not
1516          * UNION ALL).  The list elements are always simple Vars for inheritance
1517          * cases, but can be arbitrary expressions in UNION ALL cases.
1518          *
1519          * Notice we only store entries for user columns (attno > 0).  Whole-row
1520          * Vars are special-cased, and system columns (attno < 0) need no special
1521          * translation since their attnos are the same for all tables.
1522          *
1523          * Caution: the Vars have varlevelsup = 0.  Be careful to adjust as needed
1524          * when copying into a subquery.
1525          */
1526         List       *translated_vars;    /* Expressions in the child's Vars */
1527
1528         /*
1529          * We store the parent table's OID here for inheritance, or InvalidOid for
1530          * UNION ALL.  This is only needed to help in generating error messages if
1531          * an attempt is made to reference a dropped parent column.
1532          */
1533         Oid                     parent_reloid;  /* OID of parent relation */
1534 } AppendRelInfo;
1535
1536 /*
1537  * For each distinct placeholder expression generated during planning, we
1538  * store a PlaceHolderInfo node in the PlannerInfo node's placeholder_list.
1539  * This stores info that is needed centrally rather than in each copy of the
1540  * PlaceHolderVar.  The phid fields identify which PlaceHolderInfo goes with
1541  * each PlaceHolderVar.  Note that phid is unique throughout a planner run,
1542  * not just within a query level --- this is so that we need not reassign ID's
1543  * when pulling a subquery into its parent.
1544  *
1545  * The idea is to evaluate the expression at (only) the ph_eval_at join level,
1546  * then allow it to bubble up like a Var until the ph_needed join level.
1547  * ph_needed has the same definition as attr_needed for a regular Var.
1548  *
1549  * The PlaceHolderVar's expression might contain LATERAL references to vars
1550  * coming from outside its syntactic scope.  If so, those rels are *not*
1551  * included in ph_eval_at, but they are recorded in ph_lateral.
1552  *
1553  * Notice that when ph_eval_at is a join rather than a single baserel, the
1554  * PlaceHolderInfo may create constraints on join order: the ph_eval_at join
1555  * has to be formed below any outer joins that should null the PlaceHolderVar.
1556  *
1557  * We create a PlaceHolderInfo only after determining that the PlaceHolderVar
1558  * is actually referenced in the plan tree, so that unreferenced placeholders
1559  * don't result in unnecessary constraints on join order.
1560  */
1561
1562 typedef struct PlaceHolderInfo
1563 {
1564         NodeTag         type;
1565
1566         Index           phid;                   /* ID for PH (unique within planner run) */
1567         PlaceHolderVar *ph_var;         /* copy of PlaceHolderVar tree */
1568         Relids          ph_eval_at;             /* lowest level we can evaluate value at */
1569         Relids          ph_lateral;             /* relids of contained lateral refs, if any */
1570         Relids          ph_needed;              /* highest level the value is needed at */
1571         int32           ph_width;               /* estimated attribute width */
1572 } PlaceHolderInfo;
1573
1574 /*
1575  * For each potentially index-optimizable MIN/MAX aggregate function,
1576  * root->minmax_aggs stores a MinMaxAggInfo describing it.
1577  */
1578 typedef struct MinMaxAggInfo
1579 {
1580         NodeTag         type;
1581
1582         Oid                     aggfnoid;               /* pg_proc Oid of the aggregate */
1583         Oid                     aggsortop;              /* Oid of its sort operator */
1584         Expr       *target;                     /* expression we are aggregating on */
1585         PlannerInfo *subroot;           /* modified "root" for planning the subquery */
1586         Path       *path;                       /* access path for subquery */
1587         Cost            pathcost;               /* estimated cost to fetch first row */
1588         Param      *param;                      /* param for subplan's output */
1589 } MinMaxAggInfo;
1590
1591 /*
1592  * At runtime, PARAM_EXEC slots are used to pass values around from one plan
1593  * node to another.  They can be used to pass values down into subqueries (for
1594  * outer references in subqueries), or up out of subqueries (for the results
1595  * of a subplan), or from a NestLoop plan node into its inner relation (when
1596  * the inner scan is parameterized with values from the outer relation).
1597  * The planner is responsible for assigning nonconflicting PARAM_EXEC IDs to
1598  * the PARAM_EXEC Params it generates.
1599  *
1600  * Outer references are managed via root->plan_params, which is a list of
1601  * PlannerParamItems.  While planning a subquery, each parent query level's
1602  * plan_params contains the values required from it by the current subquery.
1603  * During create_plan(), we use plan_params to track values that must be
1604  * passed from outer to inner sides of NestLoop plan nodes.
1605  *
1606  * The item a PlannerParamItem represents can be one of three kinds:
1607  *
1608  * A Var: the slot represents a variable of this level that must be passed
1609  * down because subqueries have outer references to it, or must be passed
1610  * from a NestLoop node to its inner scan.  The varlevelsup value in the Var
1611  * will always be zero.
1612  *
1613  * A PlaceHolderVar: this works much like the Var case, except that the
1614  * entry is a PlaceHolderVar node with a contained expression.  The PHV
1615  * will have phlevelsup = 0, and the contained expression is adjusted
1616  * to match in level.
1617  *
1618  * An Aggref (with an expression tree representing its argument): the slot
1619  * represents an aggregate expression that is an outer reference for some
1620  * subquery.  The Aggref itself has agglevelsup = 0, and its argument tree
1621  * is adjusted to match in level.
1622  *
1623  * Note: we detect duplicate Var and PlaceHolderVar parameters and coalesce
1624  * them into one slot, but we do not bother to do that for Aggrefs.
1625  * The scope of duplicate-elimination only extends across the set of
1626  * parameters passed from one query level into a single subquery, or for
1627  * nestloop parameters across the set of nestloop parameters used in a single
1628  * query level.  So there is no possibility of a PARAM_EXEC slot being used
1629  * for conflicting purposes.
1630  *
1631  * In addition, PARAM_EXEC slots are assigned for Params representing outputs
1632  * from subplans (values that are setParam items for those subplans).  These
1633  * IDs need not be tracked via PlannerParamItems, since we do not need any
1634  * duplicate-elimination nor later processing of the represented expressions.
1635  * Instead, we just record the assignment of the slot number by incrementing
1636  * root->glob->nParamExec.
1637  */
1638 typedef struct PlannerParamItem
1639 {
1640         NodeTag         type;
1641
1642         Node       *item;                       /* the Var, PlaceHolderVar, or Aggref */
1643         int                     paramId;                /* its assigned PARAM_EXEC slot number */
1644 } PlannerParamItem;
1645
1646 /*
1647  * When making cost estimates for a SEMI or ANTI join, there are some
1648  * correction factors that are needed in both nestloop and hash joins
1649  * to account for the fact that the executor can stop scanning inner rows
1650  * as soon as it finds a match to the current outer row.  These numbers
1651  * depend only on the selected outer and inner join relations, not on the
1652  * particular paths used for them, so it's worthwhile to calculate them
1653  * just once per relation pair not once per considered path.  This struct
1654  * is filled by compute_semi_anti_join_factors and must be passed along
1655  * to the join cost estimation functions.
1656  *
1657  * outer_match_frac is the fraction of the outer tuples that are
1658  *              expected to have at least one match.
1659  * match_count is the average number of matches expected for
1660  *              outer tuples that have at least one match.
1661  */
1662 typedef struct SemiAntiJoinFactors
1663 {
1664         Selectivity outer_match_frac;
1665         Selectivity match_count;
1666 } SemiAntiJoinFactors;
1667
1668 /*
1669  * For speed reasons, cost estimation for join paths is performed in two
1670  * phases: the first phase tries to quickly derive a lower bound for the
1671  * join cost, and then we check if that's sufficient to reject the path.
1672  * If not, we come back for a more refined cost estimate.  The first phase
1673  * fills a JoinCostWorkspace struct with its preliminary cost estimates
1674  * and possibly additional intermediate values.  The second phase takes
1675  * these values as inputs to avoid repeating work.
1676  *
1677  * (Ideally we'd declare this in cost.h, but it's also needed in pathnode.h,
1678  * so seems best to put it here.)
1679  */
1680 typedef struct JoinCostWorkspace
1681 {
1682         /* Preliminary cost estimates --- must not be larger than final ones! */
1683         Cost            startup_cost;   /* cost expended before fetching any tuples */
1684         Cost            total_cost;             /* total cost (assuming all tuples fetched) */
1685
1686         /* Fields below here should be treated as private to costsize.c */
1687         Cost            run_cost;               /* non-startup cost components */
1688
1689         /* private for cost_nestloop code */
1690         Cost            inner_rescan_run_cost;
1691         double          outer_matched_rows;
1692         Selectivity inner_scan_frac;
1693
1694         /* private for cost_mergejoin code */
1695         Cost            inner_run_cost;
1696         double          outer_rows;
1697         double          inner_rows;
1698         double          outer_skip_rows;
1699         double          inner_skip_rows;
1700
1701         /* private for cost_hashjoin code */
1702         int                     numbuckets;
1703         int                     numbatches;
1704 } JoinCostWorkspace;
1705
1706 #endif   /* RELATION_H */