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