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