]> granicus.if.org Git - postgresql/blob - src/include/nodes/relation.h
Change the division of labor between grouping_planner and query_planner
[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-2005, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * $PostgreSQL: pgsql/src/include/nodes/relation.h,v 1.118 2005/08/27 22:13:43 tgl Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef RELATION_H
15 #define RELATION_H
16
17 #include "access/sdir.h"
18 #include "nodes/bitmapset.h"
19 #include "nodes/parsenodes.h"
20 #include "storage/block.h"
21
22
23 /*
24  * Relids
25  *              Set of relation identifiers (indexes into the rangetable).
26  */
27 typedef Bitmapset *Relids;
28
29 /*
30  * When looking for a "cheapest path", this enum specifies whether we want
31  * cheapest startup cost or cheapest total cost.
32  */
33 typedef enum CostSelector
34 {
35         STARTUP_COST, TOTAL_COST
36 } CostSelector;
37
38 /*
39  * The cost estimate produced by cost_qual_eval() includes both a one-time
40  * (startup) cost, and a per-tuple cost.
41  */
42 typedef struct QualCost
43 {
44         Cost            startup;                /* one-time cost */
45         Cost            per_tuple;              /* per-evaluation cost */
46 } QualCost;
47
48
49 /*----------
50  * PlannerInfo
51  *              Per-query information for planning/optimization
52  *
53  * This struct is conventionally called "root" in all the planner routines.
54  * It holds links to all of the planner's working state, in addition to the
55  * original Query.  Note that at present the planner extensively manipulates
56  * the passed-in Query data structure; someday that should stop.
57  *----------
58  */
59 typedef struct PlannerInfo
60 {
61         NodeTag         type;
62
63         Query      *parse;                      /* the Query being planned */
64
65         /*
66          * base_rel_array holds pointers to "base rels" and "other rels" (see
67          * comments for RelOptInfo for more info).  It is indexed by rangetable
68          * index (so entry 0 is always wasted).  Entries can be NULL when
69          * an RTE does not correspond to a base relation.  Note that the array
70          * may be enlarged on-the-fly.
71          */
72         struct RelOptInfo **base_rel_array;     /* All one-relation RelOptInfos */
73         int                     base_rel_array_size;    /* current allocated array len */
74
75         /*
76          * join_rel_list is a list of all join-relation RelOptInfos we have
77          * considered in this planning run.  For small problems we just scan
78          * the list to do lookups, but when there are many join relations we
79          * build a hash table for faster lookups.  The hash table is present
80          * and valid when join_rel_hash is not NULL.  Note that we still maintain
81          * the list even when using the hash table for lookups; this simplifies
82          * life for GEQO.
83          */
84         List       *join_rel_list;      /* list of join-relation RelOptInfos */
85         struct HTAB *join_rel_hash;     /* optional hashtable for join relations */
86
87         List       *equi_key_list;      /* list of lists of equijoined
88                                                                  * PathKeyItems */
89
90         List       *left_join_clauses;  /* list of RestrictInfos for outer join
91                                                                          * clauses w/nonnullable var on left */
92
93         List       *right_join_clauses; /* list of RestrictInfos for outer join
94                                                                          * clauses w/nonnullable var on right */
95
96         List       *full_join_clauses;  /* list of RestrictInfos for full outer
97                                                                          * join clauses */
98
99         List       *in_info_list;       /* list of InClauseInfos */
100
101         List       *query_pathkeys; /* desired pathkeys for query_planner(),
102                                                                  * and actual pathkeys afterwards */
103
104         List       *group_pathkeys; /* groupClause pathkeys, if any */
105         List       *sort_pathkeys;      /* sortClause pathkeys, if any */
106
107         double          tuple_fraction; /* tuple_fraction passed to query_planner */
108
109         bool            hasJoinRTEs;    /* true if any RTEs are RTE_JOIN kind */
110         bool            hasOuterJoins;  /* true if any RTEs are outer joins */
111         bool            hasHavingQual;  /* true if havingQual was non-null */
112 } PlannerInfo;
113
114
115 /*----------
116  * RelOptInfo
117  *              Per-relation information for planning/optimization
118  *
119  * For planning purposes, a "base rel" is either a plain relation (a table)
120  * or the output of a sub-SELECT or function that appears in the range table.
121  * In either case it is uniquely identified by an RT index.  A "joinrel"
122  * is the joining of two or more base rels.  A joinrel is identified by
123  * the set of RT indexes for its component baserels.  We create RelOptInfo
124  * nodes for each baserel and joinrel, and store them in the PlannerInfo's
125  * base_rel_array and join_rel_list respectively.
126  *
127  * Note that there is only one joinrel for any given set of component
128  * baserels, no matter what order we assemble them in; so an unordered
129  * set is the right datatype to identify it with.
130  *
131  * We also have "other rels", which are like base rels in that they refer to
132  * single RT indexes; but they are not part of the join tree, and are given
133  * a different RelOptKind to identify them.
134  *
135  * Currently the only kind of otherrels are those made for child relations
136  * of an inheritance scan (SELECT FROM foo*).  The parent table's RTE and
137  * corresponding baserel represent the whole result of the inheritance scan.
138  * The planner creates separate RTEs and associated RelOptInfos for each child
139  * table (including the parent table, in its capacity as a member of the
140  * inheritance set).  These RelOptInfos are physically identical to baserels,
141  * but are otherrels because they are not in the main join tree.  These added
142  * RTEs and otherrels are used to plan the scans of the individual tables in
143  * the inheritance set; then the parent baserel is given an Append plan
144  * comprising the best plans for the individual child tables.
145  *
146  * At one time we also made otherrels to represent join RTEs, for use in
147  * handling join alias Vars.  Currently this is not needed because all join
148  * alias Vars are expanded to non-aliased form during preprocess_expression.
149  *
150  * Parts of this data structure are specific to various scan and join
151  * mechanisms.  It didn't seem worth creating new node types for them.
152  *
153  *              relids - Set of base-relation identifiers; it is a base relation
154  *                              if there is just one, a join relation if more than one
155  *              rows - estimated number of tuples in the relation after restriction
156  *                         clauses have been applied (ie, output rows of a plan for it)
157  *              width - avg. number of bytes per tuple in the relation after the
158  *                              appropriate projections have been done (ie, output width)
159  *              reltargetlist - List of Var nodes for the attributes we need to
160  *                                              output from this relation (in no particular order)
161  *                                              NOTE: in a child relation, may contain RowExprs
162  *              pathlist - List of Path nodes, one for each potentially useful
163  *                                 method of generating the relation
164  *              cheapest_startup_path - the pathlist member with lowest startup cost
165  *                                                              (regardless of its ordering)
166  *              cheapest_total_path - the pathlist member with lowest total cost
167  *                                                        (regardless of its ordering)
168  *              cheapest_unique_path - for caching cheapest path to produce unique
169  *                                                         (no duplicates) output from relation
170  *
171  * If the relation is a base relation it will have these fields set:
172  *
173  *              relid - RTE index (this is redundant with the relids field, but
174  *                              is provided for convenience of access)
175  *              rtekind - distinguishes plain relation, subquery, or function RTE
176  *              min_attr, max_attr - range of valid AttrNumbers for rel
177  *              attr_needed - array of bitmapsets indicating the highest joinrel
178  *                              in which each attribute is needed; if bit 0 is set then
179  *                              the attribute is needed as part of final targetlist
180  *              attr_widths - cache space for per-attribute width estimates;
181  *                                        zero means not computed yet
182  *              indexlist - list of IndexOptInfo nodes for relation's indexes
183  *                                      (always NIL if it's not a table)
184  *              pages - number of disk pages in relation (zero if not a table)
185  *              tuples - number of tuples in relation (not considering restrictions)
186  *              subplan - plan for subquery (NULL if it's not a subquery)
187  *
188  *              Note: for a subquery, tuples and subplan are not set immediately
189  *              upon creation of the RelOptInfo object; they are filled in when
190  *              set_base_rel_pathlist processes the object.
191  *
192  *              For otherrels that are inheritance children, these fields are filled
193  *              in just as for a baserel.
194  *
195  * The presence of the remaining fields depends on the restrictions
196  * and joins that the relation participates in:
197  *
198  *              baserestrictinfo - List of RestrictInfo nodes, containing info about
199  *                                      each non-join qualification clause in which this relation
200  *                                      participates (only used for base rels)
201  *              baserestrictcost - Estimated cost of evaluating the baserestrictinfo
202  *                                      clauses at a single tuple (only used for base rels)
203  *              outerjoinset - For a base rel: if the rel appears within the nullable
204  *                                      side of an outer join, the set of all relids
205  *                                      participating in the highest such outer join; else NULL.
206  *                                      Otherwise, unused.
207  *              joininfo  - List of RestrictInfo nodes, containing info about each
208  *                                      join clause in which this relation participates
209  *              index_outer_relids - only used for base rels; set of outer relids
210  *                                      that participate in indexable joinclauses for this rel
211  *              index_inner_paths - only used for base rels; list of InnerIndexscanInfo
212  *                                      nodes showing best indexpaths for various subsets of
213  *                                      index_outer_relids.
214  *
215  * Note: Keeping a restrictinfo list in the RelOptInfo is useful only for
216  * base rels, because for a join rel the set of clauses that are treated as
217  * restrict clauses varies depending on which sub-relations we choose to join.
218  * (For example, in a 3-base-rel join, a clause relating rels 1 and 2 must be
219  * treated as a restrictclause if we join {1} and {2 3} to make {1 2 3}; but
220  * if we join {1 2} and {3} then that clause will be a restrictclause in {1 2}
221  * and should not be processed again at the level of {1 2 3}.)  Therefore,
222  * the restrictinfo list in the join case appears in individual JoinPaths
223  * (field joinrestrictinfo), not in the parent relation.  But it's OK for
224  * the RelOptInfo to store the joininfo list, because that is the same
225  * for a given rel no matter how we form it.
226  *
227  * We store baserestrictcost in the RelOptInfo (for base relations) because
228  * we know we will need it at least once (to price the sequential scan)
229  * and may need it multiple times to price index scans.
230  *
231  * outerjoinset is used to ensure correct placement of WHERE clauses that
232  * apply to outer-joined relations; we must not apply such WHERE clauses
233  * until after the outer join is performed.
234  *----------
235  */
236 typedef enum RelOptKind
237 {
238         RELOPT_BASEREL,
239         RELOPT_JOINREL,
240         RELOPT_OTHER_CHILD_REL
241 } RelOptKind;
242
243 typedef struct RelOptInfo
244 {
245         NodeTag         type;
246
247         RelOptKind      reloptkind;
248
249         /* all relations included in this RelOptInfo */
250         Relids          relids;                 /* set of base relids (rangetable indexes) */
251
252         /* size estimates generated by planner */
253         double          rows;                   /* estimated number of result tuples */
254         int                     width;                  /* estimated avg width of result tuples */
255
256         /* materialization information */
257         List       *reltargetlist;      /* needed Vars */
258         List       *pathlist;           /* Path structures */
259         struct Path *cheapest_startup_path;
260         struct Path *cheapest_total_path;
261         struct Path *cheapest_unique_path;
262
263         /* information about a base rel (not set for join rels!) */
264         Index           relid;
265         RTEKind         rtekind;                /* RELATION, SUBQUERY, or FUNCTION */
266         AttrNumber      min_attr;               /* smallest attrno of rel (often <0) */
267         AttrNumber      max_attr;               /* largest attrno of rel */
268         Relids     *attr_needed;        /* array indexed [min_attr .. max_attr] */
269         int32      *attr_widths;        /* array indexed [min_attr .. max_attr] */
270         List       *indexlist;
271         BlockNumber     pages;
272         double          tuples;
273         struct Plan *subplan;           /* if subquery */
274
275         /* used by various scans and joins: */
276         List       *baserestrictinfo;           /* RestrictInfo structures (if
277                                                                                  * base rel) */
278         QualCost        baserestrictcost;               /* cost of evaluating the above */
279         Relids          outerjoinset;   /* set of base relids */
280         List       *joininfo;           /* RestrictInfo structures for join clauses
281                                                                  * involving this rel */
282
283         /* cached info about inner indexscan paths for relation: */
284         Relids          index_outer_relids;             /* other relids in indexable join
285                                                                                  * clauses */
286         List       *index_inner_paths;          /* InnerIndexscanInfo nodes */
287
288         /*
289          * Inner indexscans are not in the main pathlist because they are not
290          * usable except in specific join contexts.  We use the
291          * index_inner_paths list just to avoid recomputing the best inner
292          * indexscan repeatedly for similar outer relations.  See comments for
293          * InnerIndexscanInfo.
294          */
295 } RelOptInfo;
296
297 /*
298  * IndexOptInfo
299  *              Per-index information for planning/optimization
300  *
301  *              Prior to Postgres 7.0, RelOptInfo was used to describe both relations
302  *              and indexes, but that created confusion without actually doing anything
303  *              useful.  So now we have a separate IndexOptInfo struct for indexes.
304  *
305  *              classlist[], indexkeys[], and ordering[] have ncolumns entries.
306  *              Zeroes in the indexkeys[] array indicate index columns that are
307  *              expressions; there is one element in indexprs for each such column.
308  *
309  *              Note: for historical reasons, the classlist and ordering arrays have
310  *              an extra entry that is always zero.  Some code scans until it sees a
311  *              zero entry, rather than looking at ncolumns.
312  *
313  *              The indexprs and indpred expressions have been run through
314  *              prepqual.c and eval_const_expressions() for ease of matching to
315  *              WHERE clauses.  indpred is in implicit-AND form.
316  */
317
318 typedef struct IndexOptInfo
319 {
320         NodeTag         type;
321
322         Oid                     indexoid;               /* OID of the index relation */
323         RelOptInfo *rel;                        /* back-link to index's table */
324
325         /* statistics from pg_class */
326         BlockNumber     pages;                  /* number of disk pages in index */
327         double          tuples;                 /* number of index tuples in index */
328
329         /* index descriptor information */
330         int                     ncolumns;               /* number of columns in index */
331         Oid                *classlist;          /* OIDs of operator classes for columns */
332         int                *indexkeys;          /* column numbers of index's keys, or 0 */
333         Oid                *ordering;           /* OIDs of sort operators for each column */
334         Oid                     relam;                  /* OID of the access method (in pg_am) */
335
336         RegProcedure amcostestimate;    /* OID of the access method's cost fcn */
337
338         List       *indexprs;           /* expressions for non-simple index
339                                                                  * columns */
340         List       *indpred;            /* predicate if a partial index, else NIL */
341
342         bool            predOK;                 /* true if predicate matches query */
343         bool            unique;                 /* true if a unique index */
344         bool            amoptionalkey;  /* can query omit key for the first column? */
345 } IndexOptInfo;
346
347
348 /*
349  * PathKeys
350  *
351  *      The sort ordering of a path is represented by a list of sublists of
352  *      PathKeyItem nodes.      An empty list implies no known ordering.  Otherwise
353  *      the first sublist represents the primary sort key, the second the
354  *      first secondary sort key, etc.  Each sublist contains one or more
355  *      PathKeyItem nodes, each of which can be taken as the attribute that
356  *      appears at that sort position.  (See optimizer/README for more
357  *      information.)
358  */
359
360 typedef struct PathKeyItem
361 {
362         NodeTag         type;
363
364         Node       *key;                        /* the item that is ordered */
365         Oid                     sortop;                 /* the ordering operator ('<' op) */
366
367         /*
368          * key typically points to a Var node, ie a relation attribute, but it
369          * can also point to an arbitrary expression representing the value
370          * indexed by an index expression.
371          */
372 } PathKeyItem;
373
374 /*
375  * Type "Path" is used as-is for sequential-scan paths.  For other
376  * path types it is the first component of a larger struct.
377  *
378  * Note: "pathtype" is the NodeTag of the Plan node we could build from this
379  * Path.  It is partially redundant with the Path's NodeTag, but allows us
380  * to use the same Path type for multiple Plan types where there is no need
381  * to distinguish the Plan type during path processing.
382  */
383
384 typedef struct Path
385 {
386         NodeTag         type;
387
388         NodeTag         pathtype;               /* tag identifying scan/join method */
389
390         RelOptInfo *parent;                     /* the relation this path can build */
391
392         /* estimated execution costs for path (see costsize.c for more info) */
393         Cost            startup_cost;   /* cost expended before fetching any
394                                                                  * tuples */
395         Cost            total_cost;             /* total cost (assuming all tuples
396                                                                  * fetched) */
397
398         List       *pathkeys;           /* sort ordering of path's output */
399         /* pathkeys is a List of Lists of PathKeyItem nodes; see above */
400 } Path;
401
402 /*----------
403  * IndexPath represents an index scan over a single index.
404  *
405  * 'indexinfo' is the index to be scanned.
406  *
407  * 'indexclauses' is a list of index qualification clauses, with implicit
408  * AND semantics across the list.  Each clause is a RestrictInfo node from
409  * the query's WHERE or JOIN conditions.
410  *
411  * 'indexquals' has the same structure as 'indexclauses', but it contains
412  * the actual indexqual conditions that can be used with the index.
413  * In simple cases this is identical to 'indexclauses', but when special
414  * indexable operators appear in 'indexclauses', they are replaced by the
415  * derived indexscannable conditions in 'indexquals'.
416  *
417  * 'isjoininner' is TRUE if the path is a nestloop inner scan (that is,
418  * some of the index conditions are join rather than restriction clauses).
419  *
420  * 'indexscandir' is one of:
421  *              ForwardScanDirection: forward scan of an ordered index
422  *              BackwardScanDirection: backward scan of an ordered index
423  *              NoMovementScanDirection: scan of an unordered index, or don't care
424  * (The executor doesn't care whether it gets ForwardScanDirection or
425  * NoMovementScanDirection for an indexscan, but the planner wants to
426  * distinguish ordered from unordered indexes for building pathkeys.)
427  *
428  * 'indextotalcost' and 'indexselectivity' are saved in the IndexPath so that
429  * we need not recompute them when considering using the same index in a
430  * bitmap index/heap scan (see BitmapHeapPath).  The costs of the IndexPath
431  * itself represent the costs of an IndexScan plan type.
432  *
433  * 'rows' is the estimated result tuple count for the indexscan.  This
434  * is the same as path.parent->rows for a simple indexscan, but it is
435  * different for a nestloop inner scan, because the additional indexquals
436  * coming from join clauses make the scan more selective than the parent
437  * rel's restrict clauses alone would do.
438  *----------
439  */
440 typedef struct IndexPath
441 {
442         Path            path;
443         IndexOptInfo *indexinfo;
444         List       *indexclauses;
445         List       *indexquals;
446         bool            isjoininner;
447         ScanDirection indexscandir;
448         Cost            indextotalcost;
449         Selectivity indexselectivity;
450         double          rows;                   /* estimated number of result tuples */
451 } IndexPath;
452
453 /*
454  * BitmapHeapPath represents one or more indexscans that generate TID bitmaps
455  * instead of directly accessing the heap, followed by AND/OR combinations
456  * to produce a single bitmap, followed by a heap scan that uses the bitmap.
457  * Note that the output is always considered unordered, since it will come
458  * out in physical heap order no matter what the underlying indexes did.
459  *
460  * The individual indexscans are represented by IndexPath nodes, and any
461  * logic on top of them is represented by a tree of BitmapAndPath and
462  * BitmapOrPath nodes.  Notice that we can use the same IndexPath node both
463  * to represent a regular IndexScan plan, and as the child of a BitmapHeapPath
464  * that represents scanning the same index using a BitmapIndexScan.  The
465  * startup_cost and total_cost figures of an IndexPath always represent the
466  * costs to use it as a regular IndexScan.  The costs of a BitmapIndexScan
467  * can be computed using the IndexPath's indextotalcost and indexselectivity.
468  *
469  * BitmapHeapPaths can be nestloop inner indexscans.  The isjoininner and
470  * rows fields serve the same purpose as for plain IndexPaths.
471  */
472 typedef struct BitmapHeapPath
473 {
474         Path            path;
475         Path       *bitmapqual;         /* IndexPath, BitmapAndPath, BitmapOrPath */
476         bool            isjoininner;    /* T if it's a nestloop inner scan */
477         double          rows;                   /* estimated number of result tuples */
478 } BitmapHeapPath;
479
480 /*
481  * BitmapAndPath represents a BitmapAnd plan node; it can only appear as
482  * part of the substructure of a BitmapHeapPath.  The Path structure is
483  * a bit more heavyweight than we really need for this, but for simplicity
484  * we make it a derivative of Path anyway.
485  */
486 typedef struct BitmapAndPath
487 {
488         Path            path;
489         List       *bitmapquals;                /* IndexPaths and BitmapOrPaths */
490         Selectivity bitmapselectivity;
491 } BitmapAndPath;
492
493 /*
494  * BitmapOrPath represents a BitmapOr plan node; it can only appear as
495  * part of the substructure of a BitmapHeapPath.  The Path structure is
496  * a bit more heavyweight than we really need for this, but for simplicity
497  * we make it a derivative of Path anyway.
498  */
499 typedef struct BitmapOrPath
500 {
501         Path            path;
502         List       *bitmapquals;                /* IndexPaths and BitmapAndPaths */
503         Selectivity bitmapselectivity;
504 } BitmapOrPath;
505
506 /*
507  * TidPath represents a scan by TID
508  *
509  * tideval is an implicitly OR'ed list of quals of the form CTID = something.
510  * Note they are bare quals, not RestrictInfos.
511  */
512 typedef struct TidPath
513 {
514         Path            path;
515         List       *tideval;            /* qual(s) involving CTID = something */
516 } TidPath;
517
518 /*
519  * AppendPath represents an Append plan, ie, successive execution of
520  * several member plans.  Currently it is only used to handle expansion
521  * of inheritance trees.
522  *
523  * Note: it is possible for "subpaths" to contain only one, or even no,
524  * elements.  These cases are optimized during create_append_plan.
525  */
526 typedef struct AppendPath
527 {
528         Path            path;
529         List       *subpaths;           /* list of component Paths */
530 } AppendPath;
531
532 /*
533  * ResultPath represents use of a Result plan node.  There are several
534  * applications for this:
535  *      * To compute a variable-free targetlist (a "SELECT expressions" query).
536  *        In this case subpath and path.parent will both be NULL.  constantqual
537  *        might or might not be empty ("SELECT expressions WHERE something").
538  *      * To gate execution of a subplan with a one-time (variable-free) qual
539  *        condition.  path.parent is copied from the subpath.
540  *      * To substitute for a scan plan when we have proven that no rows in
541  *        a table will satisfy the query.  subpath is NULL but path.parent
542  *        references the not-to-be-scanned relation, and constantqual is
543  *        a constant FALSE.
544  *
545  * Note that constantqual is a list of bare clauses, not RestrictInfos.
546  */
547 typedef struct ResultPath
548 {
549         Path            path;
550         Path       *subpath;
551         List       *constantqual;
552 } ResultPath;
553
554 /*
555  * MaterialPath represents use of a Material plan node, i.e., caching of
556  * the output of its subpath.  This is used when the subpath is expensive
557  * and needs to be scanned repeatedly, or when we need mark/restore ability
558  * and the subpath doesn't have it.
559  */
560 typedef struct MaterialPath
561 {
562         Path            path;
563         Path       *subpath;
564 } MaterialPath;
565
566 /*
567  * UniquePath represents elimination of distinct rows from the output of
568  * its subpath.
569  *
570  * This is unlike the other Path nodes in that it can actually generate
571  * different plans: either hash-based or sort-based implementation, or a
572  * no-op if the input path can be proven distinct already.      The decision
573  * is sufficiently localized that it's not worth having separate Path node
574  * types.  (Note: in the no-op case, we could eliminate the UniquePath node
575  * entirely and just return the subpath; but it's convenient to have a
576  * UniquePath in the path tree to signal upper-level routines that the input
577  * is known distinct.)
578  */
579 typedef enum
580 {
581         UNIQUE_PATH_NOOP,                       /* input is known unique already */
582         UNIQUE_PATH_HASH,                       /* use hashing */
583         UNIQUE_PATH_SORT                        /* use sorting */
584 } UniquePathMethod;
585
586 typedef struct UniquePath
587 {
588         Path            path;
589         Path       *subpath;
590         UniquePathMethod umethod;
591         double          rows;                   /* estimated number of result tuples */
592 } UniquePath;
593
594 /*
595  * All join-type paths share these fields.
596  */
597
598 typedef struct JoinPath
599 {
600         Path            path;
601
602         JoinType        jointype;
603
604         Path       *outerjoinpath;      /* path for the outer side of the join */
605         Path       *innerjoinpath;      /* path for the inner side of the join */
606
607         List       *joinrestrictinfo;           /* RestrictInfos to apply to join */
608
609         /*
610          * See the notes for RelOptInfo to understand why joinrestrictinfo is
611          * needed in JoinPath, and can't be merged into the parent RelOptInfo.
612          */
613 } JoinPath;
614
615 /*
616  * A nested-loop path needs no special fields.
617  */
618
619 typedef JoinPath NestPath;
620
621 /*
622  * A mergejoin path has these fields.
623  *
624  * path_mergeclauses lists the clauses (in the form of RestrictInfos)
625  * that will be used in the merge.
626  *
627  * Note that the mergeclauses are a subset of the parent relation's
628  * restriction-clause list.  Any join clauses that are not mergejoinable
629  * appear only in the parent's restrict list, and must be checked by a
630  * qpqual at execution time.
631  *
632  * outersortkeys (resp. innersortkeys) is NIL if the outer path
633  * (resp. inner path) is already ordered appropriately for the
634  * mergejoin.  If it is not NIL then it is a PathKeys list describing
635  * the ordering that must be created by an explicit sort step.
636  */
637
638 typedef struct MergePath
639 {
640         JoinPath        jpath;
641         List       *path_mergeclauses;          /* join clauses to be used for
642                                                                                  * merge */
643         List       *outersortkeys;      /* keys for explicit sort, if any */
644         List       *innersortkeys;      /* keys for explicit sort, if any */
645 } MergePath;
646
647 /*
648  * A hashjoin path has these fields.
649  *
650  * The remarks above for mergeclauses apply for hashclauses as well.
651  *
652  * Hashjoin does not care what order its inputs appear in, so we have
653  * no need for sortkeys.
654  */
655
656 typedef struct HashPath
657 {
658         JoinPath        jpath;
659         List       *path_hashclauses;           /* join clauses used for hashing */
660 } HashPath;
661
662 /*
663  * Restriction clause info.
664  *
665  * We create one of these for each AND sub-clause of a restriction condition
666  * (WHERE or JOIN/ON clause).  Since the restriction clauses are logically
667  * ANDed, we can use any one of them or any subset of them to filter out
668  * tuples, without having to evaluate the rest.  The RestrictInfo node itself
669  * stores data used by the optimizer while choosing the best query plan.
670  *
671  * If a restriction clause references a single base relation, it will appear
672  * in the baserestrictinfo list of the RelOptInfo for that base rel.
673  *
674  * If a restriction clause references more than one base rel, it will
675  * appear in the joininfo list of every RelOptInfo that describes a strict
676  * subset of the base rels mentioned in the clause.  The joininfo lists are
677  * used to drive join tree building by selecting plausible join candidates.
678  * The clause cannot actually be applied until we have built a join rel
679  * containing all the base rels it references, however.
680  *
681  * When we construct a join rel that includes all the base rels referenced
682  * in a multi-relation restriction clause, we place that clause into the
683  * joinrestrictinfo lists of paths for the join rel, if neither left nor
684  * right sub-path includes all base rels referenced in the clause.      The clause
685  * will be applied at that join level, and will not propagate any further up
686  * the join tree.  (Note: the "predicate migration" code was once intended to
687  * push restriction clauses up and down the plan tree based on evaluation
688  * costs, but it's dead code and is unlikely to be resurrected in the
689  * foreseeable future.)
690  *
691  * Note that in the presence of more than two rels, a multi-rel restriction
692  * might reach different heights in the join tree depending on the join
693  * sequence we use.  So, these clauses cannot be associated directly with
694  * the join RelOptInfo, but must be kept track of on a per-join-path basis.
695  *
696  * When dealing with outer joins we have to be very careful about pushing qual
697  * clauses up and down the tree.  An outer join's own JOIN/ON conditions must
698  * be evaluated exactly at that join node, and any quals appearing in WHERE or
699  * in a JOIN above the outer join cannot be pushed down below the outer join.
700  * Otherwise the outer join will produce wrong results because it will see the
701  * wrong sets of input rows.  All quals are stored as RestrictInfo nodes
702  * during planning, but there's a flag to indicate whether a qual has been
703  * pushed down to a lower level than its original syntactic placement in the
704  * join tree would suggest.  If an outer join prevents us from pushing a qual
705  * down to its "natural" semantic level (the level associated with just the
706  * base rels used in the qual) then we mark the qual with a "required_relids"
707  * value including more than just the base rels it actually uses.  By
708  * pretending that the qual references all the rels appearing in the outer
709  * join, we prevent it from being evaluated below the outer join's joinrel.
710  * When we do form the outer join's joinrel, we still need to distinguish
711  * those quals that are actually in that join's JOIN/ON condition from those
712  * that appeared higher in the tree and were pushed down to the join rel
713  * because they used no other rels.  That's what the is_pushed_down flag is
714  * for; it tells us that a qual came from a point above the join of the
715  * set of base rels listed in required_relids.  A clause that originally came
716  * from WHERE will *always* have its is_pushed_down flag set; a clause that
717  * came from an INNER JOIN condition, but doesn't use all the rels being
718  * joined, will also have is_pushed_down set because it will get attached to
719  * some lower joinrel.
720  *
721  * In general, the referenced clause might be arbitrarily complex.      The
722  * kinds of clauses we can handle as indexscan quals, mergejoin clauses,
723  * or hashjoin clauses are fairly limited --- the code for each kind of
724  * path is responsible for identifying the restrict clauses it can use
725  * and ignoring the rest.  Clauses not implemented by an indexscan,
726  * mergejoin, or hashjoin will be placed in the plan qual or joinqual field
727  * of the finished Plan node, where they will be enforced by general-purpose
728  * qual-expression-evaluation code.  (But we are still entitled to count
729  * their selectivity when estimating the result tuple count, if we
730  * can guess what it is...)
731  *
732  * When the referenced clause is an OR clause, we generate a modified copy
733  * in which additional RestrictInfo nodes are inserted below the top-level
734  * OR/AND structure.  This is a convenience for OR indexscan processing:
735  * indexquals taken from either the top level or an OR subclause will have
736  * associated RestrictInfo nodes.
737  */
738
739 typedef struct RestrictInfo
740 {
741         NodeTag         type;
742
743         Expr       *clause;                     /* the represented clause of WHERE or JOIN */
744
745         bool            is_pushed_down; /* TRUE if clause was pushed down in level */
746
747         /*
748          * This flag is set true if the clause looks potentially useful as a
749          * merge or hash join clause, that is if it is a binary opclause with
750          * nonoverlapping sets of relids referenced in the left and right
751          * sides. (Whether the operator is actually merge or hash joinable
752          * isn't checked, however.)
753          */
754         bool            can_join;
755
756         /* The set of relids (varnos) actually referenced in the clause: */
757         Relids          clause_relids;
758
759         /* The set of relids required to evaluate the clause: */
760         Relids          required_relids;
761
762         /* These fields are set for any binary opclause: */
763         Relids          left_relids;    /* relids in left side of clause */
764         Relids          right_relids;   /* relids in right side of clause */
765
766         /* This field is NULL unless clause is an OR clause: */
767         Expr       *orclause;           /* modified clause with RestrictInfos */
768
769         /* cache space for cost and selectivity */
770         QualCost        eval_cost;              /* eval cost of clause; -1 if not yet set */
771         Selectivity this_selec;         /* selectivity; -1 if not yet set */
772
773         /* valid if clause is mergejoinable, else InvalidOid: */
774         Oid                     mergejoinoperator;              /* copy of clause operator */
775         Oid                     left_sortop;    /* leftside sortop needed for mergejoin */
776         Oid                     right_sortop;   /* rightside sortop needed for mergejoin */
777
778         /* cache space for mergeclause processing; NIL if not yet set */
779         List       *left_pathkey;       /* canonical pathkey for left side */
780         List       *right_pathkey;      /* canonical pathkey for right side */
781
782         /* cache space for mergeclause processing; -1 if not yet set */
783         Selectivity left_mergescansel;          /* fraction of left side to scan */
784         Selectivity right_mergescansel;         /* fraction of right side to scan */
785
786         /* valid if clause is hashjoinable, else InvalidOid: */
787         Oid                     hashjoinoperator;               /* copy of clause operator */
788
789         /* cache space for hashclause processing; -1 if not yet set */
790         Selectivity left_bucketsize;    /* avg bucketsize of left side */
791         Selectivity right_bucketsize;           /* avg bucketsize of right side */
792 } RestrictInfo;
793
794 /*
795  * Inner indexscan info.
796  *
797  * An inner indexscan is one that uses one or more joinclauses as index
798  * conditions (perhaps in addition to plain restriction clauses).  So it
799  * can only be used as the inner path of a nestloop join where the outer
800  * relation includes all other relids appearing in those joinclauses.
801  * The set of usable joinclauses, and thus the best inner indexscan,
802  * thus varies depending on which outer relation we consider; so we have
803  * to recompute the best such path for every join.      To avoid lots of
804  * redundant computation, we cache the results of such searches.  For
805  * each relation we compute the set of possible otherrelids (all relids
806  * appearing in joinquals that could become indexquals for this table).
807  * Two outer relations whose relids have the same intersection with this
808  * set will have the same set of available joinclauses and thus the same
809  * best inner indexscan for the inner relation.  By taking the intersection
810  * before scanning the cache, we avoid recomputing when considering
811  * join rels that differ only by the inclusion of irrelevant other rels.
812  *
813  * The search key also includes a bool showing whether the join being
814  * considered is an outer join.  Since we constrain the join order for
815  * outer joins, I believe that this bool can only have one possible value
816  * for any particular base relation; but store it anyway to avoid confusion.
817  */
818
819 typedef struct InnerIndexscanInfo
820 {
821         NodeTag         type;
822         /* The lookup key: */
823         Relids          other_relids;   /* a set of relevant other relids */
824         bool            isouterjoin;    /* true if join is outer */
825         /* Best path for this lookup key: */
826         Path       *best_innerpath; /* best inner indexscan, or NULL if none */
827 } InnerIndexscanInfo;
828
829 /*
830  * IN clause info.
831  *
832  * When we convert top-level IN quals into join operations, we must restrict
833  * the order of joining and use special join methods at some join points.
834  * We record information about each such IN clause in an InClauseInfo struct.
835  * These structs are kept in the PlannerInfo node's in_info_list.
836  */
837
838 typedef struct InClauseInfo
839 {
840         NodeTag         type;
841         Relids          lefthand;               /* base relids in lefthand expressions */
842         Relids          righthand;              /* base relids coming from the subselect */
843         List       *sub_targetlist; /* targetlist of original RHS subquery */
844
845         /*
846          * Note: sub_targetlist is just a list of Vars or expressions; it does
847          * not contain TargetEntry nodes.
848          */
849 } InClauseInfo;
850
851 #endif   /* RELATION_H */