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