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