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