]> granicus.if.org Git - postgresql/blob - src/include/nodes/execnodes.h
fec07b8e426e479e10511404bbd198bae7e26282
[postgresql] / src / include / nodes / execnodes.h
1 /*-------------------------------------------------------------------------
2  *
3  * execnodes.h
4  *        definitions for executor state nodes
5  *
6  *
7  * Portions Copyright (c) 1996-2012, 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_finished;    /* true when ExecutorFinish is done */
375
376         List       *es_exprcontexts;    /* List of ExprContexts within EState */
377
378         List       *es_subplanstates;           /* List of PlanState for SubPlans */
379
380         List       *es_auxmodifytables;         /* List of secondary ModifyTableStates */
381
382         /*
383          * this ExprContext is for per-output-tuple operations, such as constraint
384          * checks and index-value computations.  It will be reset for each output
385          * tuple.  Note that it will be created only if needed.
386          */
387         ExprContext *es_per_tuple_exprcontext;
388
389         /*
390          * These fields are for re-evaluating plan quals when an updated tuple is
391          * substituted in READ COMMITTED mode.  es_epqTuple[] contains tuples that
392          * scan plan nodes should return instead of whatever they'd normally
393          * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
394          * particular array entry is valid; and es_epqScanDone[] is state to
395          * remember if the tuple has been returned already.  Arrays are of size
396          * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
397          */
398         HeapTuple  *es_epqTuple;        /* array of EPQ substitute tuples */
399         bool       *es_epqTupleSet; /* true if EPQ tuple is provided */
400         bool       *es_epqScanDone; /* true if EPQ tuple has been fetched */
401 } EState;
402
403
404 /*
405  * ExecRowMark -
406  *         runtime representation of FOR UPDATE/SHARE clauses
407  *
408  * When doing UPDATE, DELETE, or SELECT FOR UPDATE/SHARE, we should have an
409  * ExecRowMark for each non-target relation in the query (except inheritance
410  * parent RTEs, which can be ignored at runtime).  See PlanRowMark for details
411  * about most of the fields.  In addition to fields directly derived from
412  * PlanRowMark, we store curCtid, which is used by the WHERE CURRENT OF code.
413  *
414  * EState->es_rowMarks is a list of these structs.
415  */
416 typedef struct ExecRowMark
417 {
418         Relation        relation;               /* opened and suitably locked relation */
419         Index           rti;                    /* its range table index */
420         Index           prti;                   /* parent range table index, if child */
421         Index           rowmarkId;              /* unique identifier for resjunk columns */
422         RowMarkType markType;           /* see enum in nodes/plannodes.h */
423         bool            noWait;                 /* NOWAIT option */
424         ItemPointerData curCtid;        /* ctid of currently locked tuple, if any */
425 } ExecRowMark;
426
427 /*
428  * ExecAuxRowMark -
429  *         additional runtime representation of FOR UPDATE/SHARE clauses
430  *
431  * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
432  * deal with.  In addition to a pointer to the related entry in es_rowMarks,
433  * this struct carries the column number(s) of the resjunk columns associated
434  * with the rowmark (see comments for PlanRowMark for more detail).  In the
435  * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
436  * each child plan, because the resjunk columns could be at different physical
437  * column positions in different subplans.
438  */
439 typedef struct ExecAuxRowMark
440 {
441         ExecRowMark *rowmark;           /* related entry in es_rowMarks */
442         AttrNumber      ctidAttNo;              /* resno of ctid junk attribute, if any */
443         AttrNumber      toidAttNo;              /* resno of tableoid junk attribute, if any */
444         AttrNumber      wholeAttNo;             /* resno of whole-row junk attribute, if any */
445 } ExecAuxRowMark;
446
447
448 /* ----------------------------------------------------------------
449  *                               Tuple Hash Tables
450  *
451  * All-in-memory tuple hash tables are used for a number of purposes.
452  *
453  * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
454  * and tab_eq_funcs are non-cross-type equality operators for those types.
455  * Normally these are the only functions used, but FindTupleHashEntry()
456  * supports searching a hashtable using cross-data-type hashing.  For that,
457  * the caller must supply hash functions for the LHS datatype as well as
458  * the cross-type equality operators to use.  in_hash_funcs and cur_eq_funcs
459  * are set to point to the caller's function arrays while doing such a search.
460  * During LookupTupleHashEntry(), they point to tab_hash_funcs and
461  * tab_eq_funcs respectively.
462  * ----------------------------------------------------------------
463  */
464 typedef struct TupleHashEntryData *TupleHashEntry;
465 typedef struct TupleHashTableData *TupleHashTable;
466
467 typedef struct TupleHashEntryData
468 {
469         /* firstTuple must be the first field in this struct! */
470         MinimalTuple firstTuple;        /* copy of first tuple in this group */
471         /* there may be additional data beyond the end of this struct */
472 } TupleHashEntryData;                   /* VARIABLE LENGTH STRUCT */
473
474 typedef struct TupleHashTableData
475 {
476         HTAB       *hashtab;            /* underlying dynahash table */
477         int                     numCols;                /* number of columns in lookup key */
478         AttrNumber *keyColIdx;          /* attr numbers of key columns */
479         FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */
480         FmgrInfo   *tab_eq_funcs;       /* equality functions for table datatype(s) */
481         MemoryContext tablecxt;         /* memory context containing table */
482         MemoryContext tempcxt;          /* context for function evaluations */
483         Size            entrysize;              /* actual size to make each hash entry */
484         TupleTableSlot *tableslot;      /* slot for referencing table entries */
485         /* The following fields are set transiently for each table search: */
486         TupleTableSlot *inputslot;      /* current input tuple's slot */
487         FmgrInfo   *in_hash_funcs;      /* hash functions for input datatype(s) */
488         FmgrInfo   *cur_eq_funcs;       /* equality functions for input vs. table */
489 }       TupleHashTableData;
490
491 typedef HASH_SEQ_STATUS TupleHashIterator;
492
493 /*
494  * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
495  * Use ResetTupleHashIterator if the table can be frozen (in this case no
496  * explicit scan termination is needed).
497  */
498 #define InitTupleHashIterator(htable, iter) \
499         hash_seq_init(iter, (htable)->hashtab)
500 #define TermTupleHashIterator(iter) \
501         hash_seq_term(iter)
502 #define ResetTupleHashIterator(htable, iter) \
503         do { \
504                 hash_freeze((htable)->hashtab); \
505                 hash_seq_init(iter, (htable)->hashtab); \
506         } while (0)
507 #define ScanTupleHashTable(iter) \
508         ((TupleHashEntry) hash_seq_search(iter))
509
510
511 /* ----------------------------------------------------------------
512  *                               Expression State Trees
513  *
514  * Each executable expression tree has a parallel ExprState tree.
515  *
516  * Unlike PlanState, there is not an exact one-for-one correspondence between
517  * ExprState node types and Expr node types.  Many Expr node types have no
518  * need for node-type-specific run-time state, and so they can use plain
519  * ExprState or GenericExprState as their associated ExprState node type.
520  * ----------------------------------------------------------------
521  */
522
523 /* ----------------
524  *              ExprState node
525  *
526  * ExprState is the common superclass for all ExprState-type nodes.
527  *
528  * It can also be instantiated directly for leaf Expr nodes that need no
529  * local run-time state (such as Var, Const, or Param).
530  *
531  * To save on dispatch overhead, each ExprState node contains a function
532  * pointer to the routine to execute to evaluate the node.
533  * ----------------
534  */
535
536 typedef struct ExprState ExprState;
537
538 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
539                                                                                                 ExprContext *econtext,
540                                                                                                 bool *isNull,
541                                                                                                 ExprDoneCond *isDone);
542
543 struct ExprState
544 {
545         NodeTag         type;
546         Expr       *expr;                       /* associated Expr node */
547         ExprStateEvalFunc evalfunc; /* routine to run to execute node */
548 };
549
550 /* ----------------
551  *              GenericExprState node
552  *
553  * This is used for Expr node types that need no local run-time state,
554  * but have one child Expr node.
555  * ----------------
556  */
557 typedef struct GenericExprState
558 {
559         ExprState       xprstate;
560         ExprState  *arg;                        /* state of my child node */
561 } GenericExprState;
562
563 /* ----------------
564  *              WholeRowVarExprState node
565  * ----------------
566  */
567 typedef struct WholeRowVarExprState
568 {
569         ExprState       xprstate;
570         struct PlanState *parent;       /* parent PlanState, or NULL if none */
571         JunkFilter *wrv_junkFilter; /* JunkFilter to remove resjunk cols */
572 } WholeRowVarExprState;
573
574 /* ----------------
575  *              AggrefExprState node
576  * ----------------
577  */
578 typedef struct AggrefExprState
579 {
580         ExprState       xprstate;
581         List       *args;                       /* states of argument expressions */
582         int                     aggno;                  /* ID number for agg within its plan node */
583 } AggrefExprState;
584
585 /* ----------------
586  *              WindowFuncExprState node
587  * ----------------
588  */
589 typedef struct WindowFuncExprState
590 {
591         ExprState       xprstate;
592         List       *args;                       /* states of argument expressions */
593         int                     wfuncno;                /* ID number for wfunc within its plan node */
594 } WindowFuncExprState;
595
596 /* ----------------
597  *              ArrayRefExprState node
598  *
599  * Note: array types can be fixed-length (typlen > 0), but only when the
600  * element type is itself fixed-length.  Otherwise they are varlena structures
601  * and have typlen = -1.  In any case, an array type is never pass-by-value.
602  * ----------------
603  */
604 typedef struct ArrayRefExprState
605 {
606         ExprState       xprstate;
607         List       *refupperindexpr;    /* states for child nodes */
608         List       *reflowerindexpr;
609         ExprState  *refexpr;
610         ExprState  *refassgnexpr;
611         int16           refattrlength;  /* typlen of array type */
612         int16           refelemlength;  /* typlen of the array element type */
613         bool            refelembyval;   /* is the element type pass-by-value? */
614         char            refelemalign;   /* typalign of the element type */
615 } ArrayRefExprState;
616
617 /* ----------------
618  *              FuncExprState node
619  *
620  * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
621  * and NullIf nodes; be careful to check what xprstate.expr is actually
622  * pointing at!
623  * ----------------
624  */
625 typedef struct FuncExprState
626 {
627         ExprState       xprstate;
628         List       *args;                       /* states of argument expressions */
629
630         /*
631          * Function manager's lookup info for the target function.  If func.fn_oid
632          * is InvalidOid, we haven't initialized it yet (nor any of the following
633          * fields).
634          */
635         FmgrInfo        func;
636
637         /*
638          * For a set-returning function (SRF) that returns a tuplestore, we keep
639          * the tuplestore here and dole out the result rows one at a time. The
640          * slot holds the row currently being returned.
641          */
642         Tuplestorestate *funcResultStore;
643         TupleTableSlot *funcResultSlot;
644
645         /*
646          * In some cases we need to compute a tuple descriptor for the function's
647          * output.      If so, it's stored here.
648          */
649         TupleDesc       funcResultDesc;
650         bool            funcReturnsTuple;               /* valid when funcResultDesc isn't
651                                                                                  * NULL */
652
653         /*
654          * setArgsValid is true when we are evaluating a set-returning function
655          * that uses value-per-call mode and we are in the middle of a call
656          * series; we want to pass the same argument values to the function again
657          * (and again, until it returns ExprEndResult).  This indicates that
658          * fcinfo_data already contains valid argument data.
659          */
660         bool            setArgsValid;
661
662         /*
663          * Flag to remember whether we found a set-valued argument to the
664          * function. This causes the function result to be a set as well. Valid
665          * only when setArgsValid is true or funcResultStore isn't NULL.
666          */
667         bool            setHasSetArg;   /* some argument returns a set */
668
669         /*
670          * Flag to remember whether we have registered a shutdown callback for
671          * this FuncExprState.  We do so only if funcResultStore or setArgsValid
672          * has been set at least once (since all the callback is for is to release
673          * the tuplestore or clear setArgsValid).
674          */
675         bool            shutdown_reg;   /* a shutdown callback is registered */
676
677         /*
678          * Call parameter structure for the function.  This has been initialized
679          * (by InitFunctionCallInfoData) if func.fn_oid is valid.  It also saves
680          * argument values between calls, when setArgsValid is true.
681          */
682         FunctionCallInfoData fcinfo_data;
683 } FuncExprState;
684
685 /* ----------------
686  *              ScalarArrayOpExprState node
687  *
688  * This is a FuncExprState plus some additional data.
689  * ----------------
690  */
691 typedef struct ScalarArrayOpExprState
692 {
693         FuncExprState fxprstate;
694         /* Cached info about array element type */
695         Oid                     element_type;
696         int16           typlen;
697         bool            typbyval;
698         char            typalign;
699 } ScalarArrayOpExprState;
700
701 /* ----------------
702  *              BoolExprState node
703  * ----------------
704  */
705 typedef struct BoolExprState
706 {
707         ExprState       xprstate;
708         List       *args;                       /* states of argument expression(s) */
709 } BoolExprState;
710
711 /* ----------------
712  *              SubPlanState node
713  * ----------------
714  */
715 typedef struct SubPlanState
716 {
717         ExprState       xprstate;
718         struct PlanState *planstate;    /* subselect plan's state tree */
719         ExprState  *testexpr;           /* state of combining expression */
720         List       *args;                       /* states of argument expression(s) */
721         HeapTuple       curTuple;               /* copy of most recent tuple from subplan */
722         Datum           curArray;               /* most recent array from ARRAY() subplan */
723         /* these are used when hashing the subselect's output: */
724         ProjectionInfo *projLeft;       /* for projecting lefthand exprs */
725         ProjectionInfo *projRight;      /* for projecting subselect output */
726         TupleHashTable hashtable;       /* hash table for no-nulls subselect rows */
727         TupleHashTable hashnulls;       /* hash table for rows with null(s) */
728         bool            havehashrows;   /* TRUE if hashtable is not empty */
729         bool            havenullrows;   /* TRUE if hashnulls is not empty */
730         MemoryContext hashtablecxt; /* memory context containing hash tables */
731         MemoryContext hashtempcxt;      /* temp memory context for hash tables */
732         ExprContext *innerecontext; /* econtext for computing inner tuples */
733         AttrNumber *keyColIdx;          /* control data for hash tables */
734         FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */
735         FmgrInfo   *tab_eq_funcs;       /* equality functions for table datatype(s) */
736         FmgrInfo   *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
737         FmgrInfo   *cur_eq_funcs;       /* equality functions for LHS vs. table */
738 } SubPlanState;
739
740 /* ----------------
741  *              AlternativeSubPlanState node
742  * ----------------
743  */
744 typedef struct AlternativeSubPlanState
745 {
746         ExprState       xprstate;
747         List       *subplans;           /* states of alternative subplans */
748         int                     active;                 /* list index of the one we're using */
749 } AlternativeSubPlanState;
750
751 /* ----------------
752  *              FieldSelectState node
753  * ----------------
754  */
755 typedef struct FieldSelectState
756 {
757         ExprState       xprstate;
758         ExprState  *arg;                        /* input expression */
759         TupleDesc       argdesc;                /* tupdesc for most recent input */
760 } FieldSelectState;
761
762 /* ----------------
763  *              FieldStoreState node
764  * ----------------
765  */
766 typedef struct FieldStoreState
767 {
768         ExprState       xprstate;
769         ExprState  *arg;                        /* input tuple value */
770         List       *newvals;            /* new value(s) for field(s) */
771         TupleDesc       argdesc;                /* tupdesc for most recent input */
772 } FieldStoreState;
773
774 /* ----------------
775  *              CoerceViaIOState node
776  * ----------------
777  */
778 typedef struct CoerceViaIOState
779 {
780         ExprState       xprstate;
781         ExprState  *arg;                        /* input expression */
782         FmgrInfo        outfunc;                /* lookup info for source output function */
783         FmgrInfo        infunc;                 /* lookup info for result input function */
784         Oid                     intypioparam;   /* argument needed for input function */
785 } CoerceViaIOState;
786
787 /* ----------------
788  *              ArrayCoerceExprState node
789  * ----------------
790  */
791 typedef struct ArrayCoerceExprState
792 {
793         ExprState       xprstate;
794         ExprState  *arg;                        /* input array value */
795         Oid                     resultelemtype; /* element type of result array */
796         FmgrInfo        elemfunc;               /* lookup info for element coercion function */
797         /* use struct pointer to avoid including array.h here */
798         struct ArrayMapState *amstate;          /* workspace for array_map */
799 } ArrayCoerceExprState;
800
801 /* ----------------
802  *              ConvertRowtypeExprState node
803  * ----------------
804  */
805 typedef struct ConvertRowtypeExprState
806 {
807         ExprState       xprstate;
808         ExprState  *arg;                        /* input tuple value */
809         TupleDesc       indesc;                 /* tupdesc for source rowtype */
810         TupleDesc       outdesc;                /* tupdesc for result rowtype */
811         /* use "struct" so we needn't include tupconvert.h here */
812         struct TupleConversionMap *map;
813         bool            initialized;
814 } ConvertRowtypeExprState;
815
816 /* ----------------
817  *              CaseExprState node
818  * ----------------
819  */
820 typedef struct CaseExprState
821 {
822         ExprState       xprstate;
823         ExprState  *arg;                        /* implicit equality comparison argument */
824         List       *args;                       /* the arguments (list of WHEN clauses) */
825         ExprState  *defresult;          /* the default result (ELSE clause) */
826 } CaseExprState;
827
828 /* ----------------
829  *              CaseWhenState node
830  * ----------------
831  */
832 typedef struct CaseWhenState
833 {
834         ExprState       xprstate;
835         ExprState  *expr;                       /* condition expression */
836         ExprState  *result;                     /* substitution result */
837 } CaseWhenState;
838
839 /* ----------------
840  *              ArrayExprState node
841  *
842  * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
843  * arrays.
844  * ----------------
845  */
846 typedef struct ArrayExprState
847 {
848         ExprState       xprstate;
849         List       *elements;           /* states for child nodes */
850         int16           elemlength;             /* typlen of the array element type */
851         bool            elembyval;              /* is the element type pass-by-value? */
852         char            elemalign;              /* typalign of the element type */
853 } ArrayExprState;
854
855 /* ----------------
856  *              RowExprState node
857  * ----------------
858  */
859 typedef struct RowExprState
860 {
861         ExprState       xprstate;
862         List       *args;                       /* the arguments */
863         TupleDesc       tupdesc;                /* descriptor for result tuples */
864 } RowExprState;
865
866 /* ----------------
867  *              RowCompareExprState node
868  * ----------------
869  */
870 typedef struct RowCompareExprState
871 {
872         ExprState       xprstate;
873         List       *largs;                      /* the left-hand input arguments */
874         List       *rargs;                      /* the right-hand input arguments */
875         FmgrInfo   *funcs;                      /* array of comparison function info */
876         Oid                *collations;         /* array of collations to use */
877 } RowCompareExprState;
878
879 /* ----------------
880  *              CoalesceExprState node
881  * ----------------
882  */
883 typedef struct CoalesceExprState
884 {
885         ExprState       xprstate;
886         List       *args;                       /* the arguments */
887 } CoalesceExprState;
888
889 /* ----------------
890  *              MinMaxExprState node
891  * ----------------
892  */
893 typedef struct MinMaxExprState
894 {
895         ExprState       xprstate;
896         List       *args;                       /* the arguments */
897         FmgrInfo        cfunc;                  /* lookup info for comparison func */
898 } MinMaxExprState;
899
900 /* ----------------
901  *              XmlExprState node
902  * ----------------
903  */
904 typedef struct XmlExprState
905 {
906         ExprState       xprstate;
907         List       *named_args;         /* ExprStates for named arguments */
908         List       *args;                       /* ExprStates for other arguments */
909 } XmlExprState;
910
911 /* ----------------
912  *              NullTestState node
913  * ----------------
914  */
915 typedef struct NullTestState
916 {
917         ExprState       xprstate;
918         ExprState  *arg;                        /* input expression */
919         /* used only if input is of composite type: */
920         TupleDesc       argdesc;                /* tupdesc for most recent input */
921 } NullTestState;
922
923 /* ----------------
924  *              CoerceToDomainState node
925  * ----------------
926  */
927 typedef struct CoerceToDomainState
928 {
929         ExprState       xprstate;
930         ExprState  *arg;                        /* input expression */
931         /* Cached list of constraints that need to be checked */
932         List       *constraints;        /* list of DomainConstraintState nodes */
933 } CoerceToDomainState;
934
935 /*
936  * DomainConstraintState - one item to check during CoerceToDomain
937  *
938  * Note: this is just a Node, and not an ExprState, because it has no
939  * corresponding Expr to link to.  Nonetheless it is part of an ExprState
940  * tree, so we give it a name following the xxxState convention.
941  */
942 typedef enum DomainConstraintType
943 {
944         DOM_CONSTRAINT_NOTNULL,
945         DOM_CONSTRAINT_CHECK
946 } DomainConstraintType;
947
948 typedef struct DomainConstraintState
949 {
950         NodeTag         type;
951         DomainConstraintType constrainttype;            /* constraint type */
952         char       *name;                       /* name of constraint (for error msgs) */
953         ExprState  *check_expr;         /* for CHECK, a boolean expression */
954 } DomainConstraintState;
955
956
957 /* ----------------------------------------------------------------
958  *                               Executor State Trees
959  *
960  * An executing query has a PlanState tree paralleling the Plan tree
961  * that describes the plan.
962  * ----------------------------------------------------------------
963  */
964
965 /* ----------------
966  *              PlanState node
967  *
968  * We never actually instantiate any PlanState nodes; this is just the common
969  * abstract superclass for all PlanState-type nodes.
970  * ----------------
971  */
972 typedef struct PlanState
973 {
974         NodeTag         type;
975
976         Plan       *plan;                       /* associated Plan node */
977
978         EState     *state;                      /* at execution time, states of individual
979                                                                  * nodes point to one EState for the whole
980                                                                  * top-level plan */
981
982         Instrumentation *instrument;    /* Optional runtime stats for this node */
983
984         /*
985          * Common structural data for all Plan types.  These links to subsidiary
986          * state trees parallel links in the associated plan tree (except for the
987          * subPlan list, which does not exist in the plan tree).
988          */
989         List       *targetlist;         /* target list to be computed at this node */
990         List       *qual;                       /* implicitly-ANDed qual conditions */
991         struct PlanState *lefttree; /* input plan tree(s) */
992         struct PlanState *righttree;
993         List       *initPlan;           /* Init SubPlanState nodes (un-correlated expr
994                                                                  * subselects) */
995         List       *subPlan;            /* SubPlanState nodes in my expressions */
996
997         /*
998          * State for management of parameter-change-driven rescanning
999          */
1000         Bitmapset  *chgParam;           /* set of IDs of changed Params */
1001
1002         /*
1003          * Other run-time state needed by most if not all node types.
1004          */
1005         TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
1006         ExprContext *ps_ExprContext;    /* node's expression-evaluation context */
1007         ProjectionInfo *ps_ProjInfo;    /* info for doing tuple projection */
1008         bool            ps_TupFromTlist;/* state flag for processing set-valued
1009                                                                  * functions in targetlist */
1010 } PlanState;
1011
1012 /* ----------------
1013  *      these are defined to avoid confusion problems with "left"
1014  *      and "right" and "inner" and "outer".  The convention is that
1015  *      the "left" plan is the "outer" plan and the "right" plan is
1016  *      the inner plan, but these make the code more readable.
1017  * ----------------
1018  */
1019 #define innerPlanState(node)            (((PlanState *)(node))->righttree)
1020 #define outerPlanState(node)            (((PlanState *)(node))->lefttree)
1021
1022 /* Macros for inline access to certain instrumentation counters */
1023 #define InstrCountFiltered1(node, delta) \
1024         do { \
1025                 if (((PlanState *)(node))->instrument) \
1026                         ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
1027         } while(0)
1028 #define InstrCountFiltered2(node, delta) \
1029         do { \
1030                 if (((PlanState *)(node))->instrument) \
1031                         ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
1032         } while(0)
1033
1034 /*
1035  * EPQState is state for executing an EvalPlanQual recheck on a candidate
1036  * tuple in ModifyTable or LockRows.  The estate and planstate fields are
1037  * NULL if inactive.
1038  */
1039 typedef struct EPQState
1040 {
1041         EState     *estate;                     /* subsidiary EState */
1042         PlanState  *planstate;          /* plan state tree ready to be executed */
1043         TupleTableSlot *origslot;       /* original output tuple to be rechecked */
1044         Plan       *plan;                       /* plan tree to be executed */
1045         List       *arowMarks;          /* ExecAuxRowMarks (non-locking only) */
1046         int                     epqParam;               /* ID of Param to force scan node re-eval */
1047 } EPQState;
1048
1049
1050 /* ----------------
1051  *       ResultState information
1052  * ----------------
1053  */
1054 typedef struct ResultState
1055 {
1056         PlanState       ps;                             /* its first field is NodeTag */
1057         ExprState  *resconstantqual;
1058         bool            rs_done;                /* are we done? */
1059         bool            rs_checkqual;   /* do we need to check the qual? */
1060 } ResultState;
1061
1062 /* ----------------
1063  *       ModifyTableState information
1064  * ----------------
1065  */
1066 typedef struct ModifyTableState
1067 {
1068         PlanState       ps;                             /* its first field is NodeTag */
1069         CmdType         operation;              /* INSERT, UPDATE, or DELETE */
1070         bool            canSetTag;              /* do we set the command tag/es_processed? */
1071         bool            mt_done;                /* are we done? */
1072         PlanState **mt_plans;           /* subplans (one per target rel) */
1073         int                     mt_nplans;              /* number of plans in the array */
1074         int                     mt_whichplan;   /* which one is being executed (0..n-1) */
1075         ResultRelInfo *resultRelInfo;           /* per-subplan target relations */
1076         List      **mt_arowmarks;       /* per-subplan ExecAuxRowMark lists */
1077         EPQState        mt_epqstate;    /* for evaluating EvalPlanQual rechecks */
1078         bool            fireBSTriggers; /* do we need to fire stmt triggers? */
1079 } ModifyTableState;
1080
1081 /* ----------------
1082  *       AppendState information
1083  *
1084  *              nplans                  how many plans are in the array
1085  *              whichplan               which plan is being executed (0 .. n-1)
1086  * ----------------
1087  */
1088 typedef struct AppendState
1089 {
1090         PlanState       ps;                             /* its first field is NodeTag */
1091         PlanState **appendplans;        /* array of PlanStates for my inputs */
1092         int                     as_nplans;
1093         int                     as_whichplan;
1094 } AppendState;
1095
1096 /* ----------------
1097  *       MergeAppendState information
1098  *
1099  *              nplans                  how many plans are in the array
1100  *              nkeys                   number of sort key columns
1101  *              sortkeys                sort keys in SortSupport representation
1102  *              slots                   current output tuple of each subplan
1103  *              heap                    heap of active tuples (represented as array indexes)
1104  *              heap_size               number of active heap entries
1105  *              initialized             true if we have fetched first tuple from each subplan
1106  *              last_slot               last subplan fetched from (which must be re-called)
1107  * ----------------
1108  */
1109 typedef struct MergeAppendState
1110 {
1111         PlanState       ps;                             /* its first field is NodeTag */
1112         PlanState **mergeplans;         /* array of PlanStates for my inputs */
1113         int                     ms_nplans;
1114         int                     ms_nkeys;
1115         SortSupport ms_sortkeys;        /* array of length ms_nkeys */
1116         TupleTableSlot **ms_slots;      /* array of length ms_nplans */
1117         int                *ms_heap;            /* array of length ms_nplans */
1118         int                     ms_heap_size;   /* current active length of ms_heap[] */
1119         bool            ms_initialized; /* are subplans started? */
1120         int                     ms_last_slot;   /* last subplan slot we returned from */
1121 } MergeAppendState;
1122
1123 /* ----------------
1124  *       RecursiveUnionState information
1125  *
1126  *              RecursiveUnionState is used for performing a recursive union.
1127  *
1128  *              recursing                       T when we're done scanning the non-recursive term
1129  *              intermediate_empty      T if intermediate_table is currently empty
1130  *              working_table           working table (to be scanned by recursive term)
1131  *              intermediate_table      current recursive output (next generation of WT)
1132  * ----------------
1133  */
1134 typedef struct RecursiveUnionState
1135 {
1136         PlanState       ps;                             /* its first field is NodeTag */
1137         bool            recursing;
1138         bool            intermediate_empty;
1139         Tuplestorestate *working_table;
1140         Tuplestorestate *intermediate_table;
1141         /* Remaining fields are unused in UNION ALL case */
1142         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1143         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1144         MemoryContext tempContext;      /* short-term context for comparisons */
1145         TupleHashTable hashtable;       /* hash table for tuples already seen */
1146         MemoryContext tableContext; /* memory context containing hash table */
1147 } RecursiveUnionState;
1148
1149 /* ----------------
1150  *       BitmapAndState information
1151  * ----------------
1152  */
1153 typedef struct BitmapAndState
1154 {
1155         PlanState       ps;                             /* its first field is NodeTag */
1156         PlanState **bitmapplans;        /* array of PlanStates for my inputs */
1157         int                     nplans;                 /* number of input plans */
1158 } BitmapAndState;
1159
1160 /* ----------------
1161  *       BitmapOrState information
1162  * ----------------
1163  */
1164 typedef struct BitmapOrState
1165 {
1166         PlanState       ps;                             /* its first field is NodeTag */
1167         PlanState **bitmapplans;        /* array of PlanStates for my inputs */
1168         int                     nplans;                 /* number of input plans */
1169 } BitmapOrState;
1170
1171 /* ----------------------------------------------------------------
1172  *                               Scan State Information
1173  * ----------------------------------------------------------------
1174  */
1175
1176 /* ----------------
1177  *       ScanState information
1178  *
1179  *              ScanState extends PlanState for node types that represent
1180  *              scans of an underlying relation.  It can also be used for nodes
1181  *              that scan the output of an underlying plan node --- in that case,
1182  *              only ScanTupleSlot is actually useful, and it refers to the tuple
1183  *              retrieved from the subplan.
1184  *
1185  *              currentRelation    relation being scanned (NULL if none)
1186  *              currentScanDesc    current scan descriptor for scan (NULL if none)
1187  *              ScanTupleSlot      pointer to slot in tuple table holding scan tuple
1188  * ----------------
1189  */
1190 typedef struct ScanState
1191 {
1192         PlanState       ps;                             /* its first field is NodeTag */
1193         Relation        ss_currentRelation;
1194         HeapScanDesc ss_currentScanDesc;
1195         TupleTableSlot *ss_ScanTupleSlot;
1196 } ScanState;
1197
1198 /*
1199  * SeqScan uses a bare ScanState as its state node, since it needs
1200  * no additional fields.
1201  */
1202 typedef ScanState SeqScanState;
1203
1204 /*
1205  * These structs store information about index quals that don't have simple
1206  * constant right-hand sides.  See comments for ExecIndexBuildScanKeys()
1207  * for discussion.
1208  */
1209 typedef struct
1210 {
1211         ScanKey         scan_key;               /* scankey to put value into */
1212         ExprState  *key_expr;           /* expr to evaluate to get value */
1213         bool            key_toastable;  /* is expr's result a toastable datatype? */
1214 } IndexRuntimeKeyInfo;
1215
1216 typedef struct
1217 {
1218         ScanKey         scan_key;               /* scankey to put value into */
1219         ExprState  *array_expr;         /* expr to evaluate to get array value */
1220         int                     next_elem;              /* next array element to use */
1221         int                     num_elems;              /* number of elems in current array value */
1222         Datum      *elem_values;        /* array of num_elems Datums */
1223         bool       *elem_nulls;         /* array of num_elems is-null flags */
1224 } IndexArrayKeyInfo;
1225
1226 /* ----------------
1227  *       IndexScanState information
1228  *
1229  *              indexqualorig      execution state for indexqualorig expressions
1230  *              ScanKeys                   Skey structures for index quals
1231  *              NumScanKeys                number of ScanKeys
1232  *              OrderByKeys                Skey structures for index ordering operators
1233  *              NumOrderByKeys     number of OrderByKeys
1234  *              RuntimeKeys                info about Skeys that must be evaluated at runtime
1235  *              NumRuntimeKeys     number of RuntimeKeys
1236  *              RuntimeKeysReady   true if runtime Skeys have been computed
1237  *              RuntimeContext     expr context for evaling runtime Skeys
1238  *              RelationDesc       index relation descriptor
1239  *              ScanDesc                   index scan descriptor
1240  * ----------------
1241  */
1242 typedef struct IndexScanState
1243 {
1244         ScanState       ss;                             /* its first field is NodeTag */
1245         List       *indexqualorig;
1246         ScanKey         iss_ScanKeys;
1247         int                     iss_NumScanKeys;
1248         ScanKey         iss_OrderByKeys;
1249         int                     iss_NumOrderByKeys;
1250         IndexRuntimeKeyInfo *iss_RuntimeKeys;
1251         int                     iss_NumRuntimeKeys;
1252         bool            iss_RuntimeKeysReady;
1253         ExprContext *iss_RuntimeContext;
1254         Relation        iss_RelationDesc;
1255         IndexScanDesc iss_ScanDesc;
1256 } IndexScanState;
1257
1258 /* ----------------
1259  *       IndexOnlyScanState information
1260  *
1261  *              indexqual                  execution state for indexqual expressions
1262  *              ScanKeys                   Skey structures for index quals
1263  *              NumScanKeys                number of ScanKeys
1264  *              OrderByKeys                Skey structures for index ordering operators
1265  *              NumOrderByKeys     number of OrderByKeys
1266  *              RuntimeKeys                info about Skeys that must be evaluated at runtime
1267  *              NumRuntimeKeys     number of RuntimeKeys
1268  *              RuntimeKeysReady   true if runtime Skeys have been computed
1269  *              RuntimeContext     expr context for evaling runtime Skeys
1270  *              RelationDesc       index relation descriptor
1271  *              ScanDesc                   index scan descriptor
1272  *              VMBuffer                   buffer in use for visibility map testing, if any
1273  *              HeapFetches                number of tuples we were forced to fetch from heap
1274  * ----------------
1275  */
1276 typedef struct IndexOnlyScanState
1277 {
1278         ScanState       ss;                             /* its first field is NodeTag */
1279         List       *indexqual;
1280         ScanKey         ioss_ScanKeys;
1281         int                     ioss_NumScanKeys;
1282         ScanKey         ioss_OrderByKeys;
1283         int                     ioss_NumOrderByKeys;
1284         IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1285         int                     ioss_NumRuntimeKeys;
1286         bool            ioss_RuntimeKeysReady;
1287         ExprContext *ioss_RuntimeContext;
1288         Relation        ioss_RelationDesc;
1289         IndexScanDesc ioss_ScanDesc;
1290         Buffer          ioss_VMBuffer;
1291         long            ioss_HeapFetches;
1292 } IndexOnlyScanState;
1293
1294 /* ----------------
1295  *       BitmapIndexScanState information
1296  *
1297  *              result                     bitmap to return output into, or NULL
1298  *              ScanKeys                   Skey structures for index quals
1299  *              NumScanKeys                number of ScanKeys
1300  *              RuntimeKeys                info about Skeys that must be evaluated at runtime
1301  *              NumRuntimeKeys     number of RuntimeKeys
1302  *              ArrayKeys                  info about Skeys that come from ScalarArrayOpExprs
1303  *              NumArrayKeys       number of ArrayKeys
1304  *              RuntimeKeysReady   true if runtime Skeys have been computed
1305  *              RuntimeContext     expr context for evaling runtime Skeys
1306  *              RelationDesc       index relation descriptor
1307  *              ScanDesc                   index scan descriptor
1308  * ----------------
1309  */
1310 typedef struct BitmapIndexScanState
1311 {
1312         ScanState       ss;                             /* its first field is NodeTag */
1313         TIDBitmap  *biss_result;
1314         ScanKey         biss_ScanKeys;
1315         int                     biss_NumScanKeys;
1316         IndexRuntimeKeyInfo *biss_RuntimeKeys;
1317         int                     biss_NumRuntimeKeys;
1318         IndexArrayKeyInfo *biss_ArrayKeys;
1319         int                     biss_NumArrayKeys;
1320         bool            biss_RuntimeKeysReady;
1321         ExprContext *biss_RuntimeContext;
1322         Relation        biss_RelationDesc;
1323         IndexScanDesc biss_ScanDesc;
1324 } BitmapIndexScanState;
1325
1326 /* ----------------
1327  *       BitmapHeapScanState information
1328  *
1329  *              bitmapqualorig     execution state for bitmapqualorig expressions
1330  *              tbm                                bitmap obtained from child index scan(s)
1331  *              tbmiterator                iterator for scanning current pages
1332  *              tbmres                     current-page data
1333  *              prefetch_iterator  iterator for prefetching ahead of current page
1334  *              prefetch_pages     # pages prefetch iterator is ahead of current
1335  *              prefetch_target    target prefetch distance
1336  * ----------------
1337  */
1338 typedef struct BitmapHeapScanState
1339 {
1340         ScanState       ss;                             /* its first field is NodeTag */
1341         List       *bitmapqualorig;
1342         TIDBitmap  *tbm;
1343         TBMIterator *tbmiterator;
1344         TBMIterateResult *tbmres;
1345         TBMIterator *prefetch_iterator;
1346         int                     prefetch_pages;
1347         int                     prefetch_target;
1348 } BitmapHeapScanState;
1349
1350 /* ----------------
1351  *       TidScanState information
1352  *
1353  *              isCurrentOf    scan has a CurrentOfExpr qual
1354  *              NumTids            number of tids in this scan
1355  *              TidPtr             index of currently fetched tid
1356  *              TidList            evaluated item pointers (array of size NumTids)
1357  * ----------------
1358  */
1359 typedef struct TidScanState
1360 {
1361         ScanState       ss;                             /* its first field is NodeTag */
1362         List       *tss_tidquals;       /* list of ExprState nodes */
1363         bool            tss_isCurrentOf;
1364         int                     tss_NumTids;
1365         int                     tss_TidPtr;
1366         int                     tss_MarkTidPtr;
1367         ItemPointerData *tss_TidList;
1368         HeapTupleData tss_htup;
1369 } TidScanState;
1370
1371 /* ----------------
1372  *       SubqueryScanState information
1373  *
1374  *              SubqueryScanState is used for scanning a sub-query in the range table.
1375  *              ScanTupleSlot references the current output tuple of the sub-query.
1376  * ----------------
1377  */
1378 typedef struct SubqueryScanState
1379 {
1380         ScanState       ss;                             /* its first field is NodeTag */
1381         PlanState  *subplan;
1382 } SubqueryScanState;
1383
1384 /* ----------------
1385  *       FunctionScanState information
1386  *
1387  *              Function nodes are used to scan the results of a
1388  *              function appearing in FROM (typically a function returning set).
1389  *
1390  *              eflags                          node's capability flags
1391  *              tupdesc                         expected return tuple description
1392  *              tuplestorestate         private state of tuplestore.c
1393  *              funcexpr                        state for function expression being evaluated
1394  * ----------------
1395  */
1396 typedef struct FunctionScanState
1397 {
1398         ScanState       ss;                             /* its first field is NodeTag */
1399         int                     eflags;
1400         TupleDesc       tupdesc;
1401         Tuplestorestate *tuplestorestate;
1402         ExprState  *funcexpr;
1403 } FunctionScanState;
1404
1405 /* ----------------
1406  *       ValuesScanState information
1407  *
1408  *              ValuesScan nodes are used to scan the results of a VALUES list
1409  *
1410  *              rowcontext                      per-expression-list context
1411  *              exprlists                       array of expression lists being evaluated
1412  *              array_len                       size of array
1413  *              curr_idx                        current array index (0-based)
1414  *              marked_idx                      marked position (for mark/restore)
1415  *
1416  *      Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1417  *      expressions attached to the node.  We create a second ExprContext,
1418  *      rowcontext, in which to build the executor expression state for each
1419  *      Values sublist.  Resetting this context lets us get rid of expression
1420  *      state for each row, avoiding major memory leakage over a long values list.
1421  * ----------------
1422  */
1423 typedef struct ValuesScanState
1424 {
1425         ScanState       ss;                             /* its first field is NodeTag */
1426         ExprContext *rowcontext;
1427         List      **exprlists;
1428         int                     array_len;
1429         int                     curr_idx;
1430         int                     marked_idx;
1431 } ValuesScanState;
1432
1433 /* ----------------
1434  *       CteScanState information
1435  *
1436  *              CteScan nodes are used to scan a CommonTableExpr query.
1437  *
1438  * Multiple CteScan nodes can read out from the same CTE query.  We use
1439  * a tuplestore to hold rows that have been read from the CTE query but
1440  * not yet consumed by all readers.
1441  * ----------------
1442  */
1443 typedef struct CteScanState
1444 {
1445         ScanState       ss;                             /* its first field is NodeTag */
1446         int                     eflags;                 /* capability flags to pass to tuplestore */
1447         int                     readptr;                /* index of my tuplestore read pointer */
1448         PlanState  *cteplanstate;       /* PlanState for the CTE query itself */
1449         /* Link to the "leader" CteScanState (possibly this same node) */
1450         struct CteScanState *leader;
1451         /* The remaining fields are only valid in the "leader" CteScanState */
1452         Tuplestorestate *cte_table; /* rows already read from the CTE query */
1453         bool            eof_cte;                /* reached end of CTE query? */
1454 } CteScanState;
1455
1456 /* ----------------
1457  *       WorkTableScanState information
1458  *
1459  *              WorkTableScan nodes are used to scan the work table created by
1460  *              a RecursiveUnion node.  We locate the RecursiveUnion node
1461  *              during executor startup.
1462  * ----------------
1463  */
1464 typedef struct WorkTableScanState
1465 {
1466         ScanState       ss;                             /* its first field is NodeTag */
1467         RecursiveUnionState *rustate;
1468 } WorkTableScanState;
1469
1470 /* ----------------
1471  *       ForeignScanState information
1472  *
1473  *              ForeignScan nodes are used to scan foreign-data tables.
1474  * ----------------
1475  */
1476 typedef struct ForeignScanState
1477 {
1478         ScanState       ss;                             /* its first field is NodeTag */
1479         /* use struct pointer to avoid including fdwapi.h here */
1480         struct FdwRoutine *fdwroutine;
1481         void       *fdw_state;          /* foreign-data wrapper can keep state here */
1482 } ForeignScanState;
1483
1484 /* ----------------------------------------------------------------
1485  *                               Join State Information
1486  * ----------------------------------------------------------------
1487  */
1488
1489 /* ----------------
1490  *       JoinState information
1491  *
1492  *              Superclass for state nodes of join plans.
1493  * ----------------
1494  */
1495 typedef struct JoinState
1496 {
1497         PlanState       ps;
1498         JoinType        jointype;
1499         List       *joinqual;           /* JOIN quals (in addition to ps.qual) */
1500 } JoinState;
1501
1502 /* ----------------
1503  *       NestLoopState information
1504  *
1505  *              NeedNewOuter       true if need new outer tuple on next call
1506  *              MatchedOuter       true if found a join match for current outer tuple
1507  *              NullInnerTupleSlot prepared null tuple for left outer joins
1508  * ----------------
1509  */
1510 typedef struct NestLoopState
1511 {
1512         JoinState       js;                             /* its first field is NodeTag */
1513         bool            nl_NeedNewOuter;
1514         bool            nl_MatchedOuter;
1515         TupleTableSlot *nl_NullInnerTupleSlot;
1516 } NestLoopState;
1517
1518 /* ----------------
1519  *       MergeJoinState information
1520  *
1521  *              NumClauses                 number of mergejoinable join clauses
1522  *              Clauses                    info for each mergejoinable clause
1523  *              JoinState                  current state of ExecMergeJoin state machine
1524  *              ExtraMarks                 true to issue extra Mark operations on inner scan
1525  *              ConstFalseJoin     true if we have a constant-false joinqual
1526  *              FillOuter                  true if should emit unjoined outer tuples anyway
1527  *              FillInner                  true if should emit unjoined inner tuples anyway
1528  *              MatchedOuter       true if found a join match for current outer tuple
1529  *              MatchedInner       true if found a join match for current inner tuple
1530  *              OuterTupleSlot     slot in tuple table for cur outer tuple
1531  *              InnerTupleSlot     slot in tuple table for cur inner tuple
1532  *              MarkedTupleSlot    slot in tuple table for marked tuple
1533  *              NullOuterTupleSlot prepared null tuple for right outer joins
1534  *              NullInnerTupleSlot prepared null tuple for left outer joins
1535  *              OuterEContext      workspace for computing outer tuple's join values
1536  *              InnerEContext      workspace for computing inner tuple's join values
1537  * ----------------
1538  */
1539 /* private in nodeMergejoin.c: */
1540 typedef struct MergeJoinClauseData *MergeJoinClause;
1541
1542 typedef struct MergeJoinState
1543 {
1544         JoinState       js;                             /* its first field is NodeTag */
1545         int                     mj_NumClauses;
1546         MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1547         int                     mj_JoinState;
1548         bool            mj_ExtraMarks;
1549         bool            mj_ConstFalseJoin;
1550         bool            mj_FillOuter;
1551         bool            mj_FillInner;
1552         bool            mj_MatchedOuter;
1553         bool            mj_MatchedInner;
1554         TupleTableSlot *mj_OuterTupleSlot;
1555         TupleTableSlot *mj_InnerTupleSlot;
1556         TupleTableSlot *mj_MarkedTupleSlot;
1557         TupleTableSlot *mj_NullOuterTupleSlot;
1558         TupleTableSlot *mj_NullInnerTupleSlot;
1559         ExprContext *mj_OuterEContext;
1560         ExprContext *mj_InnerEContext;
1561 } MergeJoinState;
1562
1563 /* ----------------
1564  *       HashJoinState information
1565  *
1566  *              hashclauses                             original form of the hashjoin condition
1567  *              hj_OuterHashKeys                the outer hash keys in the hashjoin condition
1568  *              hj_InnerHashKeys                the inner hash keys in the hashjoin condition
1569  *              hj_HashOperators                the join operators in the hashjoin condition
1570  *              hj_HashTable                    hash table for the hashjoin
1571  *                                                              (NULL if table not built yet)
1572  *              hj_CurHashValue                 hash value for current outer tuple
1573  *              hj_CurBucketNo                  regular bucket# for current outer tuple
1574  *              hj_CurSkewBucketNo              skew bucket# for current outer tuple
1575  *              hj_CurTuple                             last inner tuple matched to current outer
1576  *                                                              tuple, or NULL if starting search
1577  *                                                              (hj_CurXXX variables are undefined if
1578  *                                                              OuterTupleSlot is empty!)
1579  *              hj_OuterTupleSlot               tuple slot for outer tuples
1580  *              hj_HashTupleSlot                tuple slot for inner (hashed) tuples
1581  *              hj_NullOuterTupleSlot   prepared null tuple for right/full outer joins
1582  *              hj_NullInnerTupleSlot   prepared null tuple for left/full outer joins
1583  *              hj_FirstOuterTupleSlot  first tuple retrieved from outer plan
1584  *              hj_JoinState                    current state of ExecHashJoin state machine
1585  *              hj_MatchedOuter                 true if found a join match for current outer
1586  *              hj_OuterNotEmpty                true if outer relation known not empty
1587  * ----------------
1588  */
1589
1590 /* these structs are defined in executor/hashjoin.h: */
1591 typedef struct HashJoinTupleData *HashJoinTuple;
1592 typedef struct HashJoinTableData *HashJoinTable;
1593
1594 typedef struct HashJoinState
1595 {
1596         JoinState       js;                             /* its first field is NodeTag */
1597         List       *hashclauses;        /* list of ExprState nodes */
1598         List       *hj_OuterHashKeys;           /* list of ExprState nodes */
1599         List       *hj_InnerHashKeys;           /* list of ExprState nodes */
1600         List       *hj_HashOperators;           /* list of operator OIDs */
1601         HashJoinTable hj_HashTable;
1602         uint32          hj_CurHashValue;
1603         int                     hj_CurBucketNo;
1604         int                     hj_CurSkewBucketNo;
1605         HashJoinTuple hj_CurTuple;
1606         TupleTableSlot *hj_OuterTupleSlot;
1607         TupleTableSlot *hj_HashTupleSlot;
1608         TupleTableSlot *hj_NullOuterTupleSlot;
1609         TupleTableSlot *hj_NullInnerTupleSlot;
1610         TupleTableSlot *hj_FirstOuterTupleSlot;
1611         int                     hj_JoinState;
1612         bool            hj_MatchedOuter;
1613         bool            hj_OuterNotEmpty;
1614 } HashJoinState;
1615
1616
1617 /* ----------------------------------------------------------------
1618  *                               Materialization State Information
1619  * ----------------------------------------------------------------
1620  */
1621
1622 /* ----------------
1623  *       MaterialState information
1624  *
1625  *              materialize nodes are used to materialize the results
1626  *              of a subplan into a temporary file.
1627  *
1628  *              ss.ss_ScanTupleSlot refers to output of underlying plan.
1629  * ----------------
1630  */
1631 typedef struct MaterialState
1632 {
1633         ScanState       ss;                             /* its first field is NodeTag */
1634         int                     eflags;                 /* capability flags to pass to tuplestore */
1635         bool            eof_underlying; /* reached end of underlying plan? */
1636         Tuplestorestate *tuplestorestate;
1637 } MaterialState;
1638
1639 /* ----------------
1640  *       SortState information
1641  * ----------------
1642  */
1643 typedef struct SortState
1644 {
1645         ScanState       ss;                             /* its first field is NodeTag */
1646         bool            randomAccess;   /* need random access to sort output? */
1647         bool            bounded;                /* is the result set bounded? */
1648         int64           bound;                  /* if bounded, how many tuples are needed */
1649         bool            sort_Done;              /* sort completed yet? */
1650         bool            bounded_Done;   /* value of bounded we did the sort with */
1651         int64           bound_Done;             /* value of bound we did the sort with */
1652         void       *tuplesortstate; /* private state of tuplesort.c */
1653 } SortState;
1654
1655 /* ---------------------
1656  *      GroupState information
1657  * -------------------------
1658  */
1659 typedef struct GroupState
1660 {
1661         ScanState       ss;                             /* its first field is NodeTag */
1662         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1663         bool            grp_done;               /* indicates completion of Group scan */
1664 } GroupState;
1665
1666 /* ---------------------
1667  *      AggState information
1668  *
1669  *      ss.ss_ScanTupleSlot refers to output of underlying plan.
1670  *
1671  *      Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1672  *      ecxt_aggnulls arrays, which hold the computed agg values for the current
1673  *      input group during evaluation of an Agg node's output tuple(s).  We
1674  *      create a second ExprContext, tmpcontext, in which to evaluate input
1675  *      expressions and run the aggregate transition functions.
1676  * -------------------------
1677  */
1678 /* these structs are private in nodeAgg.c: */
1679 typedef struct AggStatePerAggData *AggStatePerAgg;
1680 typedef struct AggStatePerGroupData *AggStatePerGroup;
1681
1682 typedef struct AggState
1683 {
1684         ScanState       ss;                             /* its first field is NodeTag */
1685         List       *aggs;                       /* all Aggref nodes in targetlist & quals */
1686         int                     numaggs;                /* length of list (could be zero!) */
1687         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1688         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1689         AggStatePerAgg peragg;          /* per-Aggref information */
1690         MemoryContext aggcontext;       /* memory context for long-lived data */
1691         ExprContext *tmpcontext;        /* econtext for input expressions */
1692         bool            agg_done;               /* indicates completion of Agg scan */
1693         /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1694         AggStatePerGroup pergroup;      /* per-Aggref-per-group working state */
1695         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1696         /* these fields are used in AGG_HASHED mode: */
1697         TupleHashTable hashtable;       /* hash table with one entry per group */
1698         TupleTableSlot *hashslot;       /* slot for loading hash table */
1699         List       *hash_needed;        /* list of columns needed in hash table */
1700         bool            table_filled;   /* hash table filled yet? */
1701         TupleHashIterator hashiter; /* for iterating through hash table */
1702 } AggState;
1703
1704 /* ----------------
1705  *      WindowAggState information
1706  * ----------------
1707  */
1708 /* these structs are private in nodeWindowAgg.c: */
1709 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1710 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1711
1712 typedef struct WindowAggState
1713 {
1714         ScanState       ss;                             /* its first field is NodeTag */
1715
1716         /* these fields are filled in by ExecInitExpr: */
1717         List       *funcs;                      /* all WindowFunc nodes in targetlist */
1718         int                     numfuncs;               /* total number of window functions */
1719         int                     numaggs;                /* number that are plain aggregates */
1720
1721         WindowStatePerFunc perfunc; /* per-window-function information */
1722         WindowStatePerAgg peragg;       /* per-plain-aggregate information */
1723         FmgrInfo   *partEqfunctions;    /* equality funcs for partition columns */
1724         FmgrInfo   *ordEqfunctions; /* equality funcs for ordering columns */
1725         Tuplestorestate *buffer;        /* stores rows of current partition */
1726         int                     current_ptr;    /* read pointer # for current */
1727         int64           spooled_rows;   /* total # of rows in buffer */
1728         int64           currentpos;             /* position of current row in partition */
1729         int64           frameheadpos;   /* current frame head position */
1730         int64           frametailpos;   /* current frame tail position */
1731         /* use struct pointer to avoid including windowapi.h here */
1732         struct WindowObjectData *agg_winobj;            /* winobj for aggregate
1733                                                                                                  * fetches */
1734         int64           aggregatedbase; /* start row for current aggregates */
1735         int64           aggregatedupto; /* rows before this one are aggregated */
1736
1737         int                     frameOptions;   /* frame_clause options, see WindowDef */
1738         ExprState  *startOffset;        /* expression for starting bound offset */
1739         ExprState  *endOffset;          /* expression for ending bound offset */
1740         Datum           startOffsetValue;               /* result of startOffset evaluation */
1741         Datum           endOffsetValue; /* result of endOffset evaluation */
1742
1743         MemoryContext partcontext;      /* context for partition-lifespan data */
1744         MemoryContext aggcontext;       /* context for each aggregate data */
1745         ExprContext *tmpcontext;        /* short-term evaluation context */
1746
1747         bool            all_first;              /* true if the scan is starting */
1748         bool            all_done;               /* true if the scan is finished */
1749         bool            partition_spooled;              /* true if all tuples in current
1750                                                                                  * partition have been spooled into
1751                                                                                  * tuplestore */
1752         bool            more_partitions;/* true if there's more partitions after this
1753                                                                  * one */
1754         bool            framehead_valid;/* true if frameheadpos is known up to date
1755                                                                  * for current row */
1756         bool            frametail_valid;/* true if frametailpos is known up to date
1757                                                                  * for current row */
1758
1759         TupleTableSlot *first_part_slot;        /* first tuple of current or next
1760                                                                                  * partition */
1761
1762         /* temporary slots for tuples fetched back from tuplestore */
1763         TupleTableSlot *agg_row_slot;
1764         TupleTableSlot *temp_slot_1;
1765         TupleTableSlot *temp_slot_2;
1766 } WindowAggState;
1767
1768 /* ----------------
1769  *       UniqueState information
1770  *
1771  *              Unique nodes are used "on top of" sort nodes to discard
1772  *              duplicate tuples returned from the sort phase.  Basically
1773  *              all it does is compare the current tuple from the subplan
1774  *              with the previously fetched tuple (stored in its result slot).
1775  *              If the two are identical in all interesting fields, then
1776  *              we just fetch another tuple from the sort and try again.
1777  * ----------------
1778  */
1779 typedef struct UniqueState
1780 {
1781         PlanState       ps;                             /* its first field is NodeTag */
1782         FmgrInfo   *eqfunctions;        /* per-field lookup data for equality fns */
1783         MemoryContext tempContext;      /* short-term context for comparisons */
1784 } UniqueState;
1785
1786 /* ----------------
1787  *       HashState information
1788  * ----------------
1789  */
1790 typedef struct HashState
1791 {
1792         PlanState       ps;                             /* its first field is NodeTag */
1793         HashJoinTable hashtable;        /* hash table for the hashjoin */
1794         List       *hashkeys;           /* list of ExprState nodes */
1795         /* hashkeys is same as parent's hj_InnerHashKeys */
1796 } HashState;
1797
1798 /* ----------------
1799  *       SetOpState information
1800  *
1801  *              Even in "sorted" mode, SetOp nodes are more complex than a simple
1802  *              Unique, since we have to count how many duplicates to return.  But
1803  *              we also support hashing, so this is really more like a cut-down
1804  *              form of Agg.
1805  * ----------------
1806  */
1807 /* this struct is private in nodeSetOp.c: */
1808 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1809
1810 typedef struct SetOpState
1811 {
1812         PlanState       ps;                             /* its first field is NodeTag */
1813         FmgrInfo   *eqfunctions;        /* per-grouping-field equality fns */
1814         FmgrInfo   *hashfunctions;      /* per-grouping-field hash fns */
1815         bool            setop_done;             /* indicates completion of output scan */
1816         long            numOutput;              /* number of dups left to output */
1817         MemoryContext tempContext;      /* short-term context for comparisons */
1818         /* these fields are used in SETOP_SORTED mode: */
1819         SetOpStatePerGroup pergroup;    /* per-group working state */
1820         HeapTuple       grp_firstTuple; /* copy of first tuple of current group */
1821         /* these fields are used in SETOP_HASHED mode: */
1822         TupleHashTable hashtable;       /* hash table with one entry per group */
1823         MemoryContext tableContext; /* memory context containing hash table */
1824         bool            table_filled;   /* hash table filled yet? */
1825         TupleHashIterator hashiter; /* for iterating through hash table */
1826 } SetOpState;
1827
1828 /* ----------------
1829  *       LockRowsState information
1830  *
1831  *              LockRows nodes are used to enforce FOR UPDATE/FOR SHARE locking.
1832  * ----------------
1833  */
1834 typedef struct LockRowsState
1835 {
1836         PlanState       ps;                             /* its first field is NodeTag */
1837         List       *lr_arowMarks;       /* List of ExecAuxRowMarks */
1838         EPQState        lr_epqstate;    /* for evaluating EvalPlanQual rechecks */
1839 } LockRowsState;
1840
1841 /* ----------------
1842  *       LimitState information
1843  *
1844  *              Limit nodes are used to enforce LIMIT/OFFSET clauses.
1845  *              They just select the desired subrange of their subplan's output.
1846  *
1847  * offset is the number of initial tuples to skip (0 does nothing).
1848  * count is the number of tuples to return after skipping the offset tuples.
1849  * If no limit count was specified, count is undefined and noCount is true.
1850  * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1851  * ----------------
1852  */
1853 typedef enum
1854 {
1855         LIMIT_INITIAL,                          /* initial state for LIMIT node */
1856         LIMIT_RESCAN,                           /* rescan after recomputing parameters */
1857         LIMIT_EMPTY,                            /* there are no returnable rows */
1858         LIMIT_INWINDOW,                         /* have returned a row in the window */
1859         LIMIT_SUBPLANEOF,                       /* at EOF of subplan (within window) */
1860         LIMIT_WINDOWEND,                        /* stepped off end of window */
1861         LIMIT_WINDOWSTART                       /* stepped off beginning of window */
1862 } LimitStateCond;
1863
1864 typedef struct LimitState
1865 {
1866         PlanState       ps;                             /* its first field is NodeTag */
1867         ExprState  *limitOffset;        /* OFFSET parameter, or NULL if none */
1868         ExprState  *limitCount;         /* COUNT parameter, or NULL if none */
1869         int64           offset;                 /* current OFFSET value */
1870         int64           count;                  /* current COUNT, if any */
1871         bool            noCount;                /* if true, ignore count */
1872         LimitStateCond lstate;          /* state machine status, as above */
1873         int64           position;               /* 1-based index of last tuple returned */
1874         TupleTableSlot *subSlot;        /* tuple last obtained from subplan */
1875 } LimitState;
1876
1877 #endif   /* EXECNODES_H */