]> granicus.if.org Git - postgresql/blob - src/include/nodes/execnodes.h
Update copyright for 2009.
[postgresql] / src / include / nodes / execnodes.h
1 /*-------------------------------------------------------------------------
2  *
3  * execnodes.h
4  *        definitions for executor state nodes
5  *
6  *
7  * Portions Copyright (c) 1996-2009, 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.199 2009/01/01 17:23:59 momjian Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef EXECNODES_H
15 #define EXECNODES_H
16
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/skey.h"
20 #include "nodes/params.h"
21 #include "nodes/plannodes.h"    
22 #include "nodes/tidbitmap.h"    
23 #include "utils/hsearch.h"
24 #include "utils/rel.h"
25 #include "utils/snapshot.h"
26 #include "utils/tuplestore.h"
27
28
29 /* ----------------
30  *        IndexInfo information
31  *
32  *              this struct holds the information needed to construct new index
33  *              entries for a particular index.  Used for both index_build and
34  *              retail creation of index entries.
35  *
36  *              NumIndexAttrs           number of columns in this index
37  *              KeyAttrNumbers          underlying-rel attribute numbers used as keys
38  *                                                      (zeroes indicate expressions)
39  *              Expressions                     expr trees for expression entries, or NIL if none
40  *              ExpressionsState        exec state for expressions, or NIL if none
41  *              Predicate                       partial-index predicate, or NIL if none
42  *              PredicateState          exec state for predicate, or NIL if none
43  *              Unique                          is it a unique index?
44  *              ReadyForInserts         is it valid for inserts?
45  *              Concurrent                      are we doing a concurrent index build?
46  *              BrokenHotChain          did we detect any broken HOT chains?
47  *
48  * ii_Concurrent and ii_BrokenHotChain are used only during index build;
49  * they're conventionally set to false otherwise.
50  * ----------------
51  */
52 typedef struct IndexInfo
53 {
54         NodeTag         type;
55         int                     ii_NumIndexAttrs;
56         AttrNumber      ii_KeyAttrNumbers[INDEX_MAX_KEYS];
57         List       *ii_Expressions; /* list of Expr */
58         List       *ii_ExpressionsState;        /* list of ExprState */
59         List       *ii_Predicate;       /* list of Expr */
60         List       *ii_PredicateState;          /* list of ExprState */
61         bool            ii_Unique;
62         bool            ii_ReadyForInserts;
63         bool            ii_Concurrent;
64         bool            ii_BrokenHotChain;
65 } IndexInfo;
66
67 /* ----------------
68  *        ExprContext_CB
69  *
70  *              List of callbacks to be called at ExprContext shutdown.
71  * ----------------
72  */
73 typedef void (*ExprContextCallbackFunction) (Datum arg);
74
75 typedef struct ExprContext_CB
76 {
77         struct ExprContext_CB *next;
78         ExprContextCallbackFunction function;
79         Datum           arg;
80 } ExprContext_CB;
81
82 /* ----------------
83  *        ExprContext
84  *
85  *              This class holds the "current context" information
86  *              needed to evaluate expressions for doing tuple qualifications
87  *              and tuple projections.  For example, if an expression refers
88  *              to an attribute in the current inner tuple then we need to know
89  *              what the current inner tuple is and so we look at the expression
90  *              context.
91  *
92  *      There are two memory contexts associated with an ExprContext:
93  *      * ecxt_per_query_memory is a query-lifespan context, typically the same
94  *        context the ExprContext node itself is allocated in.  This context
95  *        can be used for purposes such as storing function call cache info.
96  *      * ecxt_per_tuple_memory is a short-term context for expression results.
97  *        As the name suggests, it will typically be reset once per tuple,
98  *        before we begin to evaluate expressions for that tuple.  Each
99  *        ExprContext normally has its very own per-tuple memory context.
100  *
101  *      CurrentMemoryContext should be set to ecxt_per_tuple_memory before
102  *      calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
103  * ----------------
104  */
105 typedef struct ExprContext
106 {
107         NodeTag         type;
108
109         /* Tuples that Var nodes in expression may refer to */
110         TupleTableSlot *ecxt_scantuple;
111         TupleTableSlot *ecxt_innertuple;
112         TupleTableSlot *ecxt_outertuple;
113
114         /* Memory contexts for expression evaluation --- see notes above */
115         MemoryContext ecxt_per_query_memory;
116         MemoryContext ecxt_per_tuple_memory;
117
118         /* Values to substitute for Param nodes in expression */
119         ParamExecData *ecxt_param_exec_vals;            /* for PARAM_EXEC params */
120         ParamListInfo ecxt_param_list_info; /* for other param types */
121
122         /*
123          * Values to substitute for Aggref nodes in the expressions of an Agg node,
124          * or for WindowFunc nodes within a WindowAgg node.
125          */
126         Datum      *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
127         bool       *ecxt_aggnulls;      /* null flags for aggs/windowfuncs */
128
129         /* Value to substitute for CaseTestExpr nodes in expression */
130         Datum           caseValue_datum;
131         bool            caseValue_isNull;
132
133         /* Value to substitute for CoerceToDomainValue nodes in expression */
134         Datum           domainValue_datum;
135         bool            domainValue_isNull;
136
137         /* Link to containing EState (NULL if a standalone ExprContext) */
138         struct EState *ecxt_estate;
139
140         /* Functions to call back when ExprContext is shut down */
141         ExprContext_CB *ecxt_callbacks;
142 } ExprContext;
143
144 /*
145  * Set-result status returned by ExecEvalExpr()
146  */
147 typedef enum
148 {
149         ExprSingleResult,                       /* expression does not return a set */
150         ExprMultipleResult,                     /* this result is an element of a set */
151         ExprEndResult                           /* there are no more elements in the set */
152 } ExprDoneCond;
153
154 /*
155  * Return modes for functions returning sets.  Note values must be chosen
156  * as separate bits so that a bitmask can be formed to indicate supported
157  * modes.  SFRM_Materialize_Random and SFRM_Materialize_Preferred are
158  * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
159  */
160 typedef enum
161 {
162         SFRM_ValuePerCall = 0x01,       /* one value returned per call */
163         SFRM_Materialize = 0x02,        /* result set instantiated in Tuplestore */
164         SFRM_Materialize_Random = 0x04,         /* Tuplestore needs randomAccess */
165         SFRM_Materialize_Preferred = 0x08       /* caller prefers Tuplestore */
166 } SetFunctionReturnMode;
167
168 /*
169  * When calling a function that might return a set (multiple rows),
170  * a node of this type is passed as fcinfo->resultinfo to allow
171  * return status to be passed back.  A function returning set should
172  * raise an error if no such resultinfo is provided.
173  */
174 typedef struct ReturnSetInfo
175 {
176         NodeTag         type;
177         /* values set by caller: */
178         ExprContext *econtext;          /* context function is being called in */
179         TupleDesc       expectedDesc;   /* tuple descriptor expected by caller */
180         int                     allowedModes;   /* bitmask: return modes caller can handle */
181         /* result status from function (but pre-initialized by caller): */
182         SetFunctionReturnMode returnMode;       /* actual return mode */
183         ExprDoneCond isDone;            /* status for ValuePerCall mode */
184         /* fields filled by function in Materialize return mode: */
185         Tuplestorestate *setResult; /* holds the complete returned tuple set */
186         TupleDesc       setDesc;                /* actual descriptor for returned tuples */
187 } ReturnSetInfo;
188
189 /* ----------------
190  *              ProjectionInfo node information
191  *
192  *              This is all the information needed to perform projections ---
193  *              that is, form new tuples by evaluation of targetlist expressions.
194  *              Nodes which need to do projections create one of these.
195  *
196  *              ExecProject() evaluates the tlist, forms a tuple, and stores it
197  *              in the given slot.      Note that the result will be a "virtual" tuple
198  *              unless ExecMaterializeSlot() is then called to force it to be
199  *              converted to a physical tuple.  The slot must have a tupledesc
200  *              that matches the output of the tlist!
201  *
202  *              The planner very often produces tlists that consist entirely of
203  *              simple Var references (lower levels of a plan tree almost always
204  *              look like that).  So we have an optimization to handle that case
205  *              with minimum overhead.
206  *
207  *              targetlist              target list for projection
208  *              exprContext             expression context in which to evaluate targetlist
209  *              slot                    slot to place projection result in
210  *              itemIsDone              workspace for ExecProject
211  *              isVarList               TRUE if simple-Var-list optimization applies
212  *              varSlotOffsets  array indicating which slot each simple Var is from
213  *              varNumbers              array indicating attr numbers of simple Vars
214  *              lastInnerVar    highest attnum from inner tuple slot (0 if none)
215  *              lastOuterVar    highest attnum from outer tuple slot (0 if none)
216  *              lastScanVar             highest attnum from scan tuple slot (0 if none)
217  * ----------------
218  */
219 typedef struct ProjectionInfo
220 {
221         NodeTag         type;
222         List       *pi_targetlist;
223         ExprContext *pi_exprContext;
224         TupleTableSlot *pi_slot;
225         ExprDoneCond *pi_itemIsDone;
226         bool            pi_isVarList;
227         int                *pi_varSlotOffsets;
228         int                *pi_varNumbers;
229         int                     pi_lastInnerVar;
230         int                     pi_lastOuterVar;
231         int                     pi_lastScanVar;
232 } ProjectionInfo;
233
234 /* ----------------
235  *        JunkFilter
236  *
237  *        This class is used to store information regarding junk attributes.
238  *        A junk attribute is an attribute in a tuple that is needed only for
239  *        storing intermediate information in the executor, and does not belong
240  *        in emitted tuples.  For example, when we do an UPDATE query,
241  *        the planner adds a "junk" entry to the targetlist so that the tuples
242  *        returned to ExecutePlan() contain an extra attribute: the ctid of
243  *        the tuple to be updated.      This is needed to do the update, but we
244  *        don't want the ctid to be part of the stored new tuple!  So, we
245  *        apply a "junk filter" to remove the junk attributes and form the
246  *        real output tuple.  The junkfilter code also provides routines to
247  *        extract the values of the junk attribute(s) from the input tuple.
248  *
249  *        targetList:           the original target list (including junk attributes).
250  *        cleanTupType:         the tuple descriptor for the "clean" tuple (with
251  *                                              junk attributes removed).
252  *        cleanMap:                     A map with the correspondence between the non-junk
253  *                                              attribute numbers of the "original" tuple and the
254  *                                              attribute numbers of the "clean" tuple.
255  *        resultSlot:           tuple slot used to hold cleaned tuple.
256  *        junkAttNo:            not used by junkfilter code.  Can be used by caller
257  *                                              to remember the attno of a specific junk attribute
258  *                                              (execMain.c stores the "ctid" attno here).
259  * ----------------
260  */
261 typedef struct JunkFilter
262 {
263         NodeTag         type;
264         List       *jf_targetList;
265         TupleDesc       jf_cleanTupType;
266         AttrNumber *jf_cleanMap;
267         TupleTableSlot *jf_resultSlot;
268         AttrNumber      jf_junkAttNo;
269 } JunkFilter;
270
271 /* ----------------
272  *        ResultRelInfo information
273  *
274  *              Whenever we update an existing relation, we have to
275  *              update indices on the relation, and perhaps also fire triggers.
276  *              The ResultRelInfo class is used to hold all the information needed
277  *              about a result relation, including indices.. -cim 10/15/89
278  *
279  *              RangeTableIndex                 result relation's range table index
280  *              RelationDesc                    relation descriptor for result relation
281  *              NumIndices                              # of indices existing on result relation
282  *              IndexRelationDescs              array of relation descriptors for indices
283  *              IndexRelationInfo               array of key/attr info for indices
284  *              TrigDesc                                triggers to be fired, if any
285  *              TrigFunctions                   cached lookup info for trigger functions
286  *              TrigInstrument                  optional runtime measurements for triggers
287  *              ConstraintExprs                 array of constraint-checking expr states
288  *              junkFilter                              for removing junk attributes from tuples
289  *              projectReturning                for computing a RETURNING list
290  * ----------------
291  */
292 typedef struct ResultRelInfo
293 {
294         NodeTag         type;
295         Index           ri_RangeTableIndex;
296         Relation        ri_RelationDesc;
297         int                     ri_NumIndices;
298         RelationPtr ri_IndexRelationDescs;
299         IndexInfo **ri_IndexRelationInfo;
300         TriggerDesc *ri_TrigDesc;
301         FmgrInfo   *ri_TrigFunctions;
302         struct Instrumentation *ri_TrigInstrument;
303         List      **ri_ConstraintExprs;
304         JunkFilter *ri_junkFilter;
305         ProjectionInfo *ri_projectReturning;
306 } ResultRelInfo;
307
308 /* ----------------
309  *        EState information
310  *
311  * Master working state for an Executor invocation
312  * ----------------
313  */
314 typedef struct EState
315 {
316         NodeTag         type;
317
318         /* Basic state for all query types: */
319         ScanDirection es_direction; /* current scan direction */
320         Snapshot        es_snapshot;    /* time qual to use */
321         Snapshot        es_crosscheck_snapshot; /* crosscheck time qual for RI */
322         List       *es_range_table; /* List of RangeTblEntry */
323
324         /* If query can insert/delete tuples, the command ID to mark them with */
325         CommandId       es_output_cid;
326
327         /* Info about target table for insert/update/delete queries: */
328         ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
329         int                     es_num_result_relations;                /* length of array */
330         ResultRelInfo *es_result_relation_info;         /* currently active array elt */
331         JunkFilter *es_junkFilter;      /* currently active junk filter */
332
333         /* Stuff used for firing triggers: */
334         List       *es_trig_target_relations;           /* trigger-only ResultRelInfos */
335         TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
336
337         /* Parameter info: */
338         ParamListInfo es_param_list_info;       /* values of external params */
339         ParamExecData *es_param_exec_vals;      /* values of internal params */
340
341         /* Other working state: */
342         MemoryContext es_query_cxt; /* per-query context in which EState lives */
343
344         TupleTable      es_tupleTable;  /* Array of TupleTableSlots */
345
346         uint32          es_processed;   /* # of tuples processed */
347         Oid                     es_lastoid;             /* last oid processed (by INSERT) */
348         List       *es_rowMarks;        /* not good place, but there is no other */
349
350         bool            es_instrument;  /* true requests runtime instrumentation */
351         bool            es_select_into; /* true if doing SELECT INTO */
352         bool            es_into_oids;   /* true to generate OIDs in SELECT INTO */
353
354         List       *es_exprcontexts;    /* List of ExprContexts within EState */
355
356         List       *es_subplanstates;           /* List of PlanState for SubPlans */
357
358         /*
359          * this ExprContext is for per-output-tuple operations, such as constraint
360          * checks and index-value computations.  It will be reset for each output
361          * tuple.  Note that it will be created only if needed.
362          */
363         ExprContext *es_per_tuple_exprcontext;
364
365         /* Below is to re-evaluate plan qual in READ COMMITTED mode */
366         PlannedStmt *es_plannedstmt;    /* link to top of plan tree */
367         struct evalPlanQual *es_evalPlanQual;           /* chain of PlanQual states */
368         bool       *es_evTupleNull; /* local array of EPQ status */
369         HeapTuple  *es_evTuple;         /* shared array of EPQ substitute tuples */
370         bool            es_useEvalPlan; /* evaluating EPQ tuples? */
371 } EState;
372
373
374 /*
375  * es_rowMarks is a list of these structs.  See RowMarkClause for details
376  * about rti and prti.  toidAttno is not used in a "plain" rowmark.
377  */
378 typedef struct ExecRowMark
379 {
380         Relation        relation;               /* opened and RowShareLock'd relation */
381         Index           rti;                    /* its range table index */
382         Index           prti;                   /* parent range table index, if child */
383         bool            forUpdate;              /* true = FOR UPDATE, false = FOR SHARE */
384         bool            noWait;                 /* NOWAIT option */
385         AttrNumber      ctidAttNo;              /* resno of its ctid junk attribute */
386         AttrNumber      toidAttNo;              /* resno of tableoid junk attribute, if any */
387         ItemPointerData curCtid;        /* ctid of currently locked tuple, if any */
388 } ExecRowMark;
389
390
391 /* ----------------------------------------------------------------
392  *                               Tuple Hash Tables
393  *
394  * All-in-memory tuple hash tables are used for a number of purposes.
395  *
396  * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
397  * and tab_eq_funcs are non-cross-type equality operators for those types.
398  * Normally these are the only functions used, but FindTupleHashEntry()
399  * supports searching a hashtable using cross-data-type hashing.  For that,
400  * the caller must supply hash functions for the LHS datatype as well as
401  * the cross-type equality operators to use.  in_hash_funcs and cur_eq_funcs
402  * are set to point to the caller's function arrays while doing such a search.
403  * During LookupTupleHashEntry(), they point to tab_hash_funcs and
404  * tab_eq_funcs respectively.
405  * ----------------------------------------------------------------
406  */
407 typedef struct TupleHashEntryData *TupleHashEntry;
408 typedef struct TupleHashTableData *TupleHashTable;
409
410 typedef struct TupleHashEntryData
411 {
412         /* firstTuple must be the first field in this struct! */
413         MinimalTuple firstTuple;        /* copy of first tuple in this group */
414         /* there may be additional data beyond the end of this struct */
415 } TupleHashEntryData;                   /* VARIABLE LENGTH STRUCT */
416
417 typedef struct TupleHashTableData
418 {
419         HTAB       *hashtab;            /* underlying dynahash table */
420         int                     numCols;                /* number of columns in lookup key */
421         AttrNumber *keyColIdx;          /* attr numbers of key columns */
422         FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */
423         FmgrInfo   *tab_eq_funcs;       /* equality functions for table datatype(s) */
424         MemoryContext tablecxt;         /* memory context containing table */
425         MemoryContext tempcxt;          /* context for function evaluations */
426         Size            entrysize;              /* actual size to make each hash entry */
427         TupleTableSlot *tableslot;      /* slot for referencing table entries */
428         /* The following fields are set transiently for each table search: */
429         TupleTableSlot *inputslot;      /* current input tuple's slot */
430         FmgrInfo   *in_hash_funcs;      /* hash functions for input datatype(s) */
431         FmgrInfo   *cur_eq_funcs;       /* equality functions for input vs. table */
432 } TupleHashTableData;
433
434 typedef HASH_SEQ_STATUS TupleHashIterator;
435
436 /*
437  * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
438  * Use ResetTupleHashIterator if the table can be frozen (in this case no
439  * explicit scan termination is needed).
440  */
441 #define InitTupleHashIterator(htable, iter) \
442         hash_seq_init(iter, (htable)->hashtab)
443 #define TermTupleHashIterator(iter) \
444         hash_seq_term(iter)
445 #define ResetTupleHashIterator(htable, iter) \
446         do { \
447                 hash_freeze((htable)->hashtab); \
448                 hash_seq_init(iter, (htable)->hashtab); \
449         } while (0)
450 #define ScanTupleHashTable(iter) \
451         ((TupleHashEntry) hash_seq_search(iter))
452
453
454 /* ----------------------------------------------------------------
455  *                               Expression State Trees
456  *
457  * Each executable expression tree has a parallel ExprState tree.
458  *
459  * Unlike PlanState, there is not an exact one-for-one correspondence between
460  * ExprState node types and Expr node types.  Many Expr node types have no
461  * need for node-type-specific run-time state, and so they can use plain
462  * ExprState or GenericExprState as their associated ExprState node type.
463  * ----------------------------------------------------------------
464  */
465
466 /* ----------------
467  *              ExprState node
468  *
469  * ExprState is the common superclass for all ExprState-type nodes.
470  *
471  * It can also be instantiated directly for leaf Expr nodes that need no
472  * local run-time state (such as Var, Const, or Param).
473  *
474  * To save on dispatch overhead, each ExprState node contains a function
475  * pointer to the routine to execute to evaluate the node.
476  * ----------------
477  */
478
479 typedef struct ExprState ExprState;
480
481 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
482                                                                                                 ExprContext *econtext,
483                                                                                                 bool *isNull,
484                                                                                                 ExprDoneCond *isDone);
485
486 struct ExprState
487 {
488         NodeTag         type;
489         Expr       *expr;                       /* associated Expr node */
490         ExprStateEvalFunc evalfunc; /* routine to run to execute node */
491 };
492
493 /* ----------------
494  *              GenericExprState node
495  *
496  * This is used for Expr node types that need no local run-time state,
497  * but have one child Expr node.
498  * ----------------
499  */
500 typedef struct GenericExprState
501 {
502         ExprState       xprstate;
503         ExprState  *arg;                        /* state of my child node */
504 } GenericExprState;
505
506 /* ----------------
507  *              AggrefExprState node
508  * ----------------
509  */
510 typedef struct AggrefExprState
511 {
512         ExprState       xprstate;
513         List       *args;                       /* states of argument expressions */
514         int                     aggno;                  /* ID number for agg within its plan node */
515 } AggrefExprState;
516
517 /* ----------------
518  *              WindowFuncExprState node
519  * ----------------
520  */
521 typedef struct WindowFuncExprState
522 {
523         ExprState       xprstate;
524         List       *args;                       /* states of argument expressions */
525         int                     wfuncno;                /* ID number for wfunc within its plan node */
526 } WindowFuncExprState;
527
528 /* ----------------
529  *              ArrayRefExprState node
530  *
531  * Note: array types can be fixed-length (typlen > 0), but only when the
532  * element type is itself fixed-length.  Otherwise they are varlena structures
533  * and have typlen = -1.  In any case, an array type is never pass-by-value.
534  * ----------------
535  */
536 typedef struct ArrayRefExprState
537 {
538         ExprState       xprstate;
539         List       *refupperindexpr;    /* states for child nodes */
540         List       *reflowerindexpr;
541         ExprState  *refexpr;
542         ExprState  *refassgnexpr;
543         int16           refattrlength;  /* typlen of array type */
544         int16           refelemlength;  /* typlen of the array element type */
545         bool            refelembyval;   /* is the element type pass-by-value? */
546         char            refelemalign;   /* typalign of the element type */
547 } ArrayRefExprState;
548
549 /* ----------------
550  *              FuncExprState node
551  *
552  * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
553  * and NullIf nodes; be careful to check what xprstate.expr is actually
554  * pointing at!
555  * ----------------
556  */
557 typedef struct FuncExprState
558 {
559         ExprState       xprstate;
560         List       *args;                       /* states of argument expressions */
561
562         /*
563          * Function manager's lookup info for the target function.  If func.fn_oid
564          * is InvalidOid, we haven't initialized it yet (nor any of the following
565          * fields).
566          */
567         FmgrInfo        func;
568
569         /*
570          * For a set-returning function (SRF) that returns a tuplestore, we
571          * keep the tuplestore here and dole out the result rows one at a time.
572          * The slot holds the row currently being returned.
573          */
574         Tuplestorestate *funcResultStore;
575         TupleTableSlot *funcResultSlot;
576
577         /*
578          * In some cases we need to compute a tuple descriptor for the function's
579          * output.  If so, it's stored here.
580          */
581         TupleDesc       funcResultDesc;
582         bool            funcReturnsTuple;       /* valid when funcResultDesc isn't NULL */
583
584         /*
585          * We need to store argument values across calls when evaluating a SRF
586          * that uses value-per-call mode.
587          *
588          * setArgsValid is true when we are evaluating a set-valued function and
589          * we are in the middle of a call series; we want to pass the same
590          * argument values to the function again (and again, until it returns
591          * ExprEndResult).
592          */
593         bool            setArgsValid;
594
595         /*
596          * Flag to remember whether we found a set-valued argument to the
597          * function. This causes the function result to be a set as well. Valid
598          * only when setArgsValid is true or funcResultStore isn't NULL.
599          */
600         bool            setHasSetArg;   /* some argument returns a set */
601
602         /*
603          * Flag to remember whether we have registered a shutdown callback for
604          * this FuncExprState.  We do so only if funcResultStore or setArgsValid
605          * has been set at least once (since all the callback is for is to release
606          * the tuplestore or clear setArgsValid).
607          */
608         bool            shutdown_reg;   /* a shutdown callback is registered */
609
610         /*
611          * Current argument data for a set-valued function; contains valid data
612          * only if setArgsValid is true.
613          */
614         FunctionCallInfoData setArgs;
615 } FuncExprState;
616
617 /* ----------------
618  *              ScalarArrayOpExprState node
619  *
620  * This is a FuncExprState plus some additional data.
621  * ----------------
622  */
623 typedef struct ScalarArrayOpExprState
624 {
625         FuncExprState fxprstate;
626         /* Cached info about array element type */
627         Oid                     element_type;
628         int16           typlen;
629         bool            typbyval;
630         char            typalign;
631 } ScalarArrayOpExprState;
632
633 /* ----------------
634  *              BoolExprState node
635  * ----------------
636  */
637 typedef struct BoolExprState
638 {
639         ExprState       xprstate;
640         List       *args;                       /* states of argument expression(s) */
641 } BoolExprState;
642
643 /* ----------------
644  *              SubPlanState node
645  * ----------------
646  */
647 typedef struct SubPlanState
648 {
649         ExprState       xprstate;
650         struct PlanState *planstate;    /* subselect plan's state tree */
651         ExprState  *testexpr;           /* state of combining expression */
652         List       *args;                       /* states of argument expression(s) */
653         HeapTuple       curTuple;               /* copy of most recent tuple from subplan */
654         /* these are used when hashing the subselect's output: */
655         ProjectionInfo *projLeft;       /* for projecting lefthand exprs */
656         ProjectionInfo *projRight;      /* for projecting subselect output */
657         TupleHashTable hashtable;       /* hash table for no-nulls subselect rows */
658         TupleHashTable hashnulls;       /* hash table for rows with null(s) */
659         bool            havehashrows;   /* TRUE if hashtable is not empty */
660         bool            havenullrows;   /* TRUE if hashnulls is not empty */
661         MemoryContext tablecxt;         /* memory context containing tables */
662         ExprContext *innerecontext; /* working context for comparisons */
663         AttrNumber *keyColIdx;          /* control data for hash tables */
664         FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */
665         FmgrInfo   *tab_eq_funcs;       /* equality functions for table datatype(s) */
666         FmgrInfo   *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
667         FmgrInfo   *cur_eq_funcs;       /* equality functions for LHS vs. table */
668 } SubPlanState;
669
670 /* ----------------
671  *              AlternativeSubPlanState node
672  * ----------------
673  */
674 typedef struct AlternativeSubPlanState
675 {
676         ExprState       xprstate;
677         List       *subplans;           /* states of alternative subplans */
678         int                     active;                 /* list index of the one we're using */
679 } AlternativeSubPlanState;
680
681 /* ----------------
682  *              FieldSelectState node
683  * ----------------
684  */
685 typedef struct FieldSelectState
686 {
687         ExprState       xprstate;
688         ExprState  *arg;                        /* input expression */
689         TupleDesc       argdesc;                /* tupdesc for most recent input */
690 } FieldSelectState;
691
692 /* ----------------
693  *              FieldStoreState node
694  * ----------------
695  */
696 typedef struct FieldStoreState
697 {
698         ExprState       xprstate;
699         ExprState  *arg;                        /* input tuple value */
700         List       *newvals;            /* new value(s) for field(s) */
701         TupleDesc       argdesc;                /* tupdesc for most recent input */
702 } FieldStoreState;
703
704 /* ----------------
705  *              CoerceViaIOState node
706  * ----------------
707  */
708 typedef struct CoerceViaIOState
709 {
710         ExprState       xprstate;
711         ExprState  *arg;                        /* input expression */
712         FmgrInfo        outfunc;                /* lookup info for source output function */
713         FmgrInfo        infunc;                 /* lookup info for result input function */
714         Oid                     intypioparam;   /* argument needed for input function */
715 } CoerceViaIOState;
716
717 /* ----------------
718  *              ArrayCoerceExprState node
719  * ----------------
720  */
721 typedef struct ArrayCoerceExprState
722 {
723         ExprState       xprstate;
724         ExprState  *arg;                        /* input array value */
725         Oid                     resultelemtype; /* element type of result array */
726         FmgrInfo        elemfunc;               /* lookup info for element coercion function */
727         /* use struct pointer to avoid including array.h here */
728         struct ArrayMapState *amstate;          /* workspace for array_map */
729 } ArrayCoerceExprState;
730
731 /* ----------------
732  *              ConvertRowtypeExprState node
733  * ----------------
734  */
735 typedef struct ConvertRowtypeExprState
736 {
737         ExprState       xprstate;
738         ExprState  *arg;                        /* input tuple value */
739         TupleDesc       indesc;                 /* tupdesc for source rowtype */
740         TupleDesc       outdesc;                /* tupdesc for result rowtype */
741         AttrNumber *attrMap;            /* indexes of input fields, or 0 for null */
742         Datum      *invalues;           /* workspace for deconstructing source */
743         bool       *inisnull;
744         Datum      *outvalues;          /* workspace for constructing result */
745         bool       *outisnull;
746 } ConvertRowtypeExprState;
747
748 /* ----------------
749  *              CaseExprState node
750  * ----------------
751  */
752 typedef struct CaseExprState
753 {
754         ExprState       xprstate;
755         ExprState  *arg;                        /* implicit equality comparison argument */
756         List       *args;                       /* the arguments (list of WHEN clauses) */
757         ExprState  *defresult;          /* the default result (ELSE clause) */
758 } CaseExprState;
759
760 /* ----------------
761  *              CaseWhenState node
762  * ----------------
763  */
764 typedef struct CaseWhenState
765 {
766         ExprState       xprstate;
767         ExprState  *expr;                       /* condition expression */
768         ExprState  *result;                     /* substitution result */
769 } CaseWhenState;
770
771 /* ----------------
772  *              ArrayExprState node
773  *
774  * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
775  * arrays.
776  * ----------------
777  */
778 typedef struct ArrayExprState
779 {
780         ExprState       xprstate;
781         List       *elements;           /* states for child nodes */
782         int16           elemlength;             /* typlen of the array element type */
783         bool            elembyval;              /* is the element type pass-by-value? */
784         char            elemalign;              /* typalign of the element type */
785 } ArrayExprState;
786
787 /* ----------------
788  *              RowExprState node
789  * ----------------
790  */
791 typedef struct RowExprState
792 {
793         ExprState       xprstate;
794         List       *args;                       /* the arguments */
795         TupleDesc       tupdesc;                /* descriptor for result tuples */
796 } RowExprState;
797
798 /* ----------------
799  *              RowCompareExprState node
800  * ----------------
801  */
802 typedef struct RowCompareExprState
803 {
804         ExprState       xprstate;
805         List       *largs;                      /* the left-hand input arguments */
806         List       *rargs;                      /* the right-hand input arguments */
807         FmgrInfo   *funcs;                      /* array of comparison function info */
808 } RowCompareExprState;
809
810 /* ----------------
811  *              CoalesceExprState node
812  * ----------------
813  */
814 typedef struct CoalesceExprState
815 {
816         ExprState       xprstate;
817         List       *args;                       /* the arguments */
818 } CoalesceExprState;
819
820 /* ----------------
821  *              MinMaxExprState node
822  * ----------------
823  */
824 typedef struct MinMaxExprState
825 {
826         ExprState       xprstate;
827         List       *args;                       /* the arguments */
828         FmgrInfo        cfunc;                  /* lookup info for comparison func */
829 } MinMaxExprState;
830
831 /* ----------------
832  *              XmlExprState node
833  * ----------------
834  */
835 typedef struct XmlExprState
836 {
837         ExprState       xprstate;
838         List       *named_args;         /* ExprStates for named arguments */
839         FmgrInfo   *named_outfuncs; /* array of output fns for named arguments */
840         List       *args;                       /* ExprStates for other arguments */
841 } XmlExprState;
842
843 /* ----------------
844  *              NullTestState node
845  * ----------------
846  */
847 typedef struct NullTestState
848 {
849         ExprState       xprstate;
850         ExprState  *arg;                        /* input expression */
851         bool            argisrow;               /* T if input is of a composite type */
852         /* used only if argisrow: */
853         TupleDesc       argdesc;                /* tupdesc for most recent input */
854 } NullTestState;
855
856 /* ----------------
857  *              CoerceToDomainState node
858  * ----------------
859  */
860 typedef struct CoerceToDomainState
861 {
862         ExprState       xprstate;
863         ExprState  *arg;                        /* input expression */
864         /* Cached list of constraints that need to be checked */
865         List       *constraints;        /* list of DomainConstraintState nodes */
866 } CoerceToDomainState;
867
868 /*
869  * DomainConstraintState - one item to check during CoerceToDomain
870  *
871  * Note: this is just a Node, and not an ExprState, because it has no
872  * corresponding Expr to link to.  Nonetheless it is part of an ExprState
873  * tree, so we give it a name following the xxxState convention.
874  */
875 typedef enum DomainConstraintType
876 {
877         DOM_CONSTRAINT_NOTNULL,
878         DOM_CONSTRAINT_CHECK
879 } DomainConstraintType;
880
881 typedef struct DomainConstraintState
882 {
883         NodeTag         type;
884         DomainConstraintType constrainttype;            /* constraint type */
885         char       *name;                       /* name of constraint (for error msgs) */
886         ExprState  *check_expr;         /* for CHECK, a boolean expression */
887 } DomainConstraintState;
888
889
890 /* ----------------------------------------------------------------
891  *                               Executor State Trees
892  *
893  * An executing query has a PlanState tree paralleling the Plan tree
894  * that describes the plan.
895  * ----------------------------------------------------------------
896  */
897
898 /* ----------------
899  *              PlanState node
900  *
901  * We never actually instantiate any PlanState nodes; this is just the common
902  * abstract superclass for all PlanState-type nodes.
903  * ----------------
904  */
905 typedef struct PlanState
906 {
907         NodeTag         type;
908
909         Plan       *plan;                       /* associated Plan node */
910
911         EState     *state;                      /* at execution time, states of individual
912                                                                  * nodes point to one EState for the whole
913                                                                  * top-level plan */
914
915         struct Instrumentation *instrument; /* Optional runtime stats for this
916                                                                                  * plan node */
917
918         /*
919          * Common structural data for all Plan types.  These links to subsidiary
920          * state trees parallel links in the associated plan tree (except for the
921          * subPlan list, which does not exist in the plan tree).
922          */
923         List       *targetlist;         /* target list to be computed at this node */
924         List       *qual;                       /* implicitly-ANDed qual conditions */
925         struct PlanState *lefttree; /* input plan tree(s) */
926         struct PlanState *righttree;
927         List       *initPlan;           /* Init SubPlanState nodes (un-correlated expr
928                                                                  * subselects) */
929         List       *subPlan;            /* SubPlanState nodes in my expressions */
930
931         /*
932          * State for management of parameter-change-driven rescanning
933          */
934         Bitmapset  *chgParam;           /* set of IDs of changed Params */
935
936         /*
937          * Other run-time state needed by most if not all node types.
938          */
939         TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
940         ExprContext *ps_ExprContext;    /* node's expression-evaluation context */
941         ProjectionInfo *ps_ProjInfo;    /* info for doing tuple projection */
942         bool            ps_TupFromTlist;        /* state flag for processing set-valued
943                                                                          * functions in targetlist */
944 } PlanState;
945
946 /* ----------------
947  *      these are are defined to avoid confusion problems with "left"
948  *      and "right" and "inner" and "outer".  The convention is that
949  *      the "left" plan is the "outer" plan and the "right" plan is
950  *      the inner plan, but these make the code more readable.
951  * ----------------
952  */
953 #define innerPlanState(node)            (((PlanState *)(node))->righttree)
954 #define outerPlanState(node)            (((PlanState *)(node))->lefttree)
955
956
957 /* ----------------
958  *       ResultState information
959  * ----------------
960  */
961 typedef struct ResultState
962 {
963         PlanState       ps;                             /* its first field is NodeTag */
964         ExprState  *resconstantqual;
965         bool            rs_done;                /* are we done? */
966         bool            rs_checkqual;   /* do we need to check the qual? */
967 } ResultState;
968
969 /* ----------------
970  *       AppendState information
971  *
972  *              nplans                  how many plans are in the list
973  *              whichplan               which plan is being executed (0 .. n-1)
974  *              firstplan               first plan to execute (usually 0)
975  *              lastplan                last plan to execute (usually n-1)
976  * ----------------
977  */
978 typedef struct AppendState
979 {
980         PlanState       ps;                             /* its first field is NodeTag */
981         PlanState **appendplans;        /* array of PlanStates for my inputs */
982         int                     as_nplans;
983         int                     as_whichplan;
984         int                     as_firstplan;
985         int                     as_lastplan;
986 } AppendState;
987
988 /* ----------------
989  *       RecursiveUnionState information
990  *
991  *              RecursiveUnionState is used for performing a recursive union.
992  *
993  *              recursing                       T when we're done scanning the non-recursive term
994  *              intermediate_empty      T if intermediate_table is currently empty
995  *              working_table           working table (to be scanned by recursive term)
996  *              intermediate_table      current recursive output (next generation of WT)
997  * ----------------
998  */
999 typedef struct RecursiveUnionState
1000 {
1001         PlanState       ps;                             /* its first field is NodeTag */
1002         bool            recursing;
1003         bool            intermediate_empty;
1004         Tuplestorestate *working_table;
1005         Tuplestorestate *intermediate_table;
1006         /* Remaining fields are unused in UNION ALL case */
1007         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1008         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1009         MemoryContext tempContext;      /* short-term context for comparisons */
1010         TupleHashTable hashtable;       /* hash table for tuples already seen */
1011         MemoryContext tableContext;     /* memory context containing hash table */
1012 } RecursiveUnionState;
1013
1014 /* ----------------
1015  *       BitmapAndState information
1016  * ----------------
1017  */
1018 typedef struct BitmapAndState
1019 {
1020         PlanState       ps;                             /* its first field is NodeTag */
1021         PlanState **bitmapplans;        /* array of PlanStates for my inputs */
1022         int                     nplans;                 /* number of input plans */
1023 } BitmapAndState;
1024
1025 /* ----------------
1026  *       BitmapOrState information
1027  * ----------------
1028  */
1029 typedef struct BitmapOrState
1030 {
1031         PlanState       ps;                             /* its first field is NodeTag */
1032         PlanState **bitmapplans;        /* array of PlanStates for my inputs */
1033         int                     nplans;                 /* number of input plans */
1034 } BitmapOrState;
1035
1036 /* ----------------------------------------------------------------
1037  *                               Scan State Information
1038  * ----------------------------------------------------------------
1039  */
1040
1041 /* ----------------
1042  *       ScanState information
1043  *
1044  *              ScanState extends PlanState for node types that represent
1045  *              scans of an underlying relation.  It can also be used for nodes
1046  *              that scan the output of an underlying plan node --- in that case,
1047  *              only ScanTupleSlot is actually useful, and it refers to the tuple
1048  *              retrieved from the subplan.
1049  *
1050  *              currentRelation    relation being scanned (NULL if none)
1051  *              currentScanDesc    current scan descriptor for scan (NULL if none)
1052  *              ScanTupleSlot      pointer to slot in tuple table holding scan tuple
1053  * ----------------
1054  */
1055 typedef struct ScanState
1056 {
1057         PlanState       ps;                             /* its first field is NodeTag */
1058         Relation        ss_currentRelation;
1059         HeapScanDesc ss_currentScanDesc;
1060         TupleTableSlot *ss_ScanTupleSlot;
1061 } ScanState;
1062
1063 /*
1064  * SeqScan uses a bare ScanState as its state node, since it needs
1065  * no additional fields.
1066  */
1067 typedef ScanState SeqScanState;
1068
1069 /*
1070  * These structs store information about index quals that don't have simple
1071  * constant right-hand sides.  See comments for ExecIndexBuildScanKeys()
1072  * for discussion.
1073  */
1074 typedef struct
1075 {
1076         ScanKey         scan_key;               /* scankey to put value into */
1077         ExprState  *key_expr;           /* expr to evaluate to get value */
1078 } IndexRuntimeKeyInfo;
1079
1080 typedef struct
1081 {
1082         ScanKey         scan_key;               /* scankey to put value into */
1083         ExprState  *array_expr;         /* expr to evaluate to get array value */
1084         int                     next_elem;              /* next array element to use */
1085         int                     num_elems;              /* number of elems in current array value */
1086         Datum      *elem_values;        /* array of num_elems Datums */
1087         bool       *elem_nulls;         /* array of num_elems is-null flags */
1088 } IndexArrayKeyInfo;
1089
1090 /* ----------------
1091  *       IndexScanState information
1092  *
1093  *              indexqualorig      execution state for indexqualorig expressions
1094  *              ScanKeys                   Skey structures to scan index rel
1095  *              NumScanKeys                number of Skey structs
1096  *              RuntimeKeys                info about Skeys that must be evaluated at runtime
1097  *              NumRuntimeKeys     number of RuntimeKeys structs
1098  *              RuntimeKeysReady   true if runtime Skeys have been computed
1099  *              RuntimeContext     expr context for evaling runtime Skeys
1100  *              RelationDesc       index relation descriptor
1101  *              ScanDesc                   index scan descriptor
1102  * ----------------
1103  */
1104 typedef struct IndexScanState
1105 {
1106         ScanState       ss;                             /* its first field is NodeTag */
1107         List       *indexqualorig;
1108         ScanKey         iss_ScanKeys;
1109         int                     iss_NumScanKeys;
1110         IndexRuntimeKeyInfo *iss_RuntimeKeys;
1111         int                     iss_NumRuntimeKeys;
1112         bool            iss_RuntimeKeysReady;
1113         ExprContext *iss_RuntimeContext;
1114         Relation        iss_RelationDesc;
1115         IndexScanDesc iss_ScanDesc;
1116 } IndexScanState;
1117
1118 /* ----------------
1119  *       BitmapIndexScanState information
1120  *
1121  *              result                     bitmap to return output into, or NULL
1122  *              ScanKeys                   Skey structures to scan index rel
1123  *              NumScanKeys                number of Skey structs
1124  *              RuntimeKeys                info about Skeys that must be evaluated at runtime
1125  *              NumRuntimeKeys     number of RuntimeKeys structs
1126  *              ArrayKeys                  info about Skeys that come from ScalarArrayOpExprs
1127  *              NumArrayKeys       number of ArrayKeys structs
1128  *              RuntimeKeysReady   true if runtime Skeys have been computed
1129  *              RuntimeContext     expr context for evaling runtime Skeys
1130  *              RelationDesc       index relation descriptor
1131  *              ScanDesc                   index scan descriptor
1132  * ----------------
1133  */
1134 typedef struct BitmapIndexScanState
1135 {
1136         ScanState       ss;                             /* its first field is NodeTag */
1137         TIDBitmap  *biss_result;
1138         ScanKey         biss_ScanKeys;
1139         int                     biss_NumScanKeys;
1140         IndexRuntimeKeyInfo *biss_RuntimeKeys;
1141         int                     biss_NumRuntimeKeys;
1142         IndexArrayKeyInfo *biss_ArrayKeys;
1143         int                     biss_NumArrayKeys;
1144         bool            biss_RuntimeKeysReady;
1145         ExprContext *biss_RuntimeContext;
1146         Relation        biss_RelationDesc;
1147         IndexScanDesc biss_ScanDesc;
1148 } BitmapIndexScanState;
1149
1150 /* ----------------
1151  *       BitmapHeapScanState information
1152  *
1153  *              bitmapqualorig     execution state for bitmapqualorig expressions
1154  *              tbm                                bitmap obtained from child index scan(s)
1155  *              tbmres                     current-page data
1156  * ----------------
1157  */
1158 typedef struct BitmapHeapScanState
1159 {
1160         ScanState       ss;                             /* its first field is NodeTag */
1161         List       *bitmapqualorig;
1162         TIDBitmap  *tbm;
1163         TBMIterateResult *tbmres;
1164 } BitmapHeapScanState;
1165
1166 /* ----------------
1167  *       TidScanState information
1168  *
1169  *              isCurrentOf    scan has a CurrentOfExpr qual
1170  *              NumTids            number of tids in this scan
1171  *              TidPtr             index of currently fetched tid
1172  *              TidList            evaluated item pointers (array of size NumTids)
1173  * ----------------
1174  */
1175 typedef struct TidScanState
1176 {
1177         ScanState       ss;                             /* its first field is NodeTag */
1178         List       *tss_tidquals;       /* list of ExprState nodes */
1179         bool            tss_isCurrentOf;
1180         int                     tss_NumTids;
1181         int                     tss_TidPtr;
1182         int                     tss_MarkTidPtr;
1183         ItemPointerData *tss_TidList;
1184         HeapTupleData tss_htup;
1185 } TidScanState;
1186
1187 /* ----------------
1188  *       SubqueryScanState information
1189  *
1190  *              SubqueryScanState is used for scanning a sub-query in the range table.
1191  *              ScanTupleSlot references the current output tuple of the sub-query.
1192  * ----------------
1193  */
1194 typedef struct SubqueryScanState
1195 {
1196         ScanState       ss;                             /* its first field is NodeTag */
1197         PlanState  *subplan;
1198 } SubqueryScanState;
1199
1200 /* ----------------
1201  *       FunctionScanState information
1202  *
1203  *              Function nodes are used to scan the results of a
1204  *              function appearing in FROM (typically a function returning set).
1205  *
1206  *              eflags                          node's capability flags
1207  *              tupdesc                         expected return tuple description
1208  *              tuplestorestate         private state of tuplestore.c
1209  *              funcexpr                        state for function expression being evaluated
1210  * ----------------
1211  */
1212 typedef struct FunctionScanState
1213 {
1214         ScanState       ss;                             /* its first field is NodeTag */
1215         int                     eflags;
1216         TupleDesc       tupdesc;
1217         Tuplestorestate *tuplestorestate;
1218         ExprState  *funcexpr;
1219 } FunctionScanState;
1220
1221 /* ----------------
1222  *       ValuesScanState information
1223  *
1224  *              ValuesScan nodes are used to scan the results of a VALUES list
1225  *
1226  *              rowcontext                      per-expression-list context
1227  *              exprlists                       array of expression lists being evaluated
1228  *              array_len                       size of array
1229  *              curr_idx                        current array index (0-based)
1230  *              marked_idx                      marked position (for mark/restore)
1231  *
1232  *      Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1233  *      expressions attached to the node.  We create a second ExprContext,
1234  *      rowcontext, in which to build the executor expression state for each
1235  *      Values sublist.  Resetting this context lets us get rid of expression
1236  *      state for each row, avoiding major memory leakage over a long values list.
1237  * ----------------
1238  */
1239 typedef struct ValuesScanState
1240 {
1241         ScanState       ss;                             /* its first field is NodeTag */
1242         ExprContext *rowcontext;
1243         List      **exprlists;
1244         int                     array_len;
1245         int                     curr_idx;
1246         int                     marked_idx;
1247 } ValuesScanState;
1248
1249 /* ----------------
1250  *       CteScanState information
1251  *
1252  *              CteScan nodes are used to scan a CommonTableExpr query.
1253  *
1254  * Multiple CteScan nodes can read out from the same CTE query.  We use
1255  * a tuplestore to hold rows that have been read from the CTE query but
1256  * not yet consumed by all readers.
1257  * ----------------
1258  */
1259 typedef struct CteScanState
1260 {
1261         ScanState       ss;                             /* its first field is NodeTag */
1262         int                     eflags;                 /* capability flags to pass to tuplestore */
1263         int                     readptr;                /* index of my tuplestore read pointer */
1264         PlanState  *cteplanstate;       /* PlanState for the CTE query itself */
1265         /* Link to the "leader" CteScanState (possibly this same node) */
1266         struct CteScanState *leader;
1267         /* The remaining fields are only valid in the "leader" CteScanState */
1268         Tuplestorestate *cte_table;     /* rows already read from the CTE query */
1269         bool            eof_cte;                /* reached end of CTE query? */
1270 } CteScanState;
1271
1272 /* ----------------
1273  *       WorkTableScanState information
1274  *
1275  *              WorkTableScan nodes are used to scan the work table created by
1276  *              a RecursiveUnion node.  We locate the RecursiveUnion node
1277  *              during executor startup.
1278  * ----------------
1279  */
1280 typedef struct WorkTableScanState
1281 {
1282         ScanState       ss;                             /* its first field is NodeTag */
1283         RecursiveUnionState *rustate;
1284 } WorkTableScanState;
1285
1286 /* ----------------------------------------------------------------
1287  *                               Join State Information
1288  * ----------------------------------------------------------------
1289  */
1290
1291 /* ----------------
1292  *       JoinState information
1293  *
1294  *              Superclass for state nodes of join plans.
1295  * ----------------
1296  */
1297 typedef struct JoinState
1298 {
1299         PlanState       ps;
1300         JoinType        jointype;
1301         List       *joinqual;           /* JOIN quals (in addition to ps.qual) */
1302 } JoinState;
1303
1304 /* ----------------
1305  *       NestLoopState information
1306  *
1307  *              NeedNewOuter       true if need new outer tuple on next call
1308  *              MatchedOuter       true if found a join match for current outer tuple
1309  *              NullInnerTupleSlot prepared null tuple for left outer joins
1310  * ----------------
1311  */
1312 typedef struct NestLoopState
1313 {
1314         JoinState       js;                             /* its first field is NodeTag */
1315         bool            nl_NeedNewOuter;
1316         bool            nl_MatchedOuter;
1317         TupleTableSlot *nl_NullInnerTupleSlot;
1318 } NestLoopState;
1319
1320 /* ----------------
1321  *       MergeJoinState information
1322  *
1323  *              NumClauses                 number of mergejoinable join clauses
1324  *              Clauses                    info for each mergejoinable clause
1325  *              JoinState                  current "state" of join.  see execdefs.h
1326  *              ExtraMarks                 true to issue extra Mark operations on inner scan
1327  *              FillOuter                  true if should emit unjoined outer tuples anyway
1328  *              FillInner                  true if should emit unjoined inner tuples anyway
1329  *              MatchedOuter       true if found a join match for current outer tuple
1330  *              MatchedInner       true if found a join match for current inner tuple
1331  *              OuterTupleSlot     slot in tuple table for cur outer tuple
1332  *              InnerTupleSlot     slot in tuple table for cur inner tuple
1333  *              MarkedTupleSlot    slot in tuple table for marked tuple
1334  *              NullOuterTupleSlot prepared null tuple for right outer joins
1335  *              NullInnerTupleSlot prepared null tuple for left outer joins
1336  *              OuterEContext      workspace for computing outer tuple's join values
1337  *              InnerEContext      workspace for computing inner tuple's join values
1338  * ----------------
1339  */
1340 /* private in nodeMergejoin.c: */
1341 typedef struct MergeJoinClauseData *MergeJoinClause;
1342
1343 typedef struct MergeJoinState
1344 {
1345         JoinState       js;                             /* its first field is NodeTag */
1346         int                     mj_NumClauses;
1347         MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1348         int                     mj_JoinState;
1349         bool            mj_ExtraMarks;
1350         bool            mj_FillOuter;
1351         bool            mj_FillInner;
1352         bool            mj_MatchedOuter;
1353         bool            mj_MatchedInner;
1354         TupleTableSlot *mj_OuterTupleSlot;
1355         TupleTableSlot *mj_InnerTupleSlot;
1356         TupleTableSlot *mj_MarkedTupleSlot;
1357         TupleTableSlot *mj_NullOuterTupleSlot;
1358         TupleTableSlot *mj_NullInnerTupleSlot;
1359         ExprContext *mj_OuterEContext;
1360         ExprContext *mj_InnerEContext;
1361 } MergeJoinState;
1362
1363 /* ----------------
1364  *       HashJoinState information
1365  *
1366  *              hj_HashTable                    hash table for the hashjoin
1367  *                                                              (NULL if table not built yet)
1368  *              hj_CurHashValue                 hash value for current outer tuple
1369  *              hj_CurBucketNo                  bucket# for current outer tuple
1370  *              hj_CurTuple                             last inner tuple matched to current outer
1371  *                                                              tuple, or NULL if starting search
1372  *                                                              (CurHashValue, CurBucketNo and CurTuple are
1373  *                                                               undefined if OuterTupleSlot is empty!)
1374  *              hj_OuterHashKeys                the outer hash keys in the hashjoin condition
1375  *              hj_InnerHashKeys                the inner hash keys in the hashjoin condition
1376  *              hj_HashOperators                the join operators in the hashjoin condition
1377  *              hj_OuterTupleSlot               tuple slot for outer tuples
1378  *              hj_HashTupleSlot                tuple slot for hashed tuples
1379  *              hj_NullInnerTupleSlot   prepared null tuple for left outer joins
1380  *              hj_FirstOuterTupleSlot  first tuple retrieved from outer plan
1381  *              hj_NeedNewOuter                 true if need new outer tuple on next call
1382  *              hj_MatchedOuter                 true if found a join match for current outer
1383  *              hj_OuterNotEmpty                true if outer relation known not empty
1384  * ----------------
1385  */
1386
1387 /* these structs are defined in executor/hashjoin.h: */
1388 typedef struct HashJoinTupleData *HashJoinTuple;
1389 typedef struct HashJoinTableData *HashJoinTable;
1390
1391 typedef struct HashJoinState
1392 {
1393         JoinState       js;                             /* its first field is NodeTag */
1394         List       *hashclauses;        /* list of ExprState nodes */
1395         HashJoinTable hj_HashTable;
1396         uint32          hj_CurHashValue;
1397         int                     hj_CurBucketNo;
1398         HashJoinTuple hj_CurTuple;
1399         List       *hj_OuterHashKeys;           /* list of ExprState nodes */
1400         List       *hj_InnerHashKeys;           /* list of ExprState nodes */
1401         List       *hj_HashOperators;           /* list of operator OIDs */
1402         TupleTableSlot *hj_OuterTupleSlot;
1403         TupleTableSlot *hj_HashTupleSlot;
1404         TupleTableSlot *hj_NullInnerTupleSlot;
1405         TupleTableSlot *hj_FirstOuterTupleSlot;
1406         bool            hj_NeedNewOuter;
1407         bool            hj_MatchedOuter;
1408         bool            hj_OuterNotEmpty;
1409 } HashJoinState;
1410
1411
1412 /* ----------------------------------------------------------------
1413  *                               Materialization State Information
1414  * ----------------------------------------------------------------
1415  */
1416
1417 /* ----------------
1418  *       MaterialState information
1419  *
1420  *              materialize nodes are used to materialize the results
1421  *              of a subplan into a temporary file.
1422  *
1423  *              ss.ss_ScanTupleSlot refers to output of underlying plan.
1424  * ----------------
1425  */
1426 typedef struct MaterialState
1427 {
1428         ScanState       ss;                             /* its first field is NodeTag */
1429         int                     eflags;                 /* capability flags to pass to tuplestore */
1430         bool            eof_underlying; /* reached end of underlying plan? */
1431         Tuplestorestate *tuplestorestate;
1432 } MaterialState;
1433
1434 /* ----------------
1435  *       SortState information
1436  * ----------------
1437  */
1438 typedef struct SortState
1439 {
1440         ScanState       ss;                             /* its first field is NodeTag */
1441         bool            randomAccess;   /* need random access to sort output? */
1442         bool            bounded;                /* is the result set bounded? */
1443         int64           bound;                  /* if bounded, how many tuples are needed */
1444         bool            sort_Done;              /* sort completed yet? */
1445         bool            bounded_Done;   /* value of bounded we did the sort with */
1446         int64           bound_Done;             /* value of bound we did the sort with */
1447         void       *tuplesortstate; /* private state of tuplesort.c */
1448 } SortState;
1449
1450 /* ---------------------
1451  *      GroupState information
1452  * -------------------------
1453  */
1454 typedef struct GroupState
1455 {
1456         ScanState       ss;                             /* its first field is NodeTag */
1457         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1458         bool            grp_done;               /* indicates completion of Group scan */
1459 } GroupState;
1460
1461 /* ---------------------
1462  *      AggState information
1463  *
1464  *      ss.ss_ScanTupleSlot refers to output of underlying plan.
1465  *
1466  *      Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1467  *      ecxt_aggnulls arrays, which hold the computed agg values for the current
1468  *      input group during evaluation of an Agg node's output tuple(s).  We
1469  *      create a second ExprContext, tmpcontext, in which to evaluate input
1470  *      expressions and run the aggregate transition functions.
1471  * -------------------------
1472  */
1473 /* these structs are private in nodeAgg.c: */
1474 typedef struct AggStatePerAggData *AggStatePerAgg;
1475 typedef struct AggStatePerGroupData *AggStatePerGroup;
1476
1477 typedef struct AggState
1478 {
1479         ScanState       ss;                             /* its first field is NodeTag */
1480         List       *aggs;                       /* all Aggref nodes in targetlist & quals */
1481         int                     numaggs;                /* length of list (could be zero!) */
1482         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1483         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1484         AggStatePerAgg peragg;          /* per-Aggref information */
1485         MemoryContext aggcontext;       /* memory context for long-lived data */
1486         ExprContext *tmpcontext;        /* econtext for input expressions */
1487         bool            agg_done;               /* indicates completion of Agg scan */
1488         /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1489         AggStatePerGroup pergroup;      /* per-Aggref-per-group working state */
1490         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1491         /* these fields are used in AGG_HASHED mode: */
1492         TupleHashTable hashtable;       /* hash table with one entry per group */
1493         TupleTableSlot *hashslot;       /* slot for loading hash table */
1494         List       *hash_needed;        /* list of columns needed in hash table */
1495         bool            table_filled;   /* hash table filled yet? */
1496         TupleHashIterator hashiter; /* for iterating through hash table */
1497 } AggState;
1498
1499 /* ----------------
1500  *      WindowAggState information
1501  * ----------------
1502  */
1503 /* these structs are private in nodeWindowAgg.c: */
1504 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1505 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1506
1507 typedef struct WindowAggState
1508 {
1509         ScanState       ss;                                     /* its first field is NodeTag */
1510
1511         /* these fields are filled in by ExecInitExpr: */
1512         List       *funcs;                              /* all WindowFunc nodes in targetlist */
1513         int                     numfuncs;                       /* total number of window functions */
1514         int                     numaggs;                        /* number that are plain aggregates */
1515
1516         WindowStatePerFunc perfunc;             /* per-window-function information */
1517         WindowStatePerAgg peragg;               /* per-plain-aggregate information */
1518         FmgrInfo   *partEqfunctions;    /* equality funcs for partition columns */
1519         FmgrInfo   *ordEqfunctions;             /* equality funcs for ordering columns */
1520         Tuplestorestate    *buffer;             /* stores rows of current partition */
1521         int                     current_ptr;            /* read pointer # for current */
1522         int                     agg_ptr;                        /* read pointer # for aggregates */
1523         int64           spooled_rows;           /* total # of rows in buffer */
1524         int64           currentpos;                     /* position of current row in partition */
1525         int64           frametailpos;           /* current frame tail position */
1526         int64           aggregatedupto;         /* rows before this one are aggregated */
1527
1528         MemoryContext wincontext;               /* context for partition-lifespan data */
1529         ExprContext *tmpcontext;                /* short-term evaluation context */
1530
1531         bool            all_done;                       /* true if the scan is finished */
1532         bool            partition_spooled;      /* true if all tuples in current partition
1533                                                                          * have been spooled into tuplestore */
1534         bool            more_partitions;        /* true if there's more partitions after
1535                                                                          * this one */
1536         bool            frametail_valid;        /* true if frametailpos is known up to date
1537                                                                          * for current row */
1538
1539         TupleTableSlot *first_part_slot;        /* first tuple of current or next
1540                                                                                  * partition */
1541
1542         /* temporary slots for tuples fetched back from tuplestore */
1543         TupleTableSlot *agg_row_slot;
1544         TupleTableSlot *temp_slot_1;
1545         TupleTableSlot *temp_slot_2;
1546 } WindowAggState;
1547
1548 /* ----------------
1549  *       UniqueState information
1550  *
1551  *              Unique nodes are used "on top of" sort nodes to discard
1552  *              duplicate tuples returned from the sort phase.  Basically
1553  *              all it does is compare the current tuple from the subplan
1554  *              with the previously fetched tuple (stored in its result slot).
1555  *              If the two are identical in all interesting fields, then
1556  *              we just fetch another tuple from the sort and try again.
1557  * ----------------
1558  */
1559 typedef struct UniqueState
1560 {
1561         PlanState       ps;                             /* its first field is NodeTag */
1562         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1563         MemoryContext tempContext;      /* short-term context for comparisons */
1564 } UniqueState;
1565
1566 /* ----------------
1567  *       HashState information
1568  * ----------------
1569  */
1570 typedef struct HashState
1571 {
1572         PlanState       ps;                             /* its first field is NodeTag */
1573         HashJoinTable hashtable;        /* hash table for the hashjoin */
1574         List       *hashkeys;           /* list of ExprState nodes */
1575         /* hashkeys is same as parent's hj_InnerHashKeys */
1576 } HashState;
1577
1578 /* ----------------
1579  *       SetOpState information
1580  *
1581  *              Even in "sorted" mode, SetOp nodes are more complex than a simple
1582  *              Unique, since we have to count how many duplicates to return.  But
1583  *              we also support hashing, so this is really more like a cut-down
1584  *              form of Agg.
1585  * ----------------
1586  */
1587 /* this struct is private in nodeSetOp.c: */
1588 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1589
1590 typedef struct SetOpState
1591 {
1592         PlanState       ps;                             /* its first field is NodeTag */
1593         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1594         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1595         bool            setop_done;             /* indicates completion of output scan */
1596         long            numOutput;              /* number of dups left to output */
1597         MemoryContext tempContext;      /* short-term context for comparisons */
1598         /* these fields are used in SETOP_SORTED mode: */
1599         SetOpStatePerGroup pergroup;    /* per-group working state */
1600         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1601         /* these fields are used in SETOP_HASHED mode: */
1602         TupleHashTable hashtable;       /* hash table with one entry per group */
1603         MemoryContext tableContext;     /* memory context containing hash table */
1604         bool            table_filled;   /* hash table filled yet? */
1605         TupleHashIterator hashiter; /* for iterating through hash table */
1606 } SetOpState;
1607
1608 /* ----------------
1609  *       LimitState information
1610  *
1611  *              Limit nodes are used to enforce LIMIT/OFFSET clauses.
1612  *              They just select the desired subrange of their subplan's output.
1613  *
1614  * offset is the number of initial tuples to skip (0 does nothing).
1615  * count is the number of tuples to return after skipping the offset tuples.
1616  * If no limit count was specified, count is undefined and noCount is true.
1617  * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1618  * ----------------
1619  */
1620 typedef enum
1621 {
1622         LIMIT_INITIAL,                          /* initial state for LIMIT node */
1623         LIMIT_RESCAN,                           /* rescan after recomputing parameters */
1624         LIMIT_EMPTY,                            /* there are no returnable rows */
1625         LIMIT_INWINDOW,                         /* have returned a row in the window */
1626         LIMIT_SUBPLANEOF,                       /* at EOF of subplan (within window) */
1627         LIMIT_WINDOWEND,                        /* stepped off end of window */
1628         LIMIT_WINDOWSTART                       /* stepped off beginning of window */
1629 } LimitStateCond;
1630
1631 typedef struct LimitState
1632 {
1633         PlanState       ps;                             /* its first field is NodeTag */
1634         ExprState  *limitOffset;        /* OFFSET parameter, or NULL if none */
1635         ExprState  *limitCount;         /* COUNT parameter, or NULL if none */
1636         int64           offset;                 /* current OFFSET value */
1637         int64           count;                  /* current COUNT, if any */
1638         bool            noCount;                /* if true, ignore count */
1639         LimitStateCond lstate;          /* state machine status, as above */
1640         int64           position;               /* 1-based index of last tuple returned */
1641         TupleTableSlot *subSlot;        /* tuple last obtained from subplan */
1642 } LimitState;
1643
1644 #endif   /* EXECNODES_H */