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