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