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