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