]> granicus.if.org Git - postgresql/blob - src/include/nodes/execnodes.h
Another pgindent run with updated typedefs.
[postgresql] / src / include / nodes / execnodes.h
1 /*-------------------------------------------------------------------------
2  *
3  * execnodes.h
4  *        definitions for executor state nodes
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  * $Id: execnodes.h,v 1.103 2003/08/08 21:42:47 momjian Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef EXECNODES_H
15 #define EXECNODES_H
16
17 #include "access/relscan.h"
18 #include "executor/hashjoin.h"
19 #include "executor/tuptable.h"
20 #include "fmgr.h"
21 #include "nodes/bitmapset.h"
22 #include "nodes/params.h"
23 #include "nodes/plannodes.h"
24 #include "utils/tuplestore.h"
25
26
27 /* ----------------
28  *        IndexInfo information
29  *
30  *              this struct holds the information needed to construct new index
31  *              entries for a particular index.  Used for both index_build and
32  *              retail creation of index entries.
33  *
34  *              NumIndexAttrs           number of columns in this index
35  *              KeyAttrNumbers          underlying-rel attribute numbers used as keys
36  *                                                      (zeroes indicate expressions)
37  *              Expressions                     expr trees for expression entries, or NIL if none
38  *              ExpressionsState        exec state for expressions, or NIL if none
39  *              Predicate                       partial-index predicate, or NIL if none
40  *              PredicateState          exec state for predicate, or NIL if none
41  *              Unique                          is it a unique index?
42  * ----------------
43  */
44 typedef struct IndexInfo
45 {
46         NodeTag         type;
47         int                     ii_NumIndexAttrs;
48         AttrNumber      ii_KeyAttrNumbers[INDEX_MAX_KEYS];
49         List       *ii_Expressions; /* list of Expr */
50         List       *ii_ExpressionsState;        /* list of ExprState */
51         List       *ii_Predicate;       /* list of Expr */
52         List       *ii_PredicateState;          /* list of ExprState */
53         bool            ii_Unique;
54 } IndexInfo;
55
56 /* ----------------
57  *        ExprContext_CB
58  *
59  *              List of callbacks to be called at ExprContext shutdown.
60  * ----------------
61  */
62 typedef void (*ExprContextCallbackFunction) (Datum arg);
63
64 typedef struct ExprContext_CB
65 {
66         struct ExprContext_CB *next;
67         ExprContextCallbackFunction function;
68         Datum           arg;
69 } ExprContext_CB;
70
71 /* ----------------
72  *        ExprContext
73  *
74  *              This class holds the "current context" information
75  *              needed to evaluate expressions for doing tuple qualifications
76  *              and tuple projections.  For example, if an expression refers
77  *              to an attribute in the current inner tuple then we need to know
78  *              what the current inner tuple is and so we look at the expression
79  *              context.
80  *
81  *      There are two memory contexts associated with an ExprContext:
82  *      * ecxt_per_query_memory is a query-lifespan context, typically the same
83  *        context the ExprContext node itself is allocated in.  This context
84  *        can be used for purposes such as storing function call cache info.
85  *      * ecxt_per_tuple_memory is a short-term context for expression results.
86  *        As the name suggests, it will typically be reset once per tuple,
87  *        before we begin to evaluate expressions for that tuple.  Each
88  *        ExprContext normally has its very own per-tuple memory context.
89  *
90  *      CurrentMemoryContext should be set to ecxt_per_tuple_memory before
91  *      calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
92  * ----------------
93  */
94 typedef struct ExprContext
95 {
96         NodeTag         type;
97
98         /* Tuples that Var nodes in expression may refer to */
99         TupleTableSlot *ecxt_scantuple;
100         TupleTableSlot *ecxt_innertuple;
101         TupleTableSlot *ecxt_outertuple;
102
103         /* Memory contexts for expression evaluation --- see notes above */
104         MemoryContext ecxt_per_query_memory;
105         MemoryContext ecxt_per_tuple_memory;
106
107         /* Values to substitute for Param nodes in expression */
108         ParamExecData *ecxt_param_exec_vals;            /* for PARAM_EXEC params */
109         ParamListInfo ecxt_param_list_info; /* for other param types */
110
111         /* Values to substitute for Aggref nodes in expression */
112         Datum      *ecxt_aggvalues; /* precomputed values for Aggref nodes */
113         bool       *ecxt_aggnulls;      /* null flags for Aggref nodes */
114
115         /* Value to substitute for CoerceToDomainValue nodes in expression */
116         Datum           domainValue_datum;
117         bool            domainValue_isNull;
118
119         /* Link to containing EState */
120         struct EState *ecxt_estate;
121
122         /* Functions to call back when ExprContext is shut down */
123         ExprContext_CB *ecxt_callbacks;
124 } ExprContext;
125
126 /*
127  * Set-result status returned by ExecEvalExpr()
128  */
129 typedef enum
130 {
131         ExprSingleResult,                       /* expression does not return a set */
132         ExprMultipleResult,                     /* this result is an element of a set */
133         ExprEndResult                           /* there are no more elements in the set */
134 } ExprDoneCond;
135
136 /*
137  * Return modes for functions returning sets.  Note values must be chosen
138  * as separate bits so that a bitmask can be formed to indicate supported
139  * modes.
140  */
141 typedef enum
142 {
143         SFRM_ValuePerCall = 0x01,       /* one value returned per call */
144         SFRM_Materialize = 0x02         /* result set instantiated in Tuplestore */
145 } SetFunctionReturnMode;
146
147 /*
148  * When calling a function that might return a set (multiple rows),
149  * a node of this type is passed as fcinfo->resultinfo to allow
150  * return status to be passed back.  A function returning set should
151  * raise an error if no such resultinfo is provided.
152  */
153 typedef struct ReturnSetInfo
154 {
155         NodeTag         type;
156         /* values set by caller: */
157         ExprContext *econtext;          /* context function is being called in */
158         TupleDesc       expectedDesc;   /* tuple descriptor expected by caller */
159         int                     allowedModes;   /* bitmask: return modes caller can handle */
160         /* result status from function (but pre-initialized by caller): */
161         SetFunctionReturnMode returnMode;       /* actual return mode */
162         ExprDoneCond isDone;            /* status for ValuePerCall mode */
163         /* fields filled by function in Materialize return mode: */
164         Tuplestorestate *setResult; /* holds the complete returned tuple set */
165         TupleDesc       setDesc;                /* actual descriptor for returned tuples */
166 } ReturnSetInfo;
167
168 /* ----------------
169  *              ProjectionInfo node information
170  *
171  *              This is all the information needed to perform projections ---
172  *              that is, form new tuples by evaluation of targetlist expressions.
173  *              Nodes which need to do projections create one of these.
174  *              In theory, when a node wants to perform a projection
175  *              it should just update this information as necessary and then
176  *              call ExecProject().  -cim 6/3/91
177  *
178  *              ExecProject() evaluates the tlist, forms a tuple, and stores it
179  *              in the given slot.      As a side-effect, the actual datum values and
180  *              null indicators are placed in the work arrays tupValues/tupNulls.
181  *
182  *              targetlist              target list for projection
183  *              exprContext             expression context in which to evaluate targetlist
184  *              slot                    slot to place projection result in
185  *              tupValues               array of computed values
186  *              tupNull                 array of null indicators
187  *              itemIsDone              workspace for ExecProject
188  * ----------------
189  */
190 typedef struct ProjectionInfo
191 {
192         NodeTag         type;
193         List       *pi_targetlist;
194         ExprContext *pi_exprContext;
195         TupleTableSlot *pi_slot;
196         Datum      *pi_tupValues;
197         char       *pi_tupNulls;
198         ExprDoneCond *pi_itemIsDone;
199 } ProjectionInfo;
200
201 /* ----------------
202  *        JunkFilter
203  *
204  *        This class is used to store information regarding junk attributes.
205  *        A junk attribute is an attribute in a tuple that is needed only for
206  *        storing intermediate information in the executor, and does not belong
207  *        in emitted tuples.    For example, when we do an UPDATE query,
208  *        the planner adds a "junk" entry to the targetlist so that the tuples
209  *        returned to ExecutePlan() contain an extra attribute: the ctid of
210  *        the tuple to be updated.      This is needed to do the update, but we
211  *        don't want the ctid to be part of the stored new tuple!  So, we
212  *        apply a "junk filter" to remove the junk attributes and form the
213  *        real output tuple.
214  *
215  *        targetList:           the original target list (including junk attributes).
216  *        length:                       the length of 'targetList'.
217  *        tupType:                      the tuple descriptor for the "original" tuple
218  *                                              (including the junk attributes).
219  *        cleanTargetList:      the "clean" target list (junk attributes removed).
220  *        cleanLength:          the length of 'cleanTargetList'
221  *        cleanTupType:         the tuple descriptor of the "clean" tuple (with
222  *                                              junk attributes removed).
223  *        cleanMap:                     A map with the correspondence between the non-junk
224  *                                              attribute numbers of the "original" tuple and the
225  *                                              attribute numbers of the "clean" tuple.
226  *        resultSlot:           tuple slot that can be used to hold cleaned tuple.
227  * ----------------
228  */
229 typedef struct JunkFilter
230 {
231         NodeTag         type;
232         List       *jf_targetList;
233         int                     jf_length;
234         TupleDesc       jf_tupType;
235         List       *jf_cleanTargetList;
236         int                     jf_cleanLength;
237         TupleDesc       jf_cleanTupType;
238         AttrNumber *jf_cleanMap;
239         TupleTableSlot *jf_resultSlot;
240 } JunkFilter;
241
242 /* ----------------
243  *        ResultRelInfo information
244  *
245  *              Whenever we update an existing relation, we have to
246  *              update indices on the relation, and perhaps also fire triggers.
247  *              The ResultRelInfo class is used to hold all the information needed
248  *              about a result relation, including indices.. -cim 10/15/89
249  *
250  *              RangeTableIndex                 result relation's range table index
251  *              RelationDesc                    relation descriptor for result relation
252  *              NumIndices                              # of indices existing on result relation
253  *              IndexRelationDescs              array of relation descriptors for indices
254  *              IndexRelationInfo               array of key/attr info for indices
255  *              TrigDesc                                triggers to be fired, if any
256  *              TrigFunctions                   cached lookup info for trigger functions
257  *              ConstraintExprs                 array of constraint-checking expr states
258  *              junkFilter                              for removing junk attributes from tuples
259  * ----------------
260  */
261 typedef struct ResultRelInfo
262 {
263         NodeTag         type;
264         Index           ri_RangeTableIndex;
265         Relation        ri_RelationDesc;
266         int                     ri_NumIndices;
267         RelationPtr ri_IndexRelationDescs;
268         IndexInfo **ri_IndexRelationInfo;
269         TriggerDesc *ri_TrigDesc;
270         FmgrInfo   *ri_TrigFunctions;
271         List      **ri_ConstraintExprs;
272         JunkFilter *ri_junkFilter;
273 } ResultRelInfo;
274
275 /* ----------------
276  *        EState information
277  *
278  * Master working state for an Executor invocation
279  * ----------------
280  */
281 typedef struct EState
282 {
283         NodeTag         type;
284
285         /* Basic state for all query types: */
286         ScanDirection es_direction; /* current scan direction */
287         Snapshot        es_snapshot;    /* time qual to use */
288         List       *es_range_table; /* List of RangeTableEntrys */
289
290         /* Info about target table for insert/update/delete queries: */
291         ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
292         int                     es_num_result_relations;                /* length of array */
293         ResultRelInfo *es_result_relation_info;         /* currently active array
294                                                                                                  * elt */
295         JunkFilter *es_junkFilter;      /* currently active junk filter */
296         Relation        es_into_relation_descriptor;    /* for SELECT INTO */
297
298         /* Parameter info: */
299         ParamListInfo es_param_list_info;       /* values of external params */
300         ParamExecData *es_param_exec_vals;      /* values of internal params */
301
302         /* Other working state: */
303         MemoryContext es_query_cxt; /* per-query context in which EState lives */
304
305         TupleTable      es_tupleTable;  /* Array of TupleTableSlots */
306
307         uint32          es_processed;   /* # of tuples processed */
308         Oid                     es_lastoid;             /* last oid processed (by INSERT) */
309         List       *es_rowMark;         /* not good place, but there is no other */
310
311         bool            es_instrument;  /* true requests runtime instrumentation */
312         bool            es_force_oids;  /* true forces result tuples to have
313                                                                  * (space for) OIDs --- used for SELECT
314                                                                  * INTO */
315
316         List       *es_exprcontexts;    /* List of ExprContexts within EState */
317
318         /*
319          * this ExprContext is for per-output-tuple operations, such as
320          * constraint checks and index-value computations.      It will be reset
321          * for each output tuple.  Note that it will be created only if
322          * needed.
323          */
324         ExprContext *es_per_tuple_exprcontext;
325
326         /* Below is to re-evaluate plan qual in READ COMMITTED mode */
327         Plan       *es_topPlan;         /* link to top of plan tree */
328         struct evalPlanQual *es_evalPlanQual;           /* chain of PlanQual
329                                                                                                  * states */
330         bool       *es_evTupleNull; /* local array of EPQ status */
331         HeapTuple  *es_evTuple;         /* shared array of EPQ substitute tuples */
332         bool            es_useEvalPlan; /* evaluating EPQ tuples? */
333 } EState;
334
335
336 /* ----------------------------------------------------------------
337  *                               Tuple Hash Tables
338  *
339  * All-in-memory tuple hash tables are used for a number of purposes.
340  * ----------------------------------------------------------------
341  */
342 typedef struct TupleHashEntryData *TupleHashEntry;
343 typedef struct TupleHashTableData *TupleHashTable;
344
345 typedef struct TupleHashEntryData
346 {
347         TupleHashEntry next;            /* next entry in same hash bucket */
348         uint32          hashkey;                /* exact hash key of this entry */
349         HeapTuple       firstTuple;             /* copy of first tuple in this group */
350         /* there may be additional data beyond the end of this struct */
351 } TupleHashEntryData;                   /* VARIABLE LENGTH STRUCT */
352
353 typedef struct TupleHashTableData
354 {
355         int                     numCols;                /* number of columns in lookup key */
356         AttrNumber *keyColIdx;          /* attr numbers of key columns */
357         FmgrInfo   *eqfunctions;        /* lookup data for comparison functions */
358         FmgrInfo   *hashfunctions;      /* lookup data for hash functions */
359         MemoryContext tablecxt;         /* memory context containing table */
360         MemoryContext tempcxt;          /* context for function evaluations */
361         Size            entrysize;              /* actual size to make each hash entry */
362         int                     nbuckets;               /* number of buckets in hash table */
363         TupleHashEntry buckets[1];      /* VARIABLE LENGTH ARRAY */
364 } TupleHashTableData;                   /* VARIABLE LENGTH STRUCT */
365
366 typedef struct
367 {
368         TupleHashEntry next_entry;      /* next entry in current chain */
369         int                     next_bucket;    /* next chain */
370 } TupleHashIterator;
371
372 #define ResetTupleHashIterator(iter) \
373         ((iter)->next_entry = NULL, \
374          (iter)->next_bucket = 0)
375
376
377 /* ----------------------------------------------------------------
378  *                               Expression State Trees
379  *
380  * Each executable expression tree has a parallel ExprState tree.
381  *
382  * Unlike PlanState, there is not an exact one-for-one correspondence between
383  * ExprState node types and Expr node types.  Many Expr node types have no
384  * need for node-type-specific run-time state, and so they can use plain
385  * ExprState or GenericExprState as their associated ExprState node type.
386  * ----------------------------------------------------------------
387  */
388
389 /* ----------------
390  *              ExprState node
391  *
392  * ExprState is the common superclass for all ExprState-type nodes.
393  *
394  * It can also be instantiated directly for leaf Expr nodes that need no
395  * local run-time state (such as Var, Const, or Param).
396  * ----------------
397  */
398 typedef struct ExprState
399 {
400         NodeTag         type;
401         Expr       *expr;                       /* associated Expr node */
402 } ExprState;
403
404 /* ----------------
405  *              GenericExprState node
406  *
407  * This is used for Expr node types that need no local run-time state,
408  * but have one child Expr node.
409  * ----------------
410  */
411 typedef struct GenericExprState
412 {
413         ExprState       xprstate;
414         ExprState  *arg;                        /* state of my child node */
415 } GenericExprState;
416
417 /* ----------------
418  *              AggrefExprState node
419  * ----------------
420  */
421 typedef struct AggrefExprState
422 {
423         ExprState       xprstate;
424         ExprState  *target;                     /* state of my child node */
425         int                     aggno;                  /* ID number for agg within its plan node */
426 } AggrefExprState;
427
428 /* ----------------
429  *              ArrayRefExprState node
430  *
431  * Note: array types can be fixed-length (typlen > 0), but only when the
432  * element type is itself fixed-length.  Otherwise they are varlena structures
433  * and have typlen = -1.  In any case, an array type is never pass-by-value.
434  * ----------------
435  */
436 typedef struct ArrayRefExprState
437 {
438         ExprState       xprstate;
439         List       *refupperindexpr;    /* states for child nodes */
440         List       *reflowerindexpr;
441         ExprState  *refexpr;
442         ExprState  *refassgnexpr;
443         int16           refattrlength;  /* typlen of array type */
444         int16           refelemlength;  /* typlen of the array element type */
445         bool            refelembyval;   /* is the element type pass-by-value? */
446         char            refelemalign;   /* typalign of the element type */
447 } ArrayRefExprState;
448
449 /* ----------------
450  *              FuncExprState node
451  *
452  * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
453  * and NullIf nodes; be careful to check what xprstate.expr is actually
454  * pointing at!
455  * ----------------
456  */
457 typedef struct FuncExprState
458 {
459         ExprState       xprstate;
460         List       *args;                       /* states of argument expressions */
461
462         /*
463          * Function manager's lookup info for the target function.  If
464          * func.fn_oid is InvalidOid, we haven't initialized it yet.
465          */
466         FmgrInfo        func;
467
468         /*
469          * We also need to store argument values across calls when evaluating
470          * a function-returning-set.
471          *
472          * setArgsValid is true when we are evaluating a set-valued function and
473          * we are in the middle of a call series; we want to pass the same
474          * argument values to the function again (and again, until it returns
475          * ExprEndResult).
476          */
477         bool            setArgsValid;
478
479         /*
480          * Flag to remember whether we found a set-valued argument to the
481          * function. This causes the function result to be a set as well.
482          * Valid only when setArgsValid is true.
483          */
484         bool            setHasSetArg;   /* some argument returns a set */
485
486         /*
487          * Current argument data for a set-valued function; contains valid
488          * data only if setArgsValid is true.
489          */
490         FunctionCallInfoData setArgs;
491 } FuncExprState;
492
493 /* ----------------
494  *              ScalarArrayOpExprState node
495  *
496  * This is a FuncExprState plus some additional data.
497  * ----------------
498  */
499 typedef struct ScalarArrayOpExprState
500 {
501         FuncExprState fxprstate;
502         /* Cached info about array element type */
503         Oid                     element_type;
504         int16           typlen;
505         bool            typbyval;
506         char            typalign;
507 } ScalarArrayOpExprState;
508
509 /* ----------------
510  *              BoolExprState node
511  * ----------------
512  */
513 typedef struct BoolExprState
514 {
515         ExprState       xprstate;
516         List       *args;                       /* states of argument expression(s) */
517 } BoolExprState;
518
519 /* ----------------
520  *              SubPlanState node
521  * ----------------
522  */
523 typedef struct SubPlanState
524 {
525         ExprState       xprstate;
526         EState     *sub_estate;         /* subselect plan has its own EState */
527         struct PlanState *planstate;    /* subselect plan's state tree */
528         List       *exprs;                      /* states of combining expression(s) */
529         List       *args;                       /* states of argument expression(s) */
530         bool            needShutdown;   /* TRUE = need to shutdown subplan */
531         HeapTuple       curTuple;               /* copy of most recent tuple from subplan */
532         /* these are used when hashing the subselect's output: */
533         ProjectionInfo *projLeft;       /* for projecting lefthand exprs */
534         ProjectionInfo *projRight;      /* for projecting subselect output */
535         TupleHashTable hashtable;       /* hash table for no-nulls subselect rows */
536         TupleHashTable hashnulls;       /* hash table for rows with null(s) */
537         bool            havehashrows;   /* TRUE if hashtable is not empty */
538         bool            havenullrows;   /* TRUE if hashnulls is not empty */
539         MemoryContext tablecxt;         /* memory context containing tables */
540         ExprContext *innerecontext; /* working context for comparisons */
541         AttrNumber *keyColIdx;          /* control data for hash tables */
542         FmgrInfo   *eqfunctions;        /* comparison functions for hash tables */
543         FmgrInfo   *hashfunctions;      /* lookup data for hash functions */
544 } SubPlanState;
545
546 /* ----------------
547  *              CaseExprState node
548  * ----------------
549  */
550 typedef struct CaseExprState
551 {
552         ExprState       xprstate;
553         List       *args;                       /* the arguments (list of WHEN clauses) */
554         ExprState  *defresult;          /* the default result (ELSE clause) */
555 } CaseExprState;
556
557 /* ----------------
558  *              CaseWhenState node
559  * ----------------
560  */
561 typedef struct CaseWhenState
562 {
563         ExprState       xprstate;
564         ExprState  *expr;                       /* condition expression */
565         ExprState  *result;                     /* substitution result */
566 } CaseWhenState;
567
568 /* ----------------
569  *              ArrayExprState node
570  *
571  * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
572  * arrays.
573  * ----------------
574  */
575 typedef struct ArrayExprState
576 {
577         ExprState       xprstate;
578         List       *elements;           /* states for child nodes */
579         int16           elemlength;             /* typlen of the array element type */
580         bool            elembyval;              /* is the element type pass-by-value? */
581         char            elemalign;              /* typalign of the element type */
582 } ArrayExprState;
583
584 /* ----------------
585  *              CoalesceExprState node
586  * ----------------
587  */
588 typedef struct CoalesceExprState
589 {
590         ExprState       xprstate;
591         List       *args;                       /* the arguments */
592 } CoalesceExprState;
593
594 /* ----------------
595  *              CoerceToDomainState node
596  * ----------------
597  */
598 typedef struct CoerceToDomainState
599 {
600         ExprState       xprstate;
601         ExprState  *arg;                        /* input expression */
602         /* Cached list of constraints that need to be checked */
603         List       *constraints;        /* list of DomainConstraintState nodes */
604 } CoerceToDomainState;
605
606 /*
607  * DomainConstraintState - one item to check during CoerceToDomain
608  *
609  * Note: this is just a Node, and not an ExprState, because it has no
610  * corresponding Expr to link to.  Nonetheless it is part of an ExprState
611  * tree, so we give it a name following the xxxState convention.
612  */
613 typedef enum DomainConstraintType
614 {
615         DOM_CONSTRAINT_NOTNULL,
616         DOM_CONSTRAINT_CHECK
617 } DomainConstraintType;
618
619 typedef struct DomainConstraintState
620 {
621         NodeTag         type;
622         DomainConstraintType constrainttype;            /* constraint type */
623         char       *name;                       /* name of constraint (for error msgs) */
624         ExprState  *check_expr;         /* for CHECK, a boolean expression */
625 } DomainConstraintState;
626
627
628 /* ----------------------------------------------------------------
629  *                               Executor State Trees
630  *
631  * An executing query has a PlanState tree paralleling the Plan tree
632  * that describes the plan.
633  * ----------------------------------------------------------------
634  */
635
636 /* ----------------
637  *              PlanState node
638  *
639  * We never actually instantiate any PlanState nodes; this is just the common
640  * abstract superclass for all PlanState-type nodes.
641  * ----------------
642  */
643 typedef struct PlanState
644 {
645         NodeTag         type;
646
647         Plan       *plan;                       /* associated Plan node */
648
649         EState     *state;                      /* at execution time, state's of
650                                                                  * individual nodes point to one EState
651                                                                  * for the whole top-level plan */
652
653         struct Instrumentation *instrument; /* Optional runtime stats for this
654                                                                                  * plan node */
655
656         /*
657          * Common structural data for all Plan types.  These links to
658          * subsidiary state trees parallel links in the associated plan tree
659          * (except for the subPlan list, which does not exist in the plan
660          * tree).
661          */
662         List       *targetlist;         /* target list to be computed at this node */
663         List       *qual;                       /* implicitly-ANDed qual conditions */
664         struct PlanState *lefttree; /* input plan tree(s) */
665         struct PlanState *righttree;
666         List       *initPlan;           /* Init SubPlanState nodes (un-correlated
667                                                                  * expr subselects) */
668         List       *subPlan;            /* SubPlanState nodes in my expressions */
669
670         /*
671          * State for management of parameter-change-driven rescanning
672          */
673         Bitmapset  *chgParam;           /* set of IDs of changed Params */
674
675         /*
676          * Other run-time state needed by most if not all node types.
677          */
678         TupleTableSlot *ps_OuterTupleSlot;      /* slot for current "outer" tuple */
679         TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
680         ExprContext *ps_ExprContext;    /* node's expression-evaluation context */
681         ProjectionInfo *ps_ProjInfo;    /* info for doing tuple projection */
682         bool            ps_TupFromTlist;/* state flag for processing set-valued
683                                                                  * functions in targetlist */
684 } PlanState;
685
686 /* ----------------
687  *      these are are defined to avoid confusion problems with "left"
688  *      and "right" and "inner" and "outer".  The convention is that
689  *      the "left" plan is the "outer" plan and the "right" plan is
690  *      the inner plan, but these make the code more readable.
691  * ----------------
692  */
693 #define innerPlanState(node)            (((PlanState *)(node))->righttree)
694 #define outerPlanState(node)            (((PlanState *)(node))->lefttree)
695
696
697 /* ----------------
698  *       ResultState information
699  * ----------------
700  */
701 typedef struct ResultState
702 {
703         PlanState       ps;                             /* its first field is NodeTag */
704         ExprState  *resconstantqual;
705         bool            rs_done;                /* are we done? */
706         bool            rs_checkqual;   /* do we need to check the qual? */
707 } ResultState;
708
709 /* ----------------
710  *       AppendState information
711  *
712  *              nplans                  how many plans are in the list
713  *              whichplan               which plan is being executed (0 .. n-1)
714  *              firstplan               first plan to execute (usually 0)
715  *              lastplan                last plan to execute (usually n-1)
716  * ----------------
717  */
718 typedef struct AppendState
719 {
720         PlanState       ps;                             /* its first field is NodeTag */
721         PlanState **appendplans;        /* array of PlanStates for my inputs */
722         int                     as_nplans;
723         int                     as_whichplan;
724         int                     as_firstplan;
725         int                     as_lastplan;
726 } AppendState;
727
728 /* ----------------------------------------------------------------
729  *                               Scan State Information
730  * ----------------------------------------------------------------
731  */
732
733 /* ----------------
734  *       ScanState information
735  *
736  *              ScanState extends PlanState for node types that represent
737  *              scans of an underlying relation.  It can also be used for nodes
738  *              that scan the output of an underlying plan node --- in that case,
739  *              only ScanTupleSlot is actually useful, and it refers to the tuple
740  *              retrieved from the subplan.
741  *
742  *              currentRelation    relation being scanned (NULL if none)
743  *              currentScanDesc    current scan descriptor for scan (NULL if none)
744  *              ScanTupleSlot      pointer to slot in tuple table holding scan tuple
745  * ----------------
746  */
747 typedef struct ScanState
748 {
749         PlanState       ps;                             /* its first field is NodeTag */
750         Relation        ss_currentRelation;
751         HeapScanDesc ss_currentScanDesc;
752         TupleTableSlot *ss_ScanTupleSlot;
753 } ScanState;
754
755 /*
756  * SeqScan uses a bare ScanState as its state node, since it needs
757  * no additional fields.
758  */
759 typedef ScanState SeqScanState;
760
761 /* ----------------
762  *       IndexScanState information
763  *
764  *              NumIndices                 number of indices in this scan
765  *              IndexPtr                   current index in use
766  *              ScanKeys                   Skey structures to scan index rels
767  *              NumScanKeys                array of no of keys in each Skey struct
768  *              RuntimeKeyInfo     array of array of exprstates for Skeys
769  *                                                 that will be evaluated at runtime
770  *              RuntimeContext     expr context for evaling runtime Skeys
771  *              RuntimeKeysReady   true if runtime Skeys have been computed
772  *              RelationDescs      ptr to array of relation descriptors
773  *              ScanDescs                  ptr to array of scan descriptors
774  * ----------------
775  */
776 typedef struct IndexScanState
777 {
778         ScanState       ss;                             /* its first field is NodeTag */
779         List       *indxqual;
780         List       *indxqualorig;
781         int                     iss_NumIndices;
782         int                     iss_IndexPtr;
783         int                     iss_MarkIndexPtr;
784         ScanKey    *iss_ScanKeys;
785         int                *iss_NumScanKeys;
786         ExprState ***iss_RuntimeKeyInfo;
787         ExprContext *iss_RuntimeContext;
788         bool            iss_RuntimeKeysReady;
789         RelationPtr iss_RelationDescs;
790         IndexScanDescPtr iss_ScanDescs;
791 } IndexScanState;
792
793 /* ----------------
794  *       TidScanState information
795  *
796  *              NumTids            number of tids in this scan
797  *              TidPtr             current tid in use
798  *              TidList            evaluated item pointers
799  * ----------------
800  */
801 typedef struct TidScanState
802 {
803         ScanState       ss;                             /* its first field is NodeTag */
804         List       *tss_tideval;        /* list of ExprState nodes */
805         int                     tss_NumTids;
806         int                     tss_TidPtr;
807         int                     tss_MarkTidPtr;
808         ItemPointerData *tss_TidList;
809         HeapTupleData tss_htup;
810 } TidScanState;
811
812 /* ----------------
813  *       SubqueryScanState information
814  *
815  *              SubqueryScanState is used for scanning a sub-query in the range table.
816  *              The sub-query will have its own EState, which we save here.
817  *              ScanTupleSlot references the current output tuple of the sub-query.
818  *
819  *              SubEState                  exec state for sub-query
820  * ----------------
821  */
822 typedef struct SubqueryScanState
823 {
824         ScanState       ss;                             /* its first field is NodeTag */
825         PlanState  *subplan;
826         EState     *sss_SubEState;
827 } SubqueryScanState;
828
829 /* ----------------
830  *       FunctionScanState information
831  *
832  *              Function nodes are used to scan the results of a
833  *              function appearing in FROM (typically a function returning set).
834  *
835  *              tupdesc                         expected return tuple description
836  *              tuplestorestate         private state of tuplestore.c
837  *              funcexpr                        state for function expression being evaluated
838  * ----------------
839  */
840 typedef struct FunctionScanState
841 {
842         ScanState       ss;                             /* its first field is NodeTag */
843         TupleDesc       tupdesc;
844         Tuplestorestate *tuplestorestate;
845         ExprState  *funcexpr;
846 } FunctionScanState;
847
848 /* ----------------------------------------------------------------
849  *                               Join State Information
850  * ----------------------------------------------------------------
851  */
852
853 /* ----------------
854  *       JoinState information
855  *
856  *              Superclass for state nodes of join plans.
857  * ----------------
858  */
859 typedef struct JoinState
860 {
861         PlanState       ps;
862         JoinType        jointype;
863         List       *joinqual;           /* JOIN quals (in addition to ps.qual) */
864 } JoinState;
865
866 /* ----------------
867  *       NestLoopState information
868  *
869  *              NeedNewOuter       true if need new outer tuple on next call
870  *              MatchedOuter       true if found a join match for current outer tuple
871  *              NullInnerTupleSlot prepared null tuple for left outer joins
872  * ----------------
873  */
874 typedef struct NestLoopState
875 {
876         JoinState       js;                             /* its first field is NodeTag */
877         bool            nl_NeedNewOuter;
878         bool            nl_MatchedOuter;
879         TupleTableSlot *nl_NullInnerTupleSlot;
880 } NestLoopState;
881
882 /* ----------------
883  *       MergeJoinState information
884  *
885  *              OuterSkipQual      outerKey1 < innerKey1 ...
886  *              InnerSkipQual      outerKey1 > innerKey1 ...
887  *              JoinState                  current "state" of join. see executor.h
888  *              MatchedOuter       true if found a join match for current outer tuple
889  *              MatchedInner       true if found a join match for current inner tuple
890  *              OuterTupleSlot     pointer to slot in tuple table for cur outer tuple
891  *              InnerTupleSlot     pointer to slot in tuple table for cur inner tuple
892  *              MarkedTupleSlot    pointer to slot in tuple table for marked tuple
893  *              NullOuterTupleSlot prepared null tuple for right outer joins
894  *              NullInnerTupleSlot prepared null tuple for left outer joins
895  * ----------------
896  */
897 typedef struct MergeJoinState
898 {
899         JoinState       js;                             /* its first field is NodeTag */
900         List       *mergeclauses;       /* list of ExprState nodes */
901         List       *mj_OuterSkipQual;           /* list of ExprState nodes */
902         List       *mj_InnerSkipQual;           /* list of ExprState nodes */
903         int                     mj_JoinState;
904         bool            mj_MatchedOuter;
905         bool            mj_MatchedInner;
906         TupleTableSlot *mj_OuterTupleSlot;
907         TupleTableSlot *mj_InnerTupleSlot;
908         TupleTableSlot *mj_MarkedTupleSlot;
909         TupleTableSlot *mj_NullOuterTupleSlot;
910         TupleTableSlot *mj_NullInnerTupleSlot;
911 } MergeJoinState;
912
913 /* ----------------
914  *       HashJoinState information
915  *
916  *              hj_HashTable                    hash table for the hashjoin
917  *              hj_CurBucketNo                  bucket# for current outer tuple
918  *              hj_CurTuple                             last inner tuple matched to current outer
919  *                                                              tuple, or NULL if starting search
920  *                                                              (CurBucketNo and CurTuple are meaningless
921  *                                                               unless OuterTupleSlot is nonempty!)
922  *              hj_OuterHashKeys                the outer hash keys in the hashjoin condition
923  *              hj_InnerHashKeys                the inner hash keys in the hashjoin condition
924  *              hj_HashOperators                the join operators in the hashjoin condition
925  *              hj_OuterTupleSlot               tuple slot for outer tuples
926  *              hj_HashTupleSlot                tuple slot for hashed tuples
927  *              hj_NullInnerTupleSlot   prepared null tuple for left outer joins
928  *              hj_NeedNewOuter                 true if need new outer tuple on next call
929  *              hj_MatchedOuter                 true if found a join match for current outer
930  *              hj_hashdone                             true if hash-table-build phase is done
931  * ----------------
932  */
933 typedef struct HashJoinState
934 {
935         JoinState       js;                             /* its first field is NodeTag */
936         List       *hashclauses;        /* list of ExprState nodes */
937         HashJoinTable hj_HashTable;
938         int                     hj_CurBucketNo;
939         HashJoinTuple hj_CurTuple;
940         List       *hj_OuterHashKeys;           /* list of ExprState nodes */
941         List       *hj_InnerHashKeys;           /* list of ExprState nodes */
942         List       *hj_HashOperators;           /* list of operator OIDs */
943         TupleTableSlot *hj_OuterTupleSlot;
944         TupleTableSlot *hj_HashTupleSlot;
945         TupleTableSlot *hj_NullInnerTupleSlot;
946         bool            hj_NeedNewOuter;
947         bool            hj_MatchedOuter;
948         bool            hj_hashdone;
949 } HashJoinState;
950
951
952 /* ----------------------------------------------------------------
953  *                               Materialization State Information
954  * ----------------------------------------------------------------
955  */
956
957 /* ----------------
958  *       MaterialState information
959  *
960  *              materialize nodes are used to materialize the results
961  *              of a subplan into a temporary file.
962  *
963  *              ss.ss_ScanTupleSlot refers to output of underlying plan.
964  * ----------------
965  */
966 typedef struct MaterialState
967 {
968         ScanState       ss;                             /* its first field is NodeTag */
969         void       *tuplestorestate;    /* private state of tuplestore.c */
970         bool            eof_underlying; /* reached end of underlying plan? */
971 } MaterialState;
972
973 /* ----------------
974  *       SortState information
975  * ----------------
976  */
977 typedef struct SortState
978 {
979         ScanState       ss;                             /* its first field is NodeTag */
980         bool            sort_Done;              /* sort completed yet? */
981         void       *tuplesortstate; /* private state of tuplesort.c */
982 } SortState;
983
984 /* ---------------------
985  *      GroupState information
986  * -------------------------
987  */
988 typedef struct GroupState
989 {
990         ScanState       ss;                             /* its first field is NodeTag */
991         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
992         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
993         bool            grp_done;               /* indicates completion of Group scan */
994 } GroupState;
995
996 /* ---------------------
997  *      AggState information
998  *
999  *      ss.ss_ScanTupleSlot refers to output of underlying plan.
1000  *
1001  *      Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1002  *      ecxt_aggnulls arrays, which hold the computed agg values for the current
1003  *      input group during evaluation of an Agg node's output tuple(s).  We
1004  *      create a second ExprContext, tmpcontext, in which to evaluate input
1005  *      expressions and run the aggregate transition functions.
1006  * -------------------------
1007  */
1008 /* these structs are private in nodeAgg.c: */
1009 typedef struct AggStatePerAggData *AggStatePerAgg;
1010 typedef struct AggStatePerGroupData *AggStatePerGroup;
1011
1012 typedef struct AggState
1013 {
1014         ScanState       ss;                             /* its first field is NodeTag */
1015         List       *aggs;                       /* all Aggref nodes in targetlist & quals */
1016         int                     numaggs;                /* length of list (could be zero!) */
1017         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1018         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1019         AggStatePerAgg peragg;          /* per-Aggref information */
1020         MemoryContext aggcontext;       /* memory context for long-lived data */
1021         ExprContext *tmpcontext;        /* econtext for input expressions */
1022         bool            agg_done;               /* indicates completion of Agg scan */
1023         /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1024         AggStatePerGroup pergroup;      /* per-Aggref-per-group working state */
1025         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1026         /* these fields are used in AGG_HASHED mode: */
1027         TupleHashTable hashtable;       /* hash table with one entry per group */
1028         bool            table_filled;   /* hash table filled yet? */
1029         TupleHashIterator hashiter; /* for iterating through hash table */
1030 } AggState;
1031
1032 /* ----------------
1033  *       UniqueState information
1034  *
1035  *              Unique nodes are used "on top of" sort nodes to discard
1036  *              duplicate tuples returned from the sort phase.  Basically
1037  *              all it does is compare the current tuple from the subplan
1038  *              with the previously fetched tuple stored in priorTuple.
1039  *              If the two are identical in all interesting fields, then
1040  *              we just fetch another tuple from the sort and try again.
1041  * ----------------
1042  */
1043 typedef struct UniqueState
1044 {
1045         PlanState       ps;                             /* its first field is NodeTag */
1046         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1047         HeapTuple       priorTuple;             /* most recently returned tuple, or NULL */
1048         MemoryContext tempContext;      /* short-term context for comparisons */
1049 } UniqueState;
1050
1051 /* ----------------
1052  *       HashState information
1053  * ----------------
1054  */
1055 typedef struct HashState
1056 {
1057         PlanState       ps;                             /* its first field is NodeTag */
1058         HashJoinTable hashtable;        /* hash table for the hashjoin */
1059         List       *hashkeys;           /* list of ExprState nodes */
1060         /* hashkeys is same as parent's hj_InnerHashKeys */
1061 } HashState;
1062
1063 /* ----------------
1064  *       SetOpState information
1065  *
1066  *              SetOp nodes are used "on top of" sort nodes to discard
1067  *              duplicate tuples returned from the sort phase.  These are
1068  *              more complex than a simple Unique since we have to count
1069  *              how many duplicates to return.
1070  * ----------------
1071  */
1072 typedef struct SetOpState
1073 {
1074         PlanState       ps;                             /* its first field is NodeTag */
1075         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1076         bool            subplan_done;   /* has subplan returned EOF? */
1077         long            numLeft;                /* number of left-input dups of cur group */
1078         long            numRight;               /* number of right-input dups of cur group */
1079         long            numOutput;              /* number of dups left to output */
1080         MemoryContext tempContext;      /* short-term context for comparisons */
1081 } SetOpState;
1082
1083 /* ----------------
1084  *       LimitState information
1085  *
1086  *              Limit nodes are used to enforce LIMIT/OFFSET clauses.
1087  *              They just select the desired subrange of their subplan's output.
1088  *
1089  * offset is the number of initial tuples to skip (0 does nothing).
1090  * count is the number of tuples to return after skipping the offset tuples.
1091  * If no limit count was specified, count is undefined and noCount is true.
1092  * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1093  * ----------------
1094  */
1095 typedef enum
1096 {
1097         LIMIT_INITIAL,                          /* initial state for LIMIT node */
1098         LIMIT_EMPTY,                            /* there are no returnable rows */
1099         LIMIT_INWINDOW,                         /* have returned a row in the window */
1100         LIMIT_SUBPLANEOF,                       /* at EOF of subplan (within window) */
1101         LIMIT_WINDOWEND,                        /* stepped off end of window */
1102         LIMIT_WINDOWSTART                       /* stepped off beginning of window */
1103 } LimitStateCond;
1104
1105 typedef struct LimitState
1106 {
1107         PlanState       ps;                             /* its first field is NodeTag */
1108         ExprState  *limitOffset;        /* OFFSET parameter, or NULL if none */
1109         ExprState  *limitCount;         /* COUNT parameter, or NULL if none */
1110         long            offset;                 /* current OFFSET value */
1111         long            count;                  /* current COUNT, if any */
1112         bool            noCount;                /* if true, ignore count */
1113         LimitStateCond lstate;          /* state machine status, as above */
1114         long            position;               /* 1-based index of last tuple returned */
1115         TupleTableSlot *subSlot;        /* tuple last obtained from subplan */
1116 } LimitState;
1117
1118 #endif   /* EXECNODES_H */