]> granicus.if.org Git - postgresql/blob - src/include/nodes/execnodes.h
996efa8f87dd1925445855f0dacb0d51ff5145b0
[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.202 2009/03/21 00:04:40 tgl 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  *              tbmiterator                iterator for scanning current pages
1156  *              tbmres                     current-page data
1157  *              prefetch_iterator  iterator for prefetching ahead of current page
1158  *              prefetch_pages     # pages prefetch iterator is ahead of current
1159  *              prefetch_target    target prefetch distance
1160  * ----------------
1161  */
1162 typedef struct BitmapHeapScanState
1163 {
1164         ScanState       ss;                             /* its first field is NodeTag */
1165         List       *bitmapqualorig;
1166         TIDBitmap  *tbm;
1167         TBMIterator *tbmiterator;
1168         TBMIterateResult *tbmres;
1169         TBMIterator *prefetch_iterator;
1170         int                     prefetch_pages;
1171         int                     prefetch_target;
1172 } BitmapHeapScanState;
1173
1174 /* ----------------
1175  *       TidScanState information
1176  *
1177  *              isCurrentOf    scan has a CurrentOfExpr qual
1178  *              NumTids            number of tids in this scan
1179  *              TidPtr             index of currently fetched tid
1180  *              TidList            evaluated item pointers (array of size NumTids)
1181  * ----------------
1182  */
1183 typedef struct TidScanState
1184 {
1185         ScanState       ss;                             /* its first field is NodeTag */
1186         List       *tss_tidquals;       /* list of ExprState nodes */
1187         bool            tss_isCurrentOf;
1188         int                     tss_NumTids;
1189         int                     tss_TidPtr;
1190         int                     tss_MarkTidPtr;
1191         ItemPointerData *tss_TidList;
1192         HeapTupleData tss_htup;
1193 } TidScanState;
1194
1195 /* ----------------
1196  *       SubqueryScanState information
1197  *
1198  *              SubqueryScanState is used for scanning a sub-query in the range table.
1199  *              ScanTupleSlot references the current output tuple of the sub-query.
1200  * ----------------
1201  */
1202 typedef struct SubqueryScanState
1203 {
1204         ScanState       ss;                             /* its first field is NodeTag */
1205         PlanState  *subplan;
1206 } SubqueryScanState;
1207
1208 /* ----------------
1209  *       FunctionScanState information
1210  *
1211  *              Function nodes are used to scan the results of a
1212  *              function appearing in FROM (typically a function returning set).
1213  *
1214  *              eflags                          node's capability flags
1215  *              tupdesc                         expected return tuple description
1216  *              tuplestorestate         private state of tuplestore.c
1217  *              funcexpr                        state for function expression being evaluated
1218  * ----------------
1219  */
1220 typedef struct FunctionScanState
1221 {
1222         ScanState       ss;                             /* its first field is NodeTag */
1223         int                     eflags;
1224         TupleDesc       tupdesc;
1225         Tuplestorestate *tuplestorestate;
1226         ExprState  *funcexpr;
1227 } FunctionScanState;
1228
1229 /* ----------------
1230  *       ValuesScanState information
1231  *
1232  *              ValuesScan nodes are used to scan the results of a VALUES list
1233  *
1234  *              rowcontext                      per-expression-list context
1235  *              exprlists                       array of expression lists being evaluated
1236  *              array_len                       size of array
1237  *              curr_idx                        current array index (0-based)
1238  *              marked_idx                      marked position (for mark/restore)
1239  *
1240  *      Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1241  *      expressions attached to the node.  We create a second ExprContext,
1242  *      rowcontext, in which to build the executor expression state for each
1243  *      Values sublist.  Resetting this context lets us get rid of expression
1244  *      state for each row, avoiding major memory leakage over a long values list.
1245  * ----------------
1246  */
1247 typedef struct ValuesScanState
1248 {
1249         ScanState       ss;                             /* its first field is NodeTag */
1250         ExprContext *rowcontext;
1251         List      **exprlists;
1252         int                     array_len;
1253         int                     curr_idx;
1254         int                     marked_idx;
1255 } ValuesScanState;
1256
1257 /* ----------------
1258  *       CteScanState information
1259  *
1260  *              CteScan nodes are used to scan a CommonTableExpr query.
1261  *
1262  * Multiple CteScan nodes can read out from the same CTE query.  We use
1263  * a tuplestore to hold rows that have been read from the CTE query but
1264  * not yet consumed by all readers.
1265  * ----------------
1266  */
1267 typedef struct CteScanState
1268 {
1269         ScanState       ss;                             /* its first field is NodeTag */
1270         int                     eflags;                 /* capability flags to pass to tuplestore */
1271         int                     readptr;                /* index of my tuplestore read pointer */
1272         PlanState  *cteplanstate;       /* PlanState for the CTE query itself */
1273         /* Link to the "leader" CteScanState (possibly this same node) */
1274         struct CteScanState *leader;
1275         /* The remaining fields are only valid in the "leader" CteScanState */
1276         Tuplestorestate *cte_table;     /* rows already read from the CTE query */
1277         bool            eof_cte;                /* reached end of CTE query? */
1278 } CteScanState;
1279
1280 /* ----------------
1281  *       WorkTableScanState information
1282  *
1283  *              WorkTableScan nodes are used to scan the work table created by
1284  *              a RecursiveUnion node.  We locate the RecursiveUnion node
1285  *              during executor startup.
1286  * ----------------
1287  */
1288 typedef struct WorkTableScanState
1289 {
1290         ScanState       ss;                             /* its first field is NodeTag */
1291         RecursiveUnionState *rustate;
1292 } WorkTableScanState;
1293
1294 /* ----------------------------------------------------------------
1295  *                               Join State Information
1296  * ----------------------------------------------------------------
1297  */
1298
1299 /* ----------------
1300  *       JoinState information
1301  *
1302  *              Superclass for state nodes of join plans.
1303  * ----------------
1304  */
1305 typedef struct JoinState
1306 {
1307         PlanState       ps;
1308         JoinType        jointype;
1309         List       *joinqual;           /* JOIN quals (in addition to ps.qual) */
1310 } JoinState;
1311
1312 /* ----------------
1313  *       NestLoopState information
1314  *
1315  *              NeedNewOuter       true if need new outer tuple on next call
1316  *              MatchedOuter       true if found a join match for current outer tuple
1317  *              NullInnerTupleSlot prepared null tuple for left outer joins
1318  * ----------------
1319  */
1320 typedef struct NestLoopState
1321 {
1322         JoinState       js;                             /* its first field is NodeTag */
1323         bool            nl_NeedNewOuter;
1324         bool            nl_MatchedOuter;
1325         TupleTableSlot *nl_NullInnerTupleSlot;
1326 } NestLoopState;
1327
1328 /* ----------------
1329  *       MergeJoinState information
1330  *
1331  *              NumClauses                 number of mergejoinable join clauses
1332  *              Clauses                    info for each mergejoinable clause
1333  *              JoinState                  current "state" of join.  see execdefs.h
1334  *              ExtraMarks                 true to issue extra Mark operations on inner scan
1335  *              FillOuter                  true if should emit unjoined outer tuples anyway
1336  *              FillInner                  true if should emit unjoined inner tuples anyway
1337  *              MatchedOuter       true if found a join match for current outer tuple
1338  *              MatchedInner       true if found a join match for current inner tuple
1339  *              OuterTupleSlot     slot in tuple table for cur outer tuple
1340  *              InnerTupleSlot     slot in tuple table for cur inner tuple
1341  *              MarkedTupleSlot    slot in tuple table for marked tuple
1342  *              NullOuterTupleSlot prepared null tuple for right outer joins
1343  *              NullInnerTupleSlot prepared null tuple for left outer joins
1344  *              OuterEContext      workspace for computing outer tuple's join values
1345  *              InnerEContext      workspace for computing inner tuple's join values
1346  * ----------------
1347  */
1348 /* private in nodeMergejoin.c: */
1349 typedef struct MergeJoinClauseData *MergeJoinClause;
1350
1351 typedef struct MergeJoinState
1352 {
1353         JoinState       js;                             /* its first field is NodeTag */
1354         int                     mj_NumClauses;
1355         MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1356         int                     mj_JoinState;
1357         bool            mj_ExtraMarks;
1358         bool            mj_FillOuter;
1359         bool            mj_FillInner;
1360         bool            mj_MatchedOuter;
1361         bool            mj_MatchedInner;
1362         TupleTableSlot *mj_OuterTupleSlot;
1363         TupleTableSlot *mj_InnerTupleSlot;
1364         TupleTableSlot *mj_MarkedTupleSlot;
1365         TupleTableSlot *mj_NullOuterTupleSlot;
1366         TupleTableSlot *mj_NullInnerTupleSlot;
1367         ExprContext *mj_OuterEContext;
1368         ExprContext *mj_InnerEContext;
1369 } MergeJoinState;
1370
1371 /* ----------------
1372  *       HashJoinState information
1373  *
1374  *              hj_HashTable                    hash table for the hashjoin
1375  *                                                              (NULL if table not built yet)
1376  *              hj_CurHashValue                 hash value for current outer tuple
1377  *              hj_CurBucketNo                  regular bucket# for current outer tuple
1378  *              hj_CurSkewBucketNo              skew bucket# for current outer tuple
1379  *              hj_CurTuple                             last inner tuple matched to current outer
1380  *                                                              tuple, or NULL if starting search
1381  *                                                              (hj_CurXXX variables are undefined if
1382  *                                                              OuterTupleSlot is empty!)
1383  *              hj_OuterHashKeys                the outer hash keys in the hashjoin condition
1384  *              hj_InnerHashKeys                the inner hash keys in the hashjoin condition
1385  *              hj_HashOperators                the join operators in the hashjoin condition
1386  *              hj_OuterTupleSlot               tuple slot for outer tuples
1387  *              hj_HashTupleSlot                tuple slot for hashed tuples
1388  *              hj_NullInnerTupleSlot   prepared null tuple for left outer joins
1389  *              hj_FirstOuterTupleSlot  first tuple retrieved from outer plan
1390  *              hj_NeedNewOuter                 true if need new outer tuple on next call
1391  *              hj_MatchedOuter                 true if found a join match for current outer
1392  *              hj_OuterNotEmpty                true if outer relation known not empty
1393  * ----------------
1394  */
1395
1396 /* these structs are defined in executor/hashjoin.h: */
1397 typedef struct HashJoinTupleData *HashJoinTuple;
1398 typedef struct HashJoinTableData *HashJoinTable;
1399
1400 typedef struct HashJoinState
1401 {
1402         JoinState       js;                             /* its first field is NodeTag */
1403         List       *hashclauses;        /* list of ExprState nodes */
1404         HashJoinTable hj_HashTable;
1405         uint32          hj_CurHashValue;
1406         int                     hj_CurBucketNo;
1407         int                     hj_CurSkewBucketNo;
1408         HashJoinTuple hj_CurTuple;
1409         List       *hj_OuterHashKeys;           /* list of ExprState nodes */
1410         List       *hj_InnerHashKeys;           /* list of ExprState nodes */
1411         List       *hj_HashOperators;           /* list of operator OIDs */
1412         TupleTableSlot *hj_OuterTupleSlot;
1413         TupleTableSlot *hj_HashTupleSlot;
1414         TupleTableSlot *hj_NullInnerTupleSlot;
1415         TupleTableSlot *hj_FirstOuterTupleSlot;
1416         bool            hj_NeedNewOuter;
1417         bool            hj_MatchedOuter;
1418         bool            hj_OuterNotEmpty;
1419 } HashJoinState;
1420
1421
1422 /* ----------------------------------------------------------------
1423  *                               Materialization State Information
1424  * ----------------------------------------------------------------
1425  */
1426
1427 /* ----------------
1428  *       MaterialState information
1429  *
1430  *              materialize nodes are used to materialize the results
1431  *              of a subplan into a temporary file.
1432  *
1433  *              ss.ss_ScanTupleSlot refers to output of underlying plan.
1434  * ----------------
1435  */
1436 typedef struct MaterialState
1437 {
1438         ScanState       ss;                             /* its first field is NodeTag */
1439         int                     eflags;                 /* capability flags to pass to tuplestore */
1440         bool            eof_underlying; /* reached end of underlying plan? */
1441         Tuplestorestate *tuplestorestate;
1442 } MaterialState;
1443
1444 /* ----------------
1445  *       SortState information
1446  * ----------------
1447  */
1448 typedef struct SortState
1449 {
1450         ScanState       ss;                             /* its first field is NodeTag */
1451         bool            randomAccess;   /* need random access to sort output? */
1452         bool            bounded;                /* is the result set bounded? */
1453         int64           bound;                  /* if bounded, how many tuples are needed */
1454         bool            sort_Done;              /* sort completed yet? */
1455         bool            bounded_Done;   /* value of bounded we did the sort with */
1456         int64           bound_Done;             /* value of bound we did the sort with */
1457         void       *tuplesortstate; /* private state of tuplesort.c */
1458 } SortState;
1459
1460 /* ---------------------
1461  *      GroupState information
1462  * -------------------------
1463  */
1464 typedef struct GroupState
1465 {
1466         ScanState       ss;                             /* its first field is NodeTag */
1467         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1468         bool            grp_done;               /* indicates completion of Group scan */
1469 } GroupState;
1470
1471 /* ---------------------
1472  *      AggState information
1473  *
1474  *      ss.ss_ScanTupleSlot refers to output of underlying plan.
1475  *
1476  *      Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1477  *      ecxt_aggnulls arrays, which hold the computed agg values for the current
1478  *      input group during evaluation of an Agg node's output tuple(s).  We
1479  *      create a second ExprContext, tmpcontext, in which to evaluate input
1480  *      expressions and run the aggregate transition functions.
1481  * -------------------------
1482  */
1483 /* these structs are private in nodeAgg.c: */
1484 typedef struct AggStatePerAggData *AggStatePerAgg;
1485 typedef struct AggStatePerGroupData *AggStatePerGroup;
1486
1487 typedef struct AggState
1488 {
1489         ScanState       ss;                             /* its first field is NodeTag */
1490         List       *aggs;                       /* all Aggref nodes in targetlist & quals */
1491         int                     numaggs;                /* length of list (could be zero!) */
1492         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1493         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1494         AggStatePerAgg peragg;          /* per-Aggref information */
1495         MemoryContext aggcontext;       /* memory context for long-lived data */
1496         ExprContext *tmpcontext;        /* econtext for input expressions */
1497         bool            agg_done;               /* indicates completion of Agg scan */
1498         /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1499         AggStatePerGroup pergroup;      /* per-Aggref-per-group working state */
1500         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1501         /* these fields are used in AGG_HASHED mode: */
1502         TupleHashTable hashtable;       /* hash table with one entry per group */
1503         TupleTableSlot *hashslot;       /* slot for loading hash table */
1504         List       *hash_needed;        /* list of columns needed in hash table */
1505         bool            table_filled;   /* hash table filled yet? */
1506         TupleHashIterator hashiter; /* for iterating through hash table */
1507 } AggState;
1508
1509 /* ----------------
1510  *      WindowAggState information
1511  * ----------------
1512  */
1513 /* these structs are private in nodeWindowAgg.c: */
1514 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1515 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1516
1517 typedef struct WindowAggState
1518 {
1519         ScanState       ss;                                     /* its first field is NodeTag */
1520
1521         /* these fields are filled in by ExecInitExpr: */
1522         List       *funcs;                              /* all WindowFunc nodes in targetlist */
1523         int                     numfuncs;                       /* total number of window functions */
1524         int                     numaggs;                        /* number that are plain aggregates */
1525
1526         WindowStatePerFunc perfunc;             /* per-window-function information */
1527         WindowStatePerAgg peragg;               /* per-plain-aggregate information */
1528         FmgrInfo   *partEqfunctions;    /* equality funcs for partition columns */
1529         FmgrInfo   *ordEqfunctions;             /* equality funcs for ordering columns */
1530         Tuplestorestate    *buffer;             /* stores rows of current partition */
1531         int                     current_ptr;            /* read pointer # for current */
1532         int                     agg_ptr;                        /* read pointer # for aggregates */
1533         int64           spooled_rows;           /* total # of rows in buffer */
1534         int64           currentpos;                     /* position of current row in partition */
1535         int64           frametailpos;           /* current frame tail position */
1536         int64           aggregatedupto;         /* rows before this one are aggregated */
1537
1538         MemoryContext wincontext;               /* context for partition-lifespan data */
1539         ExprContext *tmpcontext;                /* short-term evaluation context */
1540
1541         bool            all_done;                       /* true if the scan is finished */
1542         bool            partition_spooled;      /* true if all tuples in current partition
1543                                                                          * have been spooled into tuplestore */
1544         bool            more_partitions;        /* true if there's more partitions after
1545                                                                          * this one */
1546         bool            frametail_valid;        /* true if frametailpos is known up to date
1547                                                                          * for current row */
1548
1549         TupleTableSlot *first_part_slot;        /* first tuple of current or next
1550                                                                                  * partition */
1551
1552         /* temporary slots for tuples fetched back from tuplestore */
1553         TupleTableSlot *agg_row_slot;
1554         TupleTableSlot *temp_slot_1;
1555         TupleTableSlot *temp_slot_2;
1556 } WindowAggState;
1557
1558 /* ----------------
1559  *       UniqueState information
1560  *
1561  *              Unique nodes are used "on top of" sort nodes to discard
1562  *              duplicate tuples returned from the sort phase.  Basically
1563  *              all it does is compare the current tuple from the subplan
1564  *              with the previously fetched tuple (stored in its result slot).
1565  *              If the two are identical in all interesting fields, then
1566  *              we just fetch another tuple from the sort and try again.
1567  * ----------------
1568  */
1569 typedef struct UniqueState
1570 {
1571         PlanState       ps;                             /* its first field is NodeTag */
1572         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1573         MemoryContext tempContext;      /* short-term context for comparisons */
1574 } UniqueState;
1575
1576 /* ----------------
1577  *       HashState information
1578  * ----------------
1579  */
1580 typedef struct HashState
1581 {
1582         PlanState       ps;                             /* its first field is NodeTag */
1583         HashJoinTable hashtable;        /* hash table for the hashjoin */
1584         List       *hashkeys;           /* list of ExprState nodes */
1585         /* hashkeys is same as parent's hj_InnerHashKeys */
1586 } HashState;
1587
1588 /* ----------------
1589  *       SetOpState information
1590  *
1591  *              Even in "sorted" mode, SetOp nodes are more complex than a simple
1592  *              Unique, since we have to count how many duplicates to return.  But
1593  *              we also support hashing, so this is really more like a cut-down
1594  *              form of Agg.
1595  * ----------------
1596  */
1597 /* this struct is private in nodeSetOp.c: */
1598 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1599
1600 typedef struct SetOpState
1601 {
1602         PlanState       ps;                             /* its first field is NodeTag */
1603         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1604         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1605         bool            setop_done;             /* indicates completion of output scan */
1606         long            numOutput;              /* number of dups left to output */
1607         MemoryContext tempContext;      /* short-term context for comparisons */
1608         /* these fields are used in SETOP_SORTED mode: */
1609         SetOpStatePerGroup pergroup;    /* per-group working state */
1610         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1611         /* these fields are used in SETOP_HASHED mode: */
1612         TupleHashTable hashtable;       /* hash table with one entry per group */
1613         MemoryContext tableContext;     /* memory context containing hash table */
1614         bool            table_filled;   /* hash table filled yet? */
1615         TupleHashIterator hashiter; /* for iterating through hash table */
1616 } SetOpState;
1617
1618 /* ----------------
1619  *       LimitState information
1620  *
1621  *              Limit nodes are used to enforce LIMIT/OFFSET clauses.
1622  *              They just select the desired subrange of their subplan's output.
1623  *
1624  * offset is the number of initial tuples to skip (0 does nothing).
1625  * count is the number of tuples to return after skipping the offset tuples.
1626  * If no limit count was specified, count is undefined and noCount is true.
1627  * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1628  * ----------------
1629  */
1630 typedef enum
1631 {
1632         LIMIT_INITIAL,                          /* initial state for LIMIT node */
1633         LIMIT_RESCAN,                           /* rescan after recomputing parameters */
1634         LIMIT_EMPTY,                            /* there are no returnable rows */
1635         LIMIT_INWINDOW,                         /* have returned a row in the window */
1636         LIMIT_SUBPLANEOF,                       /* at EOF of subplan (within window) */
1637         LIMIT_WINDOWEND,                        /* stepped off end of window */
1638         LIMIT_WINDOWSTART                       /* stepped off beginning of window */
1639 } LimitStateCond;
1640
1641 typedef struct LimitState
1642 {
1643         PlanState       ps;                             /* its first field is NodeTag */
1644         ExprState  *limitOffset;        /* OFFSET parameter, or NULL if none */
1645         ExprState  *limitCount;         /* COUNT parameter, or NULL if none */
1646         int64           offset;                 /* current OFFSET value */
1647         int64           count;                  /* current COUNT, if any */
1648         bool            noCount;                /* if true, ignore count */
1649         LimitStateCond lstate;          /* state machine status, as above */
1650         int64           position;               /* 1-based index of last tuple returned */
1651         TupleTableSlot *subSlot;        /* tuple last obtained from subplan */
1652 } LimitState;
1653
1654 #endif   /* EXECNODES_H */