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