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