1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/include/nodes/execnodes.h
12 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "executor/instrument.h"
20 #include "nodes/params.h"
21 #include "nodes/plannodes.h"
22 #include "utils/reltrigger.h"
23 #include "utils/sortsupport.h"
24 #include "utils/tuplestore.h"
28 * IndexInfo information
30 * this struct holds the information needed to construct new index
31 * entries for a particular index. Used for both index_build and
32 * retail creation of index entries.
34 * NumIndexAttrs number of columns in this index
35 * KeyAttrNumbers underlying-rel attribute numbers used as keys
36 * (zeroes indicate expressions)
37 * Expressions expr trees for expression entries, or NIL if none
38 * ExpressionsState exec state for expressions, or NIL if none
39 * Predicate partial-index predicate, or NIL if none
40 * PredicateState exec state for predicate, or NIL if none
41 * ExclusionOps Per-column exclusion operators, or NULL if none
42 * ExclusionProcs Underlying function OIDs for ExclusionOps
43 * ExclusionStrats Opclass strategy numbers for ExclusionOps
44 * Unique is it a unique index?
45 * ReadyForInserts is it valid for inserts?
46 * Concurrent are we doing a concurrent index build?
47 * BrokenHotChain did we detect any broken HOT chains?
49 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
50 * they're conventionally set to false otherwise.
53 typedef struct IndexInfo
57 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
58 List *ii_Expressions; /* list of Expr */
59 List *ii_ExpressionsState; /* list of ExprState */
60 List *ii_Predicate; /* list of Expr */
61 List *ii_PredicateState; /* list of ExprState */
62 Oid *ii_ExclusionOps; /* array with one entry per column */
63 Oid *ii_ExclusionProcs; /* array with one entry per column */
64 uint16 *ii_ExclusionStrats; /* array with one entry per column */
66 bool ii_ReadyForInserts;
68 bool ii_BrokenHotChain;
74 * List of callbacks to be called at ExprContext shutdown.
77 typedef void (*ExprContextCallbackFunction) (Datum arg);
79 typedef struct ExprContext_CB
81 struct ExprContext_CB *next;
82 ExprContextCallbackFunction function;
89 * This class holds the "current context" information
90 * needed to evaluate expressions for doing tuple qualifications
91 * and tuple projections. For example, if an expression refers
92 * to an attribute in the current inner tuple then we need to know
93 * what the current inner tuple is and so we look at the expression
96 * There are two memory contexts associated with an ExprContext:
97 * * ecxt_per_query_memory is a query-lifespan context, typically the same
98 * context the ExprContext node itself is allocated in. This context
99 * can be used for purposes such as storing function call cache info.
100 * * ecxt_per_tuple_memory is a short-term context for expression results.
101 * As the name suggests, it will typically be reset once per tuple,
102 * before we begin to evaluate expressions for that tuple. Each
103 * ExprContext normally has its very own per-tuple memory context.
105 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
106 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
109 typedef struct ExprContext
113 /* Tuples that Var nodes in expression may refer to */
114 TupleTableSlot *ecxt_scantuple;
115 TupleTableSlot *ecxt_innertuple;
116 TupleTableSlot *ecxt_outertuple;
118 /* Memory contexts for expression evaluation --- see notes above */
119 MemoryContext ecxt_per_query_memory;
120 MemoryContext ecxt_per_tuple_memory;
122 /* Values to substitute for Param nodes in expression */
123 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
124 ParamListInfo ecxt_param_list_info; /* for other param types */
127 * Values to substitute for Aggref nodes in the expressions of an Agg
128 * node, or for WindowFunc nodes within a WindowAgg node.
130 Datum *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
131 bool *ecxt_aggnulls; /* null flags for aggs/windowfuncs */
133 /* Value to substitute for CaseTestExpr nodes in expression */
134 Datum caseValue_datum;
135 bool caseValue_isNull;
137 /* Value to substitute for CoerceToDomainValue nodes in expression */
138 Datum domainValue_datum;
139 bool domainValue_isNull;
141 /* Link to containing EState (NULL if a standalone ExprContext) */
142 struct EState *ecxt_estate;
144 /* Functions to call back when ExprContext is shut down */
145 ExprContext_CB *ecxt_callbacks;
149 * Set-result status returned by ExecEvalExpr()
153 ExprSingleResult, /* expression does not return a set */
154 ExprMultipleResult, /* this result is an element of a set */
155 ExprEndResult /* there are no more elements in the set */
159 * Return modes for functions returning sets. Note values must be chosen
160 * as separate bits so that a bitmask can be formed to indicate supported
161 * modes. SFRM_Materialize_Random and SFRM_Materialize_Preferred are
162 * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
166 SFRM_ValuePerCall = 0x01, /* one value returned per call */
167 SFRM_Materialize = 0x02, /* result set instantiated in Tuplestore */
168 SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */
169 SFRM_Materialize_Preferred = 0x08 /* caller prefers Tuplestore */
170 } SetFunctionReturnMode;
173 * When calling a function that might return a set (multiple rows),
174 * a node of this type is passed as fcinfo->resultinfo to allow
175 * return status to be passed back. A function returning set should
176 * raise an error if no such resultinfo is provided.
178 typedef struct ReturnSetInfo
181 /* values set by caller: */
182 ExprContext *econtext; /* context function is being called in */
183 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
184 int allowedModes; /* bitmask: return modes caller can handle */
185 /* result status from function (but pre-initialized by caller): */
186 SetFunctionReturnMode returnMode; /* actual return mode */
187 ExprDoneCond isDone; /* status for ValuePerCall mode */
188 /* fields filled by function in Materialize return mode: */
189 Tuplestorestate *setResult; /* holds the complete returned tuple set */
190 TupleDesc setDesc; /* actual descriptor for returned tuples */
194 * ProjectionInfo node information
196 * This is all the information needed to perform projections ---
197 * that is, form new tuples by evaluation of targetlist expressions.
198 * Nodes which need to do projections create one of these.
200 * ExecProject() evaluates the tlist, forms a tuple, and stores it
201 * in the given slot. Note that the result will be a "virtual" tuple
202 * unless ExecMaterializeSlot() is then called to force it to be
203 * converted to a physical tuple. The slot must have a tupledesc
204 * that matches the output of the tlist!
206 * The planner very often produces tlists that consist entirely of
207 * simple Var references (lower levels of a plan tree almost always
208 * look like that). And top-level tlists are often mostly Vars too.
209 * We therefore optimize execution of simple-Var tlist entries.
210 * The pi_targetlist list actually contains only the tlist entries that
211 * aren't simple Vars, while those that are Vars are processed using the
212 * varSlotOffsets/varNumbers/varOutputCols arrays.
214 * The lastXXXVar fields are used to optimize fetching of fields from
215 * input tuples: they let us do a slot_getsomeattrs() call to ensure
216 * that all needed attributes are extracted in one pass.
218 * targetlist target list for projection (non-Var expressions only)
219 * exprContext expression context in which to evaluate targetlist
220 * slot slot to place projection result in
221 * itemIsDone workspace array for ExecProject
222 * directMap true if varOutputCols[] is an identity map
223 * numSimpleVars number of simple Vars found in original tlist
224 * varSlotOffsets array indicating which slot each simple Var is from
225 * varNumbers array containing input attr numbers of simple Vars
226 * varOutputCols array containing output attr numbers of simple Vars
227 * lastInnerVar highest attnum from inner tuple slot (0 if none)
228 * lastOuterVar highest attnum from outer tuple slot (0 if none)
229 * lastScanVar highest attnum from scan tuple slot (0 if none)
232 typedef struct ProjectionInfo
236 ExprContext *pi_exprContext;
237 TupleTableSlot *pi_slot;
238 ExprDoneCond *pi_itemIsDone;
240 int pi_numSimpleVars;
241 int *pi_varSlotOffsets;
243 int *pi_varOutputCols;
252 * This class is used to store information regarding junk attributes.
253 * A junk attribute is an attribute in a tuple that is needed only for
254 * storing intermediate information in the executor, and does not belong
255 * in emitted tuples. For example, when we do an UPDATE query,
256 * the planner adds a "junk" entry to the targetlist so that the tuples
257 * returned to ExecutePlan() contain an extra attribute: the ctid of
258 * the tuple to be updated. This is needed to do the update, but we
259 * don't want the ctid to be part of the stored new tuple! So, we
260 * apply a "junk filter" to remove the junk attributes and form the
261 * real output tuple. The junkfilter code also provides routines to
262 * extract the values of the junk attribute(s) from the input tuple.
264 * targetList: the original target list (including junk attributes).
265 * cleanTupType: the tuple descriptor for the "clean" tuple (with
266 * junk attributes removed).
267 * cleanMap: A map with the correspondence between the non-junk
268 * attribute numbers of the "original" tuple and the
269 * attribute numbers of the "clean" tuple.
270 * resultSlot: tuple slot used to hold cleaned tuple.
271 * junkAttNo: not used by junkfilter code. Can be used by caller
272 * to remember the attno of a specific junk attribute
273 * (execMain.c stores the "ctid" attno here).
276 typedef struct JunkFilter
280 TupleDesc jf_cleanTupType;
281 AttrNumber *jf_cleanMap;
282 TupleTableSlot *jf_resultSlot;
283 AttrNumber jf_junkAttNo;
287 * ResultRelInfo information
289 * Whenever we update an existing relation, we have to
290 * update indices on the relation, and perhaps also fire triggers.
291 * The ResultRelInfo class is used to hold all the information needed
292 * about a result relation, including indices.. -cim 10/15/89
294 * RangeTableIndex result relation's range table index
295 * RelationDesc relation descriptor for result relation
296 * NumIndices # of indices existing on result relation
297 * IndexRelationDescs array of relation descriptors for indices
298 * IndexRelationInfo array of key/attr info for indices
299 * TrigDesc triggers to be fired, if any
300 * TrigFunctions cached lookup info for trigger functions
301 * TrigWhenExprs array of trigger WHEN expr states
302 * TrigInstrument optional runtime measurements for triggers
303 * ConstraintExprs array of constraint-checking expr states
304 * junkFilter for removing junk attributes from tuples
305 * projectReturning for computing a RETURNING list
308 typedef struct ResultRelInfo
311 Index ri_RangeTableIndex;
312 Relation ri_RelationDesc;
314 RelationPtr ri_IndexRelationDescs;
315 IndexInfo **ri_IndexRelationInfo;
316 TriggerDesc *ri_TrigDesc;
317 FmgrInfo *ri_TrigFunctions;
318 List **ri_TrigWhenExprs;
319 Instrumentation *ri_TrigInstrument;
320 List **ri_ConstraintExprs;
321 JunkFilter *ri_junkFilter;
322 ProjectionInfo *ri_projectReturning;
328 * Master working state for an Executor invocation
331 typedef struct EState
335 /* Basic state for all query types: */
336 ScanDirection es_direction; /* current scan direction */
337 Snapshot es_snapshot; /* time qual to use */
338 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
339 List *es_range_table; /* List of RangeTblEntry */
340 PlannedStmt *es_plannedstmt; /* link to top of plan tree */
342 JunkFilter *es_junkFilter; /* top-level junk filter, if any */
344 /* If query can insert/delete tuples, the command ID to mark them with */
345 CommandId es_output_cid;
347 /* Info about target table(s) for insert/update/delete queries: */
348 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
349 int es_num_result_relations; /* length of array */
350 ResultRelInfo *es_result_relation_info; /* currently active array elt */
352 /* Stuff used for firing triggers: */
353 List *es_trig_target_relations; /* trigger-only ResultRelInfos */
354 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
355 TupleTableSlot *es_trig_oldtup_slot; /* for TriggerEnabled */
356 TupleTableSlot *es_trig_newtup_slot; /* for TriggerEnabled */
358 /* Parameter info: */
359 ParamListInfo es_param_list_info; /* values of external params */
360 ParamExecData *es_param_exec_vals; /* values of internal params */
362 /* Other working state: */
363 MemoryContext es_query_cxt; /* per-query context in which EState lives */
365 List *es_tupleTable; /* List of TupleTableSlots */
367 List *es_rowMarks; /* List of ExecRowMarks */
369 uint32 es_processed; /* # of tuples processed */
370 Oid es_lastoid; /* last oid processed (by INSERT) */
372 int es_top_eflags; /* eflags passed to ExecutorStart */
373 int es_instrument; /* OR of InstrumentOption flags */
374 bool es_finished; /* true when ExecutorFinish is done */
376 List *es_exprcontexts; /* List of ExprContexts within EState */
378 List *es_subplanstates; /* List of PlanState for SubPlans */
380 List *es_auxmodifytables; /* List of secondary ModifyTableStates */
383 * this ExprContext is for per-output-tuple operations, such as constraint
384 * checks and index-value computations. It will be reset for each output
385 * tuple. Note that it will be created only if needed.
387 ExprContext *es_per_tuple_exprcontext;
390 * These fields are for re-evaluating plan quals when an updated tuple is
391 * substituted in READ COMMITTED mode. es_epqTuple[] contains tuples that
392 * scan plan nodes should return instead of whatever they'd normally
393 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
394 * particular array entry is valid; and es_epqScanDone[] is state to
395 * remember if the tuple has been returned already. Arrays are of size
396 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
398 HeapTuple *es_epqTuple; /* array of EPQ substitute tuples */
399 bool *es_epqTupleSet; /* true if EPQ tuple is provided */
400 bool *es_epqScanDone; /* true if EPQ tuple has been fetched */
406 * runtime representation of FOR UPDATE/SHARE clauses
408 * When doing UPDATE, DELETE, or SELECT FOR UPDATE/SHARE, we should have an
409 * ExecRowMark for each non-target relation in the query (except inheritance
410 * parent RTEs, which can be ignored at runtime). See PlanRowMark for details
411 * about most of the fields. In addition to fields directly derived from
412 * PlanRowMark, we store curCtid, which is used by the WHERE CURRENT OF code.
414 * EState->es_rowMarks is a list of these structs.
416 typedef struct ExecRowMark
418 Relation relation; /* opened and suitably locked relation */
419 Index rti; /* its range table index */
420 Index prti; /* parent range table index, if child */
421 Index rowmarkId; /* unique identifier for resjunk columns */
422 RowMarkType markType; /* see enum in nodes/plannodes.h */
423 bool noWait; /* NOWAIT option */
424 ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
429 * additional runtime representation of FOR UPDATE/SHARE clauses
431 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
432 * deal with. In addition to a pointer to the related entry in es_rowMarks,
433 * this struct carries the column number(s) of the resjunk columns associated
434 * with the rowmark (see comments for PlanRowMark for more detail). In the
435 * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
436 * each child plan, because the resjunk columns could be at different physical
437 * column positions in different subplans.
439 typedef struct ExecAuxRowMark
441 ExecRowMark *rowmark; /* related entry in es_rowMarks */
442 AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
443 AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
444 AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
448 /* ----------------------------------------------------------------
451 * All-in-memory tuple hash tables are used for a number of purposes.
453 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
454 * and tab_eq_funcs are non-cross-type equality operators for those types.
455 * Normally these are the only functions used, but FindTupleHashEntry()
456 * supports searching a hashtable using cross-data-type hashing. For that,
457 * the caller must supply hash functions for the LHS datatype as well as
458 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
459 * are set to point to the caller's function arrays while doing such a search.
460 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
461 * tab_eq_funcs respectively.
462 * ----------------------------------------------------------------
464 typedef struct TupleHashEntryData *TupleHashEntry;
465 typedef struct TupleHashTableData *TupleHashTable;
467 typedef struct TupleHashEntryData
469 /* firstTuple must be the first field in this struct! */
470 MinimalTuple firstTuple; /* copy of first tuple in this group */
471 /* there may be additional data beyond the end of this struct */
472 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
474 typedef struct TupleHashTableData
476 HTAB *hashtab; /* underlying dynahash table */
477 int numCols; /* number of columns in lookup key */
478 AttrNumber *keyColIdx; /* attr numbers of key columns */
479 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
480 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
481 MemoryContext tablecxt; /* memory context containing table */
482 MemoryContext tempcxt; /* context for function evaluations */
483 Size entrysize; /* actual size to make each hash entry */
484 TupleTableSlot *tableslot; /* slot for referencing table entries */
485 /* The following fields are set transiently for each table search: */
486 TupleTableSlot *inputslot; /* current input tuple's slot */
487 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
488 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
489 } TupleHashTableData;
491 typedef HASH_SEQ_STATUS TupleHashIterator;
494 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
495 * Use ResetTupleHashIterator if the table can be frozen (in this case no
496 * explicit scan termination is needed).
498 #define InitTupleHashIterator(htable, iter) \
499 hash_seq_init(iter, (htable)->hashtab)
500 #define TermTupleHashIterator(iter) \
502 #define ResetTupleHashIterator(htable, iter) \
504 hash_freeze((htable)->hashtab); \
505 hash_seq_init(iter, (htable)->hashtab); \
507 #define ScanTupleHashTable(iter) \
508 ((TupleHashEntry) hash_seq_search(iter))
511 /* ----------------------------------------------------------------
512 * Expression State Trees
514 * Each executable expression tree has a parallel ExprState tree.
516 * Unlike PlanState, there is not an exact one-for-one correspondence between
517 * ExprState node types and Expr node types. Many Expr node types have no
518 * need for node-type-specific run-time state, and so they can use plain
519 * ExprState or GenericExprState as their associated ExprState node type.
520 * ----------------------------------------------------------------
526 * ExprState is the common superclass for all ExprState-type nodes.
528 * It can also be instantiated directly for leaf Expr nodes that need no
529 * local run-time state (such as Var, Const, or Param).
531 * To save on dispatch overhead, each ExprState node contains a function
532 * pointer to the routine to execute to evaluate the node.
536 typedef struct ExprState ExprState;
538 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
539 ExprContext *econtext,
541 ExprDoneCond *isDone);
546 Expr *expr; /* associated Expr node */
547 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
551 * GenericExprState node
553 * This is used for Expr node types that need no local run-time state,
554 * but have one child Expr node.
557 typedef struct GenericExprState
560 ExprState *arg; /* state of my child node */
564 * WholeRowVarExprState node
567 typedef struct WholeRowVarExprState
570 struct PlanState *parent; /* parent PlanState, or NULL if none */
571 JunkFilter *wrv_junkFilter; /* JunkFilter to remove resjunk cols */
572 } WholeRowVarExprState;
575 * AggrefExprState node
578 typedef struct AggrefExprState
581 List *args; /* states of argument expressions */
582 int aggno; /* ID number for agg within its plan node */
586 * WindowFuncExprState node
589 typedef struct WindowFuncExprState
592 List *args; /* states of argument expressions */
593 int wfuncno; /* ID number for wfunc within its plan node */
594 } WindowFuncExprState;
597 * ArrayRefExprState node
599 * Note: array types can be fixed-length (typlen > 0), but only when the
600 * element type is itself fixed-length. Otherwise they are varlena structures
601 * and have typlen = -1. In any case, an array type is never pass-by-value.
604 typedef struct ArrayRefExprState
607 List *refupperindexpr; /* states for child nodes */
608 List *reflowerindexpr;
610 ExprState *refassgnexpr;
611 int16 refattrlength; /* typlen of array type */
612 int16 refelemlength; /* typlen of the array element type */
613 bool refelembyval; /* is the element type pass-by-value? */
614 char refelemalign; /* typalign of the element type */
620 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
621 * and NullIf nodes; be careful to check what xprstate.expr is actually
625 typedef struct FuncExprState
628 List *args; /* states of argument expressions */
631 * Function manager's lookup info for the target function. If func.fn_oid
632 * is InvalidOid, we haven't initialized it yet (nor any of the following
638 * For a set-returning function (SRF) that returns a tuplestore, we keep
639 * the tuplestore here and dole out the result rows one at a time. The
640 * slot holds the row currently being returned.
642 Tuplestorestate *funcResultStore;
643 TupleTableSlot *funcResultSlot;
646 * In some cases we need to compute a tuple descriptor for the function's
647 * output. If so, it's stored here.
649 TupleDesc funcResultDesc;
650 bool funcReturnsTuple; /* valid when funcResultDesc isn't
654 * setArgsValid is true when we are evaluating a set-returning function
655 * that uses value-per-call mode and we are in the middle of a call
656 * series; we want to pass the same argument values to the function again
657 * (and again, until it returns ExprEndResult). This indicates that
658 * fcinfo_data already contains valid argument data.
663 * Flag to remember whether we found a set-valued argument to the
664 * function. This causes the function result to be a set as well. Valid
665 * only when setArgsValid is true or funcResultStore isn't NULL.
667 bool setHasSetArg; /* some argument returns a set */
670 * Flag to remember whether we have registered a shutdown callback for
671 * this FuncExprState. We do so only if funcResultStore or setArgsValid
672 * has been set at least once (since all the callback is for is to release
673 * the tuplestore or clear setArgsValid).
675 bool shutdown_reg; /* a shutdown callback is registered */
678 * Call parameter structure for the function. This has been initialized
679 * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
680 * argument values between calls, when setArgsValid is true.
682 FunctionCallInfoData fcinfo_data;
686 * ScalarArrayOpExprState node
688 * This is a FuncExprState plus some additional data.
691 typedef struct ScalarArrayOpExprState
693 FuncExprState fxprstate;
694 /* Cached info about array element type */
699 } ScalarArrayOpExprState;
705 typedef struct BoolExprState
708 List *args; /* states of argument expression(s) */
715 typedef struct SubPlanState
718 struct PlanState *planstate; /* subselect plan's state tree */
719 ExprState *testexpr; /* state of combining expression */
720 List *args; /* states of argument expression(s) */
721 HeapTuple curTuple; /* copy of most recent tuple from subplan */
722 Datum curArray; /* most recent array from ARRAY() subplan */
723 /* these are used when hashing the subselect's output: */
724 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
725 ProjectionInfo *projRight; /* for projecting subselect output */
726 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
727 TupleHashTable hashnulls; /* hash table for rows with null(s) */
728 bool havehashrows; /* TRUE if hashtable is not empty */
729 bool havenullrows; /* TRUE if hashnulls is not empty */
730 MemoryContext hashtablecxt; /* memory context containing hash tables */
731 MemoryContext hashtempcxt; /* temp memory context for hash tables */
732 ExprContext *innerecontext; /* econtext for computing inner tuples */
733 AttrNumber *keyColIdx; /* control data for hash tables */
734 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
735 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
736 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
737 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
741 * AlternativeSubPlanState node
744 typedef struct AlternativeSubPlanState
747 List *subplans; /* states of alternative subplans */
748 int active; /* list index of the one we're using */
749 } AlternativeSubPlanState;
752 * FieldSelectState node
755 typedef struct FieldSelectState
758 ExprState *arg; /* input expression */
759 TupleDesc argdesc; /* tupdesc for most recent input */
763 * FieldStoreState node
766 typedef struct FieldStoreState
769 ExprState *arg; /* input tuple value */
770 List *newvals; /* new value(s) for field(s) */
771 TupleDesc argdesc; /* tupdesc for most recent input */
775 * CoerceViaIOState node
778 typedef struct CoerceViaIOState
781 ExprState *arg; /* input expression */
782 FmgrInfo outfunc; /* lookup info for source output function */
783 FmgrInfo infunc; /* lookup info for result input function */
784 Oid intypioparam; /* argument needed for input function */
788 * ArrayCoerceExprState node
791 typedef struct ArrayCoerceExprState
794 ExprState *arg; /* input array value */
795 Oid resultelemtype; /* element type of result array */
796 FmgrInfo elemfunc; /* lookup info for element coercion function */
797 /* use struct pointer to avoid including array.h here */
798 struct ArrayMapState *amstate; /* workspace for array_map */
799 } ArrayCoerceExprState;
802 * ConvertRowtypeExprState node
805 typedef struct ConvertRowtypeExprState
808 ExprState *arg; /* input tuple value */
809 TupleDesc indesc; /* tupdesc for source rowtype */
810 TupleDesc outdesc; /* tupdesc for result rowtype */
811 /* use "struct" so we needn't include tupconvert.h here */
812 struct TupleConversionMap *map;
814 } ConvertRowtypeExprState;
820 typedef struct CaseExprState
823 ExprState *arg; /* implicit equality comparison argument */
824 List *args; /* the arguments (list of WHEN clauses) */
825 ExprState *defresult; /* the default result (ELSE clause) */
832 typedef struct CaseWhenState
835 ExprState *expr; /* condition expression */
836 ExprState *result; /* substitution result */
840 * ArrayExprState node
842 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
846 typedef struct ArrayExprState
849 List *elements; /* states for child nodes */
850 int16 elemlength; /* typlen of the array element type */
851 bool elembyval; /* is the element type pass-by-value? */
852 char elemalign; /* typalign of the element type */
859 typedef struct RowExprState
862 List *args; /* the arguments */
863 TupleDesc tupdesc; /* descriptor for result tuples */
867 * RowCompareExprState node
870 typedef struct RowCompareExprState
873 List *largs; /* the left-hand input arguments */
874 List *rargs; /* the right-hand input arguments */
875 FmgrInfo *funcs; /* array of comparison function info */
876 Oid *collations; /* array of collations to use */
877 } RowCompareExprState;
880 * CoalesceExprState node
883 typedef struct CoalesceExprState
886 List *args; /* the arguments */
890 * MinMaxExprState node
893 typedef struct MinMaxExprState
896 List *args; /* the arguments */
897 FmgrInfo cfunc; /* lookup info for comparison func */
904 typedef struct XmlExprState
907 List *named_args; /* ExprStates for named arguments */
908 List *args; /* ExprStates for other arguments */
915 typedef struct NullTestState
918 ExprState *arg; /* input expression */
919 /* used only if input is of composite type: */
920 TupleDesc argdesc; /* tupdesc for most recent input */
924 * CoerceToDomainState node
927 typedef struct CoerceToDomainState
930 ExprState *arg; /* input expression */
931 /* Cached list of constraints that need to be checked */
932 List *constraints; /* list of DomainConstraintState nodes */
933 } CoerceToDomainState;
936 * DomainConstraintState - one item to check during CoerceToDomain
938 * Note: this is just a Node, and not an ExprState, because it has no
939 * corresponding Expr to link to. Nonetheless it is part of an ExprState
940 * tree, so we give it a name following the xxxState convention.
942 typedef enum DomainConstraintType
944 DOM_CONSTRAINT_NOTNULL,
946 } DomainConstraintType;
948 typedef struct DomainConstraintState
951 DomainConstraintType constrainttype; /* constraint type */
952 char *name; /* name of constraint (for error msgs) */
953 ExprState *check_expr; /* for CHECK, a boolean expression */
954 } DomainConstraintState;
957 /* ----------------------------------------------------------------
958 * Executor State Trees
960 * An executing query has a PlanState tree paralleling the Plan tree
961 * that describes the plan.
962 * ----------------------------------------------------------------
968 * We never actually instantiate any PlanState nodes; this is just the common
969 * abstract superclass for all PlanState-type nodes.
972 typedef struct PlanState
976 Plan *plan; /* associated Plan node */
978 EState *state; /* at execution time, states of individual
979 * nodes point to one EState for the whole
982 Instrumentation *instrument; /* Optional runtime stats for this node */
985 * Common structural data for all Plan types. These links to subsidiary
986 * state trees parallel links in the associated plan tree (except for the
987 * subPlan list, which does not exist in the plan tree).
989 List *targetlist; /* target list to be computed at this node */
990 List *qual; /* implicitly-ANDed qual conditions */
991 struct PlanState *lefttree; /* input plan tree(s) */
992 struct PlanState *righttree;
993 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
995 List *subPlan; /* SubPlanState nodes in my expressions */
998 * State for management of parameter-change-driven rescanning
1000 Bitmapset *chgParam; /* set of IDs of changed Params */
1003 * Other run-time state needed by most if not all node types.
1005 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
1006 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
1007 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
1008 bool ps_TupFromTlist;/* state flag for processing set-valued
1009 * functions in targetlist */
1013 * these are defined to avoid confusion problems with "left"
1014 * and "right" and "inner" and "outer". The convention is that
1015 * the "left" plan is the "outer" plan and the "right" plan is
1016 * the inner plan, but these make the code more readable.
1019 #define innerPlanState(node) (((PlanState *)(node))->righttree)
1020 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
1022 /* Macros for inline access to certain instrumentation counters */
1023 #define InstrCountFiltered1(node, delta) \
1025 if (((PlanState *)(node))->instrument) \
1026 ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
1028 #define InstrCountFiltered2(node, delta) \
1030 if (((PlanState *)(node))->instrument) \
1031 ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
1035 * EPQState is state for executing an EvalPlanQual recheck on a candidate
1036 * tuple in ModifyTable or LockRows. The estate and planstate fields are
1039 typedef struct EPQState
1041 EState *estate; /* subsidiary EState */
1042 PlanState *planstate; /* plan state tree ready to be executed */
1043 TupleTableSlot *origslot; /* original output tuple to be rechecked */
1044 Plan *plan; /* plan tree to be executed */
1045 List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
1046 int epqParam; /* ID of Param to force scan node re-eval */
1051 * ResultState information
1054 typedef struct ResultState
1056 PlanState ps; /* its first field is NodeTag */
1057 ExprState *resconstantqual;
1058 bool rs_done; /* are we done? */
1059 bool rs_checkqual; /* do we need to check the qual? */
1063 * ModifyTableState information
1066 typedef struct ModifyTableState
1068 PlanState ps; /* its first field is NodeTag */
1069 CmdType operation; /* INSERT, UPDATE, or DELETE */
1070 bool canSetTag; /* do we set the command tag/es_processed? */
1071 bool mt_done; /* are we done? */
1072 PlanState **mt_plans; /* subplans (one per target rel) */
1073 int mt_nplans; /* number of plans in the array */
1074 int mt_whichplan; /* which one is being executed (0..n-1) */
1075 ResultRelInfo *resultRelInfo; /* per-subplan target relations */
1076 List **mt_arowmarks; /* per-subplan ExecAuxRowMark lists */
1077 EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
1078 bool fireBSTriggers; /* do we need to fire stmt triggers? */
1082 * AppendState information
1084 * nplans how many plans are in the array
1085 * whichplan which plan is being executed (0 .. n-1)
1088 typedef struct AppendState
1090 PlanState ps; /* its first field is NodeTag */
1091 PlanState **appendplans; /* array of PlanStates for my inputs */
1097 * MergeAppendState information
1099 * nplans how many plans are in the array
1100 * nkeys number of sort key columns
1101 * sortkeys sort keys in SortSupport representation
1102 * slots current output tuple of each subplan
1103 * heap heap of active tuples (represented as array indexes)
1104 * heap_size number of active heap entries
1105 * initialized true if we have fetched first tuple from each subplan
1106 * last_slot last subplan fetched from (which must be re-called)
1109 typedef struct MergeAppendState
1111 PlanState ps; /* its first field is NodeTag */
1112 PlanState **mergeplans; /* array of PlanStates for my inputs */
1115 SortSupport ms_sortkeys; /* array of length ms_nkeys */
1116 TupleTableSlot **ms_slots; /* array of length ms_nplans */
1117 int *ms_heap; /* array of length ms_nplans */
1118 int ms_heap_size; /* current active length of ms_heap[] */
1119 bool ms_initialized; /* are subplans started? */
1120 int ms_last_slot; /* last subplan slot we returned from */
1124 * RecursiveUnionState information
1126 * RecursiveUnionState is used for performing a recursive union.
1128 * recursing T when we're done scanning the non-recursive term
1129 * intermediate_empty T if intermediate_table is currently empty
1130 * working_table working table (to be scanned by recursive term)
1131 * intermediate_table current recursive output (next generation of WT)
1134 typedef struct RecursiveUnionState
1136 PlanState ps; /* its first field is NodeTag */
1138 bool intermediate_empty;
1139 Tuplestorestate *working_table;
1140 Tuplestorestate *intermediate_table;
1141 /* Remaining fields are unused in UNION ALL case */
1142 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1143 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1144 MemoryContext tempContext; /* short-term context for comparisons */
1145 TupleHashTable hashtable; /* hash table for tuples already seen */
1146 MemoryContext tableContext; /* memory context containing hash table */
1147 } RecursiveUnionState;
1150 * BitmapAndState information
1153 typedef struct BitmapAndState
1155 PlanState ps; /* its first field is NodeTag */
1156 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1157 int nplans; /* number of input plans */
1161 * BitmapOrState information
1164 typedef struct BitmapOrState
1166 PlanState ps; /* its first field is NodeTag */
1167 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1168 int nplans; /* number of input plans */
1171 /* ----------------------------------------------------------------
1172 * Scan State Information
1173 * ----------------------------------------------------------------
1177 * ScanState information
1179 * ScanState extends PlanState for node types that represent
1180 * scans of an underlying relation. It can also be used for nodes
1181 * that scan the output of an underlying plan node --- in that case,
1182 * only ScanTupleSlot is actually useful, and it refers to the tuple
1183 * retrieved from the subplan.
1185 * currentRelation relation being scanned (NULL if none)
1186 * currentScanDesc current scan descriptor for scan (NULL if none)
1187 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
1190 typedef struct ScanState
1192 PlanState ps; /* its first field is NodeTag */
1193 Relation ss_currentRelation;
1194 HeapScanDesc ss_currentScanDesc;
1195 TupleTableSlot *ss_ScanTupleSlot;
1199 * SeqScan uses a bare ScanState as its state node, since it needs
1200 * no additional fields.
1202 typedef ScanState SeqScanState;
1205 * These structs store information about index quals that don't have simple
1206 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1211 ScanKey scan_key; /* scankey to put value into */
1212 ExprState *key_expr; /* expr to evaluate to get value */
1213 bool key_toastable; /* is expr's result a toastable datatype? */
1214 } IndexRuntimeKeyInfo;
1218 ScanKey scan_key; /* scankey to put value into */
1219 ExprState *array_expr; /* expr to evaluate to get array value */
1220 int next_elem; /* next array element to use */
1221 int num_elems; /* number of elems in current array value */
1222 Datum *elem_values; /* array of num_elems Datums */
1223 bool *elem_nulls; /* array of num_elems is-null flags */
1224 } IndexArrayKeyInfo;
1227 * IndexScanState information
1229 * indexqualorig execution state for indexqualorig expressions
1230 * ScanKeys Skey structures for index quals
1231 * NumScanKeys number of ScanKeys
1232 * OrderByKeys Skey structures for index ordering operators
1233 * NumOrderByKeys number of OrderByKeys
1234 * RuntimeKeys info about Skeys that must be evaluated at runtime
1235 * NumRuntimeKeys number of RuntimeKeys
1236 * RuntimeKeysReady true if runtime Skeys have been computed
1237 * RuntimeContext expr context for evaling runtime Skeys
1238 * RelationDesc index relation descriptor
1239 * ScanDesc index scan descriptor
1242 typedef struct IndexScanState
1244 ScanState ss; /* its first field is NodeTag */
1245 List *indexqualorig;
1246 ScanKey iss_ScanKeys;
1247 int iss_NumScanKeys;
1248 ScanKey iss_OrderByKeys;
1249 int iss_NumOrderByKeys;
1250 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1251 int iss_NumRuntimeKeys;
1252 bool iss_RuntimeKeysReady;
1253 ExprContext *iss_RuntimeContext;
1254 Relation iss_RelationDesc;
1255 IndexScanDesc iss_ScanDesc;
1259 * IndexOnlyScanState information
1261 * indexqual execution state for indexqual expressions
1262 * ScanKeys Skey structures for index quals
1263 * NumScanKeys number of ScanKeys
1264 * OrderByKeys Skey structures for index ordering operators
1265 * NumOrderByKeys number of OrderByKeys
1266 * RuntimeKeys info about Skeys that must be evaluated at runtime
1267 * NumRuntimeKeys number of RuntimeKeys
1268 * RuntimeKeysReady true if runtime Skeys have been computed
1269 * RuntimeContext expr context for evaling runtime Skeys
1270 * RelationDesc index relation descriptor
1271 * ScanDesc index scan descriptor
1272 * VMBuffer buffer in use for visibility map testing, if any
1273 * HeapFetches number of tuples we were forced to fetch from heap
1276 typedef struct IndexOnlyScanState
1278 ScanState ss; /* its first field is NodeTag */
1280 ScanKey ioss_ScanKeys;
1281 int ioss_NumScanKeys;
1282 ScanKey ioss_OrderByKeys;
1283 int ioss_NumOrderByKeys;
1284 IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1285 int ioss_NumRuntimeKeys;
1286 bool ioss_RuntimeKeysReady;
1287 ExprContext *ioss_RuntimeContext;
1288 Relation ioss_RelationDesc;
1289 IndexScanDesc ioss_ScanDesc;
1290 Buffer ioss_VMBuffer;
1291 long ioss_HeapFetches;
1292 } IndexOnlyScanState;
1295 * BitmapIndexScanState information
1297 * result bitmap to return output into, or NULL
1298 * ScanKeys Skey structures for index quals
1299 * NumScanKeys number of ScanKeys
1300 * RuntimeKeys info about Skeys that must be evaluated at runtime
1301 * NumRuntimeKeys number of RuntimeKeys
1302 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1303 * NumArrayKeys number of ArrayKeys
1304 * RuntimeKeysReady true if runtime Skeys have been computed
1305 * RuntimeContext expr context for evaling runtime Skeys
1306 * RelationDesc index relation descriptor
1307 * ScanDesc index scan descriptor
1310 typedef struct BitmapIndexScanState
1312 ScanState ss; /* its first field is NodeTag */
1313 TIDBitmap *biss_result;
1314 ScanKey biss_ScanKeys;
1315 int biss_NumScanKeys;
1316 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1317 int biss_NumRuntimeKeys;
1318 IndexArrayKeyInfo *biss_ArrayKeys;
1319 int biss_NumArrayKeys;
1320 bool biss_RuntimeKeysReady;
1321 ExprContext *biss_RuntimeContext;
1322 Relation biss_RelationDesc;
1323 IndexScanDesc biss_ScanDesc;
1324 } BitmapIndexScanState;
1327 * BitmapHeapScanState information
1329 * bitmapqualorig execution state for bitmapqualorig expressions
1330 * tbm bitmap obtained from child index scan(s)
1331 * tbmiterator iterator for scanning current pages
1332 * tbmres current-page data
1333 * prefetch_iterator iterator for prefetching ahead of current page
1334 * prefetch_pages # pages prefetch iterator is ahead of current
1335 * prefetch_target target prefetch distance
1338 typedef struct BitmapHeapScanState
1340 ScanState ss; /* its first field is NodeTag */
1341 List *bitmapqualorig;
1343 TBMIterator *tbmiterator;
1344 TBMIterateResult *tbmres;
1345 TBMIterator *prefetch_iterator;
1347 int prefetch_target;
1348 } BitmapHeapScanState;
1351 * TidScanState information
1353 * isCurrentOf scan has a CurrentOfExpr qual
1354 * NumTids number of tids in this scan
1355 * TidPtr index of currently fetched tid
1356 * TidList evaluated item pointers (array of size NumTids)
1359 typedef struct TidScanState
1361 ScanState ss; /* its first field is NodeTag */
1362 List *tss_tidquals; /* list of ExprState nodes */
1363 bool tss_isCurrentOf;
1367 ItemPointerData *tss_TidList;
1368 HeapTupleData tss_htup;
1372 * SubqueryScanState information
1374 * SubqueryScanState is used for scanning a sub-query in the range table.
1375 * ScanTupleSlot references the current output tuple of the sub-query.
1378 typedef struct SubqueryScanState
1380 ScanState ss; /* its first field is NodeTag */
1382 } SubqueryScanState;
1385 * FunctionScanState information
1387 * Function nodes are used to scan the results of a
1388 * function appearing in FROM (typically a function returning set).
1390 * eflags node's capability flags
1391 * tupdesc expected return tuple description
1392 * tuplestorestate private state of tuplestore.c
1393 * funcexpr state for function expression being evaluated
1396 typedef struct FunctionScanState
1398 ScanState ss; /* its first field is NodeTag */
1401 Tuplestorestate *tuplestorestate;
1402 ExprState *funcexpr;
1403 } FunctionScanState;
1406 * ValuesScanState information
1408 * ValuesScan nodes are used to scan the results of a VALUES list
1410 * rowcontext per-expression-list context
1411 * exprlists array of expression lists being evaluated
1412 * array_len size of array
1413 * curr_idx current array index (0-based)
1414 * marked_idx marked position (for mark/restore)
1416 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1417 * expressions attached to the node. We create a second ExprContext,
1418 * rowcontext, in which to build the executor expression state for each
1419 * Values sublist. Resetting this context lets us get rid of expression
1420 * state for each row, avoiding major memory leakage over a long values list.
1423 typedef struct ValuesScanState
1425 ScanState ss; /* its first field is NodeTag */
1426 ExprContext *rowcontext;
1434 * CteScanState information
1436 * CteScan nodes are used to scan a CommonTableExpr query.
1438 * Multiple CteScan nodes can read out from the same CTE query. We use
1439 * a tuplestore to hold rows that have been read from the CTE query but
1440 * not yet consumed by all readers.
1443 typedef struct CteScanState
1445 ScanState ss; /* its first field is NodeTag */
1446 int eflags; /* capability flags to pass to tuplestore */
1447 int readptr; /* index of my tuplestore read pointer */
1448 PlanState *cteplanstate; /* PlanState for the CTE query itself */
1449 /* Link to the "leader" CteScanState (possibly this same node) */
1450 struct CteScanState *leader;
1451 /* The remaining fields are only valid in the "leader" CteScanState */
1452 Tuplestorestate *cte_table; /* rows already read from the CTE query */
1453 bool eof_cte; /* reached end of CTE query? */
1457 * WorkTableScanState information
1459 * WorkTableScan nodes are used to scan the work table created by
1460 * a RecursiveUnion node. We locate the RecursiveUnion node
1461 * during executor startup.
1464 typedef struct WorkTableScanState
1466 ScanState ss; /* its first field is NodeTag */
1467 RecursiveUnionState *rustate;
1468 } WorkTableScanState;
1471 * ForeignScanState information
1473 * ForeignScan nodes are used to scan foreign-data tables.
1476 typedef struct ForeignScanState
1478 ScanState ss; /* its first field is NodeTag */
1479 /* use struct pointer to avoid including fdwapi.h here */
1480 struct FdwRoutine *fdwroutine;
1481 void *fdw_state; /* foreign-data wrapper can keep state here */
1484 /* ----------------------------------------------------------------
1485 * Join State Information
1486 * ----------------------------------------------------------------
1490 * JoinState information
1492 * Superclass for state nodes of join plans.
1495 typedef struct JoinState
1499 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1503 * NestLoopState information
1505 * NeedNewOuter true if need new outer tuple on next call
1506 * MatchedOuter true if found a join match for current outer tuple
1507 * NullInnerTupleSlot prepared null tuple for left outer joins
1510 typedef struct NestLoopState
1512 JoinState js; /* its first field is NodeTag */
1513 bool nl_NeedNewOuter;
1514 bool nl_MatchedOuter;
1515 TupleTableSlot *nl_NullInnerTupleSlot;
1519 * MergeJoinState information
1521 * NumClauses number of mergejoinable join clauses
1522 * Clauses info for each mergejoinable clause
1523 * JoinState current state of ExecMergeJoin state machine
1524 * ExtraMarks true to issue extra Mark operations on inner scan
1525 * ConstFalseJoin true if we have a constant-false joinqual
1526 * FillOuter true if should emit unjoined outer tuples anyway
1527 * FillInner true if should emit unjoined inner tuples anyway
1528 * MatchedOuter true if found a join match for current outer tuple
1529 * MatchedInner true if found a join match for current inner tuple
1530 * OuterTupleSlot slot in tuple table for cur outer tuple
1531 * InnerTupleSlot slot in tuple table for cur inner tuple
1532 * MarkedTupleSlot slot in tuple table for marked tuple
1533 * NullOuterTupleSlot prepared null tuple for right outer joins
1534 * NullInnerTupleSlot prepared null tuple for left outer joins
1535 * OuterEContext workspace for computing outer tuple's join values
1536 * InnerEContext workspace for computing inner tuple's join values
1539 /* private in nodeMergejoin.c: */
1540 typedef struct MergeJoinClauseData *MergeJoinClause;
1542 typedef struct MergeJoinState
1544 JoinState js; /* its first field is NodeTag */
1546 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1549 bool mj_ConstFalseJoin;
1552 bool mj_MatchedOuter;
1553 bool mj_MatchedInner;
1554 TupleTableSlot *mj_OuterTupleSlot;
1555 TupleTableSlot *mj_InnerTupleSlot;
1556 TupleTableSlot *mj_MarkedTupleSlot;
1557 TupleTableSlot *mj_NullOuterTupleSlot;
1558 TupleTableSlot *mj_NullInnerTupleSlot;
1559 ExprContext *mj_OuterEContext;
1560 ExprContext *mj_InnerEContext;
1564 * HashJoinState information
1566 * hashclauses original form of the hashjoin condition
1567 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1568 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1569 * hj_HashOperators the join operators in the hashjoin condition
1570 * hj_HashTable hash table for the hashjoin
1571 * (NULL if table not built yet)
1572 * hj_CurHashValue hash value for current outer tuple
1573 * hj_CurBucketNo regular bucket# for current outer tuple
1574 * hj_CurSkewBucketNo skew bucket# for current outer tuple
1575 * hj_CurTuple last inner tuple matched to current outer
1576 * tuple, or NULL if starting search
1577 * (hj_CurXXX variables are undefined if
1578 * OuterTupleSlot is empty!)
1579 * hj_OuterTupleSlot tuple slot for outer tuples
1580 * hj_HashTupleSlot tuple slot for inner (hashed) tuples
1581 * hj_NullOuterTupleSlot prepared null tuple for right/full outer joins
1582 * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
1583 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1584 * hj_JoinState current state of ExecHashJoin state machine
1585 * hj_MatchedOuter true if found a join match for current outer
1586 * hj_OuterNotEmpty true if outer relation known not empty
1590 /* these structs are defined in executor/hashjoin.h: */
1591 typedef struct HashJoinTupleData *HashJoinTuple;
1592 typedef struct HashJoinTableData *HashJoinTable;
1594 typedef struct HashJoinState
1596 JoinState js; /* its first field is NodeTag */
1597 List *hashclauses; /* list of ExprState nodes */
1598 List *hj_OuterHashKeys; /* list of ExprState nodes */
1599 List *hj_InnerHashKeys; /* list of ExprState nodes */
1600 List *hj_HashOperators; /* list of operator OIDs */
1601 HashJoinTable hj_HashTable;
1602 uint32 hj_CurHashValue;
1604 int hj_CurSkewBucketNo;
1605 HashJoinTuple hj_CurTuple;
1606 TupleTableSlot *hj_OuterTupleSlot;
1607 TupleTableSlot *hj_HashTupleSlot;
1608 TupleTableSlot *hj_NullOuterTupleSlot;
1609 TupleTableSlot *hj_NullInnerTupleSlot;
1610 TupleTableSlot *hj_FirstOuterTupleSlot;
1612 bool hj_MatchedOuter;
1613 bool hj_OuterNotEmpty;
1617 /* ----------------------------------------------------------------
1618 * Materialization State Information
1619 * ----------------------------------------------------------------
1623 * MaterialState information
1625 * materialize nodes are used to materialize the results
1626 * of a subplan into a temporary file.
1628 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1631 typedef struct MaterialState
1633 ScanState ss; /* its first field is NodeTag */
1634 int eflags; /* capability flags to pass to tuplestore */
1635 bool eof_underlying; /* reached end of underlying plan? */
1636 Tuplestorestate *tuplestorestate;
1640 * SortState information
1643 typedef struct SortState
1645 ScanState ss; /* its first field is NodeTag */
1646 bool randomAccess; /* need random access to sort output? */
1647 bool bounded; /* is the result set bounded? */
1648 int64 bound; /* if bounded, how many tuples are needed */
1649 bool sort_Done; /* sort completed yet? */
1650 bool bounded_Done; /* value of bounded we did the sort with */
1651 int64 bound_Done; /* value of bound we did the sort with */
1652 void *tuplesortstate; /* private state of tuplesort.c */
1655 /* ---------------------
1656 * GroupState information
1657 * -------------------------
1659 typedef struct GroupState
1661 ScanState ss; /* its first field is NodeTag */
1662 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1663 bool grp_done; /* indicates completion of Group scan */
1666 /* ---------------------
1667 * AggState information
1669 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1671 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1672 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1673 * input group during evaluation of an Agg node's output tuple(s). We
1674 * create a second ExprContext, tmpcontext, in which to evaluate input
1675 * expressions and run the aggregate transition functions.
1676 * -------------------------
1678 /* these structs are private in nodeAgg.c: */
1679 typedef struct AggStatePerAggData *AggStatePerAgg;
1680 typedef struct AggStatePerGroupData *AggStatePerGroup;
1682 typedef struct AggState
1684 ScanState ss; /* its first field is NodeTag */
1685 List *aggs; /* all Aggref nodes in targetlist & quals */
1686 int numaggs; /* length of list (could be zero!) */
1687 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1688 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1689 AggStatePerAgg peragg; /* per-Aggref information */
1690 MemoryContext aggcontext; /* memory context for long-lived data */
1691 ExprContext *tmpcontext; /* econtext for input expressions */
1692 bool agg_done; /* indicates completion of Agg scan */
1693 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1694 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1695 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1696 /* these fields are used in AGG_HASHED mode: */
1697 TupleHashTable hashtable; /* hash table with one entry per group */
1698 TupleTableSlot *hashslot; /* slot for loading hash table */
1699 List *hash_needed; /* list of columns needed in hash table */
1700 bool table_filled; /* hash table filled yet? */
1701 TupleHashIterator hashiter; /* for iterating through hash table */
1705 * WindowAggState information
1708 /* these structs are private in nodeWindowAgg.c: */
1709 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1710 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1712 typedef struct WindowAggState
1714 ScanState ss; /* its first field is NodeTag */
1716 /* these fields are filled in by ExecInitExpr: */
1717 List *funcs; /* all WindowFunc nodes in targetlist */
1718 int numfuncs; /* total number of window functions */
1719 int numaggs; /* number that are plain aggregates */
1721 WindowStatePerFunc perfunc; /* per-window-function information */
1722 WindowStatePerAgg peragg; /* per-plain-aggregate information */
1723 FmgrInfo *partEqfunctions; /* equality funcs for partition columns */
1724 FmgrInfo *ordEqfunctions; /* equality funcs for ordering columns */
1725 Tuplestorestate *buffer; /* stores rows of current partition */
1726 int current_ptr; /* read pointer # for current */
1727 int64 spooled_rows; /* total # of rows in buffer */
1728 int64 currentpos; /* position of current row in partition */
1729 int64 frameheadpos; /* current frame head position */
1730 int64 frametailpos; /* current frame tail position */
1731 /* use struct pointer to avoid including windowapi.h here */
1732 struct WindowObjectData *agg_winobj; /* winobj for aggregate
1734 int64 aggregatedbase; /* start row for current aggregates */
1735 int64 aggregatedupto; /* rows before this one are aggregated */
1737 int frameOptions; /* frame_clause options, see WindowDef */
1738 ExprState *startOffset; /* expression for starting bound offset */
1739 ExprState *endOffset; /* expression for ending bound offset */
1740 Datum startOffsetValue; /* result of startOffset evaluation */
1741 Datum endOffsetValue; /* result of endOffset evaluation */
1743 MemoryContext partcontext; /* context for partition-lifespan data */
1744 MemoryContext aggcontext; /* context for each aggregate data */
1745 ExprContext *tmpcontext; /* short-term evaluation context */
1747 bool all_first; /* true if the scan is starting */
1748 bool all_done; /* true if the scan is finished */
1749 bool partition_spooled; /* true if all tuples in current
1750 * partition have been spooled into
1752 bool more_partitions;/* true if there's more partitions after this
1754 bool framehead_valid;/* true if frameheadpos is known up to date
1755 * for current row */
1756 bool frametail_valid;/* true if frametailpos is known up to date
1757 * for current row */
1759 TupleTableSlot *first_part_slot; /* first tuple of current or next
1762 /* temporary slots for tuples fetched back from tuplestore */
1763 TupleTableSlot *agg_row_slot;
1764 TupleTableSlot *temp_slot_1;
1765 TupleTableSlot *temp_slot_2;
1769 * UniqueState information
1771 * Unique nodes are used "on top of" sort nodes to discard
1772 * duplicate tuples returned from the sort phase. Basically
1773 * all it does is compare the current tuple from the subplan
1774 * with the previously fetched tuple (stored in its result slot).
1775 * If the two are identical in all interesting fields, then
1776 * we just fetch another tuple from the sort and try again.
1779 typedef struct UniqueState
1781 PlanState ps; /* its first field is NodeTag */
1782 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1783 MemoryContext tempContext; /* short-term context for comparisons */
1787 * HashState information
1790 typedef struct HashState
1792 PlanState ps; /* its first field is NodeTag */
1793 HashJoinTable hashtable; /* hash table for the hashjoin */
1794 List *hashkeys; /* list of ExprState nodes */
1795 /* hashkeys is same as parent's hj_InnerHashKeys */
1799 * SetOpState information
1801 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1802 * Unique, since we have to count how many duplicates to return. But
1803 * we also support hashing, so this is really more like a cut-down
1807 /* this struct is private in nodeSetOp.c: */
1808 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1810 typedef struct SetOpState
1812 PlanState ps; /* its first field is NodeTag */
1813 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1814 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1815 bool setop_done; /* indicates completion of output scan */
1816 long numOutput; /* number of dups left to output */
1817 MemoryContext tempContext; /* short-term context for comparisons */
1818 /* these fields are used in SETOP_SORTED mode: */
1819 SetOpStatePerGroup pergroup; /* per-group working state */
1820 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1821 /* these fields are used in SETOP_HASHED mode: */
1822 TupleHashTable hashtable; /* hash table with one entry per group */
1823 MemoryContext tableContext; /* memory context containing hash table */
1824 bool table_filled; /* hash table filled yet? */
1825 TupleHashIterator hashiter; /* for iterating through hash table */
1829 * LockRowsState information
1831 * LockRows nodes are used to enforce FOR UPDATE/FOR SHARE locking.
1834 typedef struct LockRowsState
1836 PlanState ps; /* its first field is NodeTag */
1837 List *lr_arowMarks; /* List of ExecAuxRowMarks */
1838 EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
1842 * LimitState information
1844 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1845 * They just select the desired subrange of their subplan's output.
1847 * offset is the number of initial tuples to skip (0 does nothing).
1848 * count is the number of tuples to return after skipping the offset tuples.
1849 * If no limit count was specified, count is undefined and noCount is true.
1850 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1855 LIMIT_INITIAL, /* initial state for LIMIT node */
1856 LIMIT_RESCAN, /* rescan after recomputing parameters */
1857 LIMIT_EMPTY, /* there are no returnable rows */
1858 LIMIT_INWINDOW, /* have returned a row in the window */
1859 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1860 LIMIT_WINDOWEND, /* stepped off end of window */
1861 LIMIT_WINDOWSTART /* stepped off beginning of window */
1864 typedef struct LimitState
1866 PlanState ps; /* its first field is NodeTag */
1867 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1868 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1869 int64 offset; /* current OFFSET value */
1870 int64 count; /* current COUNT, if any */
1871 bool noCount; /* if true, ignore count */
1872 LimitStateCond lstate; /* state machine status, as above */
1873 int64 position; /* 1-based index of last tuple returned */
1874 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1877 #endif /* EXECNODES_H */