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