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