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