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