1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2011, 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_select_into; /* true if doing SELECT INTO */
375 bool es_into_oids; /* true to generate OIDs in SELECT INTO */
376 bool es_finished; /* true when ExecutorFinish is done */
378 List *es_exprcontexts; /* List of ExprContexts within EState */
380 List *es_subplanstates; /* List of PlanState for SubPlans */
382 List *es_auxmodifytables; /* List of secondary ModifyTableStates */
385 * this ExprContext is for per-output-tuple operations, such as constraint
386 * checks and index-value computations. It will be reset for each output
387 * tuple. Note that it will be created only if needed.
389 ExprContext *es_per_tuple_exprcontext;
392 * These fields are for re-evaluating plan quals when an updated tuple is
393 * substituted in READ COMMITTED mode. es_epqTuple[] contains tuples that
394 * scan plan nodes should return instead of whatever they'd normally
395 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
396 * particular array entry is valid; and es_epqScanDone[] is state to
397 * remember if the tuple has been returned already. Arrays are of size
398 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
400 HeapTuple *es_epqTuple; /* array of EPQ substitute tuples */
401 bool *es_epqTupleSet; /* true if EPQ tuple is provided */
402 bool *es_epqScanDone; /* true if EPQ tuple has been fetched */
408 * runtime representation of FOR UPDATE/SHARE clauses
410 * When doing UPDATE, DELETE, or SELECT FOR UPDATE/SHARE, we should have an
411 * ExecRowMark for each non-target relation in the query (except inheritance
412 * parent RTEs, which can be ignored at runtime). See PlanRowMark for details
413 * about most of the fields. In addition to fields directly derived from
414 * PlanRowMark, we store curCtid, which is used by the WHERE CURRENT OF code.
416 * EState->es_rowMarks is a list of these structs.
418 typedef struct ExecRowMark
420 Relation relation; /* opened and suitably locked relation */
421 Index rti; /* its range table index */
422 Index prti; /* parent range table index, if child */
423 Index rowmarkId; /* unique identifier for resjunk columns */
424 RowMarkType markType; /* see enum in nodes/plannodes.h */
425 bool noWait; /* NOWAIT option */
426 ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
431 * additional runtime representation of FOR UPDATE/SHARE clauses
433 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
434 * deal with. In addition to a pointer to the related entry in es_rowMarks,
435 * this struct carries the column number(s) of the resjunk columns associated
436 * with the rowmark (see comments for PlanRowMark for more detail). In the
437 * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
438 * each child plan, because the resjunk columns could be at different physical
439 * column positions in different subplans.
441 typedef struct ExecAuxRowMark
443 ExecRowMark *rowmark; /* related entry in es_rowMarks */
444 AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
445 AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
446 AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
450 /* ----------------------------------------------------------------
453 * All-in-memory tuple hash tables are used for a number of purposes.
455 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
456 * and tab_eq_funcs are non-cross-type equality operators for those types.
457 * Normally these are the only functions used, but FindTupleHashEntry()
458 * supports searching a hashtable using cross-data-type hashing. For that,
459 * the caller must supply hash functions for the LHS datatype as well as
460 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
461 * are set to point to the caller's function arrays while doing such a search.
462 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
463 * tab_eq_funcs respectively.
464 * ----------------------------------------------------------------
466 typedef struct TupleHashEntryData *TupleHashEntry;
467 typedef struct TupleHashTableData *TupleHashTable;
469 typedef struct TupleHashEntryData
471 /* firstTuple must be the first field in this struct! */
472 MinimalTuple firstTuple; /* copy of first tuple in this group */
473 /* there may be additional data beyond the end of this struct */
474 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
476 typedef struct TupleHashTableData
478 HTAB *hashtab; /* underlying dynahash table */
479 int numCols; /* number of columns in lookup key */
480 AttrNumber *keyColIdx; /* attr numbers of key columns */
481 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
482 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
483 MemoryContext tablecxt; /* memory context containing table */
484 MemoryContext tempcxt; /* context for function evaluations */
485 Size entrysize; /* actual size to make each hash entry */
486 TupleTableSlot *tableslot; /* slot for referencing table entries */
487 /* The following fields are set transiently for each table search: */
488 TupleTableSlot *inputslot; /* current input tuple's slot */
489 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
490 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
491 } TupleHashTableData;
493 typedef HASH_SEQ_STATUS TupleHashIterator;
496 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
497 * Use ResetTupleHashIterator if the table can be frozen (in this case no
498 * explicit scan termination is needed).
500 #define InitTupleHashIterator(htable, iter) \
501 hash_seq_init(iter, (htable)->hashtab)
502 #define TermTupleHashIterator(iter) \
504 #define ResetTupleHashIterator(htable, iter) \
506 hash_freeze((htable)->hashtab); \
507 hash_seq_init(iter, (htable)->hashtab); \
509 #define ScanTupleHashTable(iter) \
510 ((TupleHashEntry) hash_seq_search(iter))
513 /* ----------------------------------------------------------------
514 * Expression State Trees
516 * Each executable expression tree has a parallel ExprState tree.
518 * Unlike PlanState, there is not an exact one-for-one correspondence between
519 * ExprState node types and Expr node types. Many Expr node types have no
520 * need for node-type-specific run-time state, and so they can use plain
521 * ExprState or GenericExprState as their associated ExprState node type.
522 * ----------------------------------------------------------------
528 * ExprState is the common superclass for all ExprState-type nodes.
530 * It can also be instantiated directly for leaf Expr nodes that need no
531 * local run-time state (such as Var, Const, or Param).
533 * To save on dispatch overhead, each ExprState node contains a function
534 * pointer to the routine to execute to evaluate the node.
538 typedef struct ExprState ExprState;
540 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
541 ExprContext *econtext,
543 ExprDoneCond *isDone);
548 Expr *expr; /* associated Expr node */
549 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
553 * GenericExprState node
555 * This is used for Expr node types that need no local run-time state,
556 * but have one child Expr node.
559 typedef struct GenericExprState
562 ExprState *arg; /* state of my child node */
566 * AggrefExprState node
569 typedef struct AggrefExprState
572 List *args; /* states of argument expressions */
573 int aggno; /* ID number for agg within its plan node */
577 * WindowFuncExprState node
580 typedef struct WindowFuncExprState
583 List *args; /* states of argument expressions */
584 int wfuncno; /* ID number for wfunc within its plan node */
585 } WindowFuncExprState;
588 * ArrayRefExprState node
590 * Note: array types can be fixed-length (typlen > 0), but only when the
591 * element type is itself fixed-length. Otherwise they are varlena structures
592 * and have typlen = -1. In any case, an array type is never pass-by-value.
595 typedef struct ArrayRefExprState
598 List *refupperindexpr; /* states for child nodes */
599 List *reflowerindexpr;
601 ExprState *refassgnexpr;
602 int16 refattrlength; /* typlen of array type */
603 int16 refelemlength; /* typlen of the array element type */
604 bool refelembyval; /* is the element type pass-by-value? */
605 char refelemalign; /* typalign of the element type */
611 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
612 * and NullIf nodes; be careful to check what xprstate.expr is actually
616 typedef struct FuncExprState
619 List *args; /* states of argument expressions */
622 * Function manager's lookup info for the target function. If func.fn_oid
623 * is InvalidOid, we haven't initialized it yet (nor any of the following
629 * For a set-returning function (SRF) that returns a tuplestore, we keep
630 * the tuplestore here and dole out the result rows one at a time. The
631 * slot holds the row currently being returned.
633 Tuplestorestate *funcResultStore;
634 TupleTableSlot *funcResultSlot;
637 * In some cases we need to compute a tuple descriptor for the function's
638 * output. If so, it's stored here.
640 TupleDesc funcResultDesc;
641 bool funcReturnsTuple; /* valid when funcResultDesc isn't
645 * setArgsValid is true when we are evaluating a set-returning function
646 * that uses value-per-call mode and we are in the middle of a call
647 * series; we want to pass the same argument values to the function again
648 * (and again, until it returns ExprEndResult). This indicates that
649 * fcinfo_data already contains valid argument data.
654 * Flag to remember whether we found a set-valued argument to the
655 * function. This causes the function result to be a set as well. Valid
656 * only when setArgsValid is true or funcResultStore isn't NULL.
658 bool setHasSetArg; /* some argument returns a set */
661 * Flag to remember whether we have registered a shutdown callback for
662 * this FuncExprState. We do so only if funcResultStore or setArgsValid
663 * has been set at least once (since all the callback is for is to release
664 * the tuplestore or clear setArgsValid).
666 bool shutdown_reg; /* a shutdown callback is registered */
669 * Call parameter structure for the function. This has been initialized
670 * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
671 * argument values between calls, when setArgsValid is true.
673 FunctionCallInfoData fcinfo_data;
677 * ScalarArrayOpExprState node
679 * This is a FuncExprState plus some additional data.
682 typedef struct ScalarArrayOpExprState
684 FuncExprState fxprstate;
685 /* Cached info about array element type */
690 } ScalarArrayOpExprState;
696 typedef struct BoolExprState
699 List *args; /* states of argument expression(s) */
706 typedef struct SubPlanState
709 struct PlanState *planstate; /* subselect plan's state tree */
710 ExprState *testexpr; /* state of combining expression */
711 List *args; /* states of argument expression(s) */
712 HeapTuple curTuple; /* copy of most recent tuple from subplan */
713 /* these are used when hashing the subselect's output: */
714 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
715 ProjectionInfo *projRight; /* for projecting subselect output */
716 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
717 TupleHashTable hashnulls; /* hash table for rows with null(s) */
718 bool havehashrows; /* TRUE if hashtable is not empty */
719 bool havenullrows; /* TRUE if hashnulls is not empty */
720 MemoryContext hashtablecxt; /* memory context containing hash tables */
721 MemoryContext hashtempcxt; /* temp memory context for hash tables */
722 ExprContext *innerecontext; /* econtext for computing inner tuples */
723 AttrNumber *keyColIdx; /* control data for hash tables */
724 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
725 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
726 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
727 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
731 * AlternativeSubPlanState node
734 typedef struct AlternativeSubPlanState
737 List *subplans; /* states of alternative subplans */
738 int active; /* list index of the one we're using */
739 } AlternativeSubPlanState;
742 * FieldSelectState node
745 typedef struct FieldSelectState
748 ExprState *arg; /* input expression */
749 TupleDesc argdesc; /* tupdesc for most recent input */
753 * FieldStoreState node
756 typedef struct FieldStoreState
759 ExprState *arg; /* input tuple value */
760 List *newvals; /* new value(s) for field(s) */
761 TupleDesc argdesc; /* tupdesc for most recent input */
765 * CoerceViaIOState node
768 typedef struct CoerceViaIOState
771 ExprState *arg; /* input expression */
772 FmgrInfo outfunc; /* lookup info for source output function */
773 FmgrInfo infunc; /* lookup info for result input function */
774 Oid intypioparam; /* argument needed for input function */
778 * ArrayCoerceExprState node
781 typedef struct ArrayCoerceExprState
784 ExprState *arg; /* input array value */
785 Oid resultelemtype; /* element type of result array */
786 FmgrInfo elemfunc; /* lookup info for element coercion function */
787 /* use struct pointer to avoid including array.h here */
788 struct ArrayMapState *amstate; /* workspace for array_map */
789 } ArrayCoerceExprState;
792 * ConvertRowtypeExprState node
795 typedef struct ConvertRowtypeExprState
798 ExprState *arg; /* input tuple value */
799 TupleDesc indesc; /* tupdesc for source rowtype */
800 TupleDesc outdesc; /* tupdesc for result rowtype */
801 /* use "struct" so we needn't include tupconvert.h here */
802 struct TupleConversionMap *map;
804 } ConvertRowtypeExprState;
810 typedef struct CaseExprState
813 ExprState *arg; /* implicit equality comparison argument */
814 List *args; /* the arguments (list of WHEN clauses) */
815 ExprState *defresult; /* the default result (ELSE clause) */
822 typedef struct CaseWhenState
825 ExprState *expr; /* condition expression */
826 ExprState *result; /* substitution result */
830 * ArrayExprState node
832 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
836 typedef struct ArrayExprState
839 List *elements; /* states for child nodes */
840 int16 elemlength; /* typlen of the array element type */
841 bool elembyval; /* is the element type pass-by-value? */
842 char elemalign; /* typalign of the element type */
849 typedef struct RowExprState
852 List *args; /* the arguments */
853 TupleDesc tupdesc; /* descriptor for result tuples */
857 * RowCompareExprState node
860 typedef struct RowCompareExprState
863 List *largs; /* the left-hand input arguments */
864 List *rargs; /* the right-hand input arguments */
865 FmgrInfo *funcs; /* array of comparison function info */
866 Oid *collations; /* array of collations to use */
867 } RowCompareExprState;
870 * CoalesceExprState node
873 typedef struct CoalesceExprState
876 List *args; /* the arguments */
880 * MinMaxExprState node
883 typedef struct MinMaxExprState
886 List *args; /* the arguments */
887 FmgrInfo cfunc; /* lookup info for comparison func */
894 typedef struct XmlExprState
897 List *named_args; /* ExprStates for named arguments */
898 List *args; /* ExprStates for other arguments */
905 typedef struct NullTestState
908 ExprState *arg; /* input expression */
909 /* used only if input is of composite type: */
910 TupleDesc argdesc; /* tupdesc for most recent input */
914 * CoerceToDomainState node
917 typedef struct CoerceToDomainState
920 ExprState *arg; /* input expression */
921 /* Cached list of constraints that need to be checked */
922 List *constraints; /* list of DomainConstraintState nodes */
923 } CoerceToDomainState;
926 * DomainConstraintState - one item to check during CoerceToDomain
928 * Note: this is just a Node, and not an ExprState, because it has no
929 * corresponding Expr to link to. Nonetheless it is part of an ExprState
930 * tree, so we give it a name following the xxxState convention.
932 typedef enum DomainConstraintType
934 DOM_CONSTRAINT_NOTNULL,
936 } DomainConstraintType;
938 typedef struct DomainConstraintState
941 DomainConstraintType constrainttype; /* constraint type */
942 char *name; /* name of constraint (for error msgs) */
943 ExprState *check_expr; /* for CHECK, a boolean expression */
944 } DomainConstraintState;
947 /* ----------------------------------------------------------------
948 * Executor State Trees
950 * An executing query has a PlanState tree paralleling the Plan tree
951 * that describes the plan.
952 * ----------------------------------------------------------------
958 * We never actually instantiate any PlanState nodes; this is just the common
959 * abstract superclass for all PlanState-type nodes.
962 typedef struct PlanState
966 Plan *plan; /* associated Plan node */
968 EState *state; /* at execution time, states of individual
969 * nodes point to one EState for the whole
972 Instrumentation *instrument; /* Optional runtime stats for this node */
975 * Common structural data for all Plan types. These links to subsidiary
976 * state trees parallel links in the associated plan tree (except for the
977 * subPlan list, which does not exist in the plan tree).
979 List *targetlist; /* target list to be computed at this node */
980 List *qual; /* implicitly-ANDed qual conditions */
981 struct PlanState *lefttree; /* input plan tree(s) */
982 struct PlanState *righttree;
983 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
985 List *subPlan; /* SubPlanState nodes in my expressions */
988 * State for management of parameter-change-driven rescanning
990 Bitmapset *chgParam; /* set of IDs of changed Params */
993 * Other run-time state needed by most if not all node types.
995 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
996 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
997 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
998 bool ps_TupFromTlist;/* state flag for processing set-valued
999 * functions in targetlist */
1003 * these are defined to avoid confusion problems with "left"
1004 * and "right" and "inner" and "outer". The convention is that
1005 * the "left" plan is the "outer" plan and the "right" plan is
1006 * the inner plan, but these make the code more readable.
1009 #define innerPlanState(node) (((PlanState *)(node))->righttree)
1010 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
1012 /* Macros for inline access to certain instrumentation counters */
1013 #define InstrCountFiltered1(node, delta) \
1015 if (((PlanState *)(node))->instrument) \
1016 ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
1018 #define InstrCountFiltered2(node, delta) \
1020 if (((PlanState *)(node))->instrument) \
1021 ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
1025 * EPQState is state for executing an EvalPlanQual recheck on a candidate
1026 * tuple in ModifyTable or LockRows. The estate and planstate fields are
1029 typedef struct EPQState
1031 EState *estate; /* subsidiary EState */
1032 PlanState *planstate; /* plan state tree ready to be executed */
1033 TupleTableSlot *origslot; /* original output tuple to be rechecked */
1034 Plan *plan; /* plan tree to be executed */
1035 List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
1036 int epqParam; /* ID of Param to force scan node re-eval */
1041 * ResultState information
1044 typedef struct ResultState
1046 PlanState ps; /* its first field is NodeTag */
1047 ExprState *resconstantqual;
1048 bool rs_done; /* are we done? */
1049 bool rs_checkqual; /* do we need to check the qual? */
1053 * ModifyTableState information
1056 typedef struct ModifyTableState
1058 PlanState ps; /* its first field is NodeTag */
1059 CmdType operation; /* INSERT, UPDATE, or DELETE */
1060 bool canSetTag; /* do we set the command tag/es_processed? */
1061 bool mt_done; /* are we done? */
1062 PlanState **mt_plans; /* subplans (one per target rel) */
1063 int mt_nplans; /* number of plans in the array */
1064 int mt_whichplan; /* which one is being executed (0..n-1) */
1065 ResultRelInfo *resultRelInfo; /* per-subplan target relations */
1066 List **mt_arowmarks; /* per-subplan ExecAuxRowMark lists */
1067 EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
1068 bool fireBSTriggers; /* do we need to fire stmt triggers? */
1072 * AppendState information
1074 * nplans how many plans are in the array
1075 * whichplan which plan is being executed (0 .. n-1)
1078 typedef struct AppendState
1080 PlanState ps; /* its first field is NodeTag */
1081 PlanState **appendplans; /* array of PlanStates for my inputs */
1087 * MergeAppendState information
1089 * nplans how many plans are in the array
1090 * nkeys number of sort key columns
1091 * sortkeys sort keys in SortSupport representation
1092 * slots current output tuple of each subplan
1093 * heap heap of active tuples (represented as array indexes)
1094 * heap_size number of active heap entries
1095 * initialized true if we have fetched first tuple from each subplan
1096 * last_slot last subplan fetched from (which must be re-called)
1099 typedef struct MergeAppendState
1101 PlanState ps; /* its first field is NodeTag */
1102 PlanState **mergeplans; /* array of PlanStates for my inputs */
1105 SortSupport ms_sortkeys; /* array of length ms_nkeys */
1106 TupleTableSlot **ms_slots; /* array of length ms_nplans */
1107 int *ms_heap; /* array of length ms_nplans */
1108 int ms_heap_size; /* current active length of ms_heap[] */
1109 bool ms_initialized; /* are subplans started? */
1110 int ms_last_slot; /* last subplan slot we returned from */
1114 * RecursiveUnionState information
1116 * RecursiveUnionState is used for performing a recursive union.
1118 * recursing T when we're done scanning the non-recursive term
1119 * intermediate_empty T if intermediate_table is currently empty
1120 * working_table working table (to be scanned by recursive term)
1121 * intermediate_table current recursive output (next generation of WT)
1124 typedef struct RecursiveUnionState
1126 PlanState ps; /* its first field is NodeTag */
1128 bool intermediate_empty;
1129 Tuplestorestate *working_table;
1130 Tuplestorestate *intermediate_table;
1131 /* Remaining fields are unused in UNION ALL case */
1132 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1133 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1134 MemoryContext tempContext; /* short-term context for comparisons */
1135 TupleHashTable hashtable; /* hash table for tuples already seen */
1136 MemoryContext tableContext; /* memory context containing hash table */
1137 } RecursiveUnionState;
1140 * BitmapAndState information
1143 typedef struct BitmapAndState
1145 PlanState ps; /* its first field is NodeTag */
1146 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1147 int nplans; /* number of input plans */
1151 * BitmapOrState information
1154 typedef struct BitmapOrState
1156 PlanState ps; /* its first field is NodeTag */
1157 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1158 int nplans; /* number of input plans */
1161 /* ----------------------------------------------------------------
1162 * Scan State Information
1163 * ----------------------------------------------------------------
1167 * ScanState information
1169 * ScanState extends PlanState for node types that represent
1170 * scans of an underlying relation. It can also be used for nodes
1171 * that scan the output of an underlying plan node --- in that case,
1172 * only ScanTupleSlot is actually useful, and it refers to the tuple
1173 * retrieved from the subplan.
1175 * currentRelation relation being scanned (NULL if none)
1176 * currentScanDesc current scan descriptor for scan (NULL if none)
1177 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
1180 typedef struct ScanState
1182 PlanState ps; /* its first field is NodeTag */
1183 Relation ss_currentRelation;
1184 HeapScanDesc ss_currentScanDesc;
1185 TupleTableSlot *ss_ScanTupleSlot;
1189 * SeqScan uses a bare ScanState as its state node, since it needs
1190 * no additional fields.
1192 typedef ScanState SeqScanState;
1195 * These structs store information about index quals that don't have simple
1196 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1201 ScanKey scan_key; /* scankey to put value into */
1202 ExprState *key_expr; /* expr to evaluate to get value */
1203 bool key_toastable; /* is expr's result a toastable datatype? */
1204 } IndexRuntimeKeyInfo;
1208 ScanKey scan_key; /* scankey to put value into */
1209 ExprState *array_expr; /* expr to evaluate to get array value */
1210 int next_elem; /* next array element to use */
1211 int num_elems; /* number of elems in current array value */
1212 Datum *elem_values; /* array of num_elems Datums */
1213 bool *elem_nulls; /* array of num_elems is-null flags */
1214 } IndexArrayKeyInfo;
1217 * IndexScanState information
1219 * indexqualorig execution state for indexqualorig expressions
1220 * ScanKeys Skey structures for index quals
1221 * NumScanKeys number of ScanKeys
1222 * OrderByKeys Skey structures for index ordering operators
1223 * NumOrderByKeys number of OrderByKeys
1224 * RuntimeKeys info about Skeys that must be evaluated at runtime
1225 * NumRuntimeKeys number of RuntimeKeys
1226 * RuntimeKeysReady true if runtime Skeys have been computed
1227 * RuntimeContext expr context for evaling runtime Skeys
1228 * RelationDesc index relation descriptor
1229 * ScanDesc index scan descriptor
1232 typedef struct IndexScanState
1234 ScanState ss; /* its first field is NodeTag */
1235 List *indexqualorig;
1236 ScanKey iss_ScanKeys;
1237 int iss_NumScanKeys;
1238 ScanKey iss_OrderByKeys;
1239 int iss_NumOrderByKeys;
1240 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1241 int iss_NumRuntimeKeys;
1242 bool iss_RuntimeKeysReady;
1243 ExprContext *iss_RuntimeContext;
1244 Relation iss_RelationDesc;
1245 IndexScanDesc iss_ScanDesc;
1249 * IndexOnlyScanState information
1251 * indexqual execution state for indexqual expressions
1252 * ScanKeys Skey structures for index quals
1253 * NumScanKeys number of ScanKeys
1254 * OrderByKeys Skey structures for index ordering operators
1255 * NumOrderByKeys number of OrderByKeys
1256 * RuntimeKeys info about Skeys that must be evaluated at runtime
1257 * NumRuntimeKeys number of RuntimeKeys
1258 * RuntimeKeysReady true if runtime Skeys have been computed
1259 * RuntimeContext expr context for evaling runtime Skeys
1260 * RelationDesc index relation descriptor
1261 * ScanDesc index scan descriptor
1262 * VMBuffer buffer in use for visibility map testing, if any
1265 typedef struct IndexOnlyScanState
1267 ScanState ss; /* its first field is NodeTag */
1269 ScanKey ioss_ScanKeys;
1270 int ioss_NumScanKeys;
1271 ScanKey ioss_OrderByKeys;
1272 int ioss_NumOrderByKeys;
1273 IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1274 int ioss_NumRuntimeKeys;
1275 bool ioss_RuntimeKeysReady;
1276 ExprContext *ioss_RuntimeContext;
1277 Relation ioss_RelationDesc;
1278 IndexScanDesc ioss_ScanDesc;
1279 Buffer ioss_VMBuffer;
1280 } IndexOnlyScanState;
1283 * BitmapIndexScanState information
1285 * result bitmap to return output into, or NULL
1286 * ScanKeys Skey structures for index quals
1287 * NumScanKeys number of ScanKeys
1288 * RuntimeKeys info about Skeys that must be evaluated at runtime
1289 * NumRuntimeKeys number of RuntimeKeys
1290 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1291 * NumArrayKeys number of ArrayKeys
1292 * RuntimeKeysReady true if runtime Skeys have been computed
1293 * RuntimeContext expr context for evaling runtime Skeys
1294 * RelationDesc index relation descriptor
1295 * ScanDesc index scan descriptor
1298 typedef struct BitmapIndexScanState
1300 ScanState ss; /* its first field is NodeTag */
1301 TIDBitmap *biss_result;
1302 ScanKey biss_ScanKeys;
1303 int biss_NumScanKeys;
1304 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1305 int biss_NumRuntimeKeys;
1306 IndexArrayKeyInfo *biss_ArrayKeys;
1307 int biss_NumArrayKeys;
1308 bool biss_RuntimeKeysReady;
1309 ExprContext *biss_RuntimeContext;
1310 Relation biss_RelationDesc;
1311 IndexScanDesc biss_ScanDesc;
1312 } BitmapIndexScanState;
1315 * BitmapHeapScanState information
1317 * bitmapqualorig execution state for bitmapqualorig expressions
1318 * tbm bitmap obtained from child index scan(s)
1319 * tbmiterator iterator for scanning current pages
1320 * tbmres current-page data
1321 * prefetch_iterator iterator for prefetching ahead of current page
1322 * prefetch_pages # pages prefetch iterator is ahead of current
1323 * prefetch_target target prefetch distance
1326 typedef struct BitmapHeapScanState
1328 ScanState ss; /* its first field is NodeTag */
1329 List *bitmapqualorig;
1331 TBMIterator *tbmiterator;
1332 TBMIterateResult *tbmres;
1333 TBMIterator *prefetch_iterator;
1335 int prefetch_target;
1336 } BitmapHeapScanState;
1339 * TidScanState information
1341 * isCurrentOf scan has a CurrentOfExpr qual
1342 * NumTids number of tids in this scan
1343 * TidPtr index of currently fetched tid
1344 * TidList evaluated item pointers (array of size NumTids)
1347 typedef struct TidScanState
1349 ScanState ss; /* its first field is NodeTag */
1350 List *tss_tidquals; /* list of ExprState nodes */
1351 bool tss_isCurrentOf;
1355 ItemPointerData *tss_TidList;
1356 HeapTupleData tss_htup;
1360 * SubqueryScanState information
1362 * SubqueryScanState is used for scanning a sub-query in the range table.
1363 * ScanTupleSlot references the current output tuple of the sub-query.
1366 typedef struct SubqueryScanState
1368 ScanState ss; /* its first field is NodeTag */
1370 } SubqueryScanState;
1373 * FunctionScanState information
1375 * Function nodes are used to scan the results of a
1376 * function appearing in FROM (typically a function returning set).
1378 * eflags node's capability flags
1379 * tupdesc expected return tuple description
1380 * tuplestorestate private state of tuplestore.c
1381 * funcexpr state for function expression being evaluated
1384 typedef struct FunctionScanState
1386 ScanState ss; /* its first field is NodeTag */
1389 Tuplestorestate *tuplestorestate;
1390 ExprState *funcexpr;
1391 } FunctionScanState;
1394 * ValuesScanState information
1396 * ValuesScan nodes are used to scan the results of a VALUES list
1398 * rowcontext per-expression-list context
1399 * exprlists array of expression lists being evaluated
1400 * array_len size of array
1401 * curr_idx current array index (0-based)
1402 * marked_idx marked position (for mark/restore)
1404 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1405 * expressions attached to the node. We create a second ExprContext,
1406 * rowcontext, in which to build the executor expression state for each
1407 * Values sublist. Resetting this context lets us get rid of expression
1408 * state for each row, avoiding major memory leakage over a long values list.
1411 typedef struct ValuesScanState
1413 ScanState ss; /* its first field is NodeTag */
1414 ExprContext *rowcontext;
1422 * CteScanState information
1424 * CteScan nodes are used to scan a CommonTableExpr query.
1426 * Multiple CteScan nodes can read out from the same CTE query. We use
1427 * a tuplestore to hold rows that have been read from the CTE query but
1428 * not yet consumed by all readers.
1431 typedef struct CteScanState
1433 ScanState ss; /* its first field is NodeTag */
1434 int eflags; /* capability flags to pass to tuplestore */
1435 int readptr; /* index of my tuplestore read pointer */
1436 PlanState *cteplanstate; /* PlanState for the CTE query itself */
1437 /* Link to the "leader" CteScanState (possibly this same node) */
1438 struct CteScanState *leader;
1439 /* The remaining fields are only valid in the "leader" CteScanState */
1440 Tuplestorestate *cte_table; /* rows already read from the CTE query */
1441 bool eof_cte; /* reached end of CTE query? */
1445 * WorkTableScanState information
1447 * WorkTableScan nodes are used to scan the work table created by
1448 * a RecursiveUnion node. We locate the RecursiveUnion node
1449 * during executor startup.
1452 typedef struct WorkTableScanState
1454 ScanState ss; /* its first field is NodeTag */
1455 RecursiveUnionState *rustate;
1456 } WorkTableScanState;
1459 * ForeignScanState information
1461 * ForeignScan nodes are used to scan foreign-data tables.
1464 typedef struct ForeignScanState
1466 ScanState ss; /* its first field is NodeTag */
1467 /* use struct pointer to avoid including fdwapi.h here */
1468 struct FdwRoutine *fdwroutine;
1469 void *fdw_state; /* foreign-data wrapper can keep state here */
1472 /* ----------------------------------------------------------------
1473 * Join State Information
1474 * ----------------------------------------------------------------
1478 * JoinState information
1480 * Superclass for state nodes of join plans.
1483 typedef struct JoinState
1487 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1491 * NestLoopState information
1493 * NeedNewOuter true if need new outer tuple on next call
1494 * MatchedOuter true if found a join match for current outer tuple
1495 * NullInnerTupleSlot prepared null tuple for left outer joins
1498 typedef struct NestLoopState
1500 JoinState js; /* its first field is NodeTag */
1501 bool nl_NeedNewOuter;
1502 bool nl_MatchedOuter;
1503 TupleTableSlot *nl_NullInnerTupleSlot;
1507 * MergeJoinState information
1509 * NumClauses number of mergejoinable join clauses
1510 * Clauses info for each mergejoinable clause
1511 * JoinState current state of ExecMergeJoin state machine
1512 * ExtraMarks true to issue extra Mark operations on inner scan
1513 * ConstFalseJoin true if we have a constant-false joinqual
1514 * FillOuter true if should emit unjoined outer tuples anyway
1515 * FillInner true if should emit unjoined inner tuples anyway
1516 * MatchedOuter true if found a join match for current outer tuple
1517 * MatchedInner true if found a join match for current inner tuple
1518 * OuterTupleSlot slot in tuple table for cur outer tuple
1519 * InnerTupleSlot slot in tuple table for cur inner tuple
1520 * MarkedTupleSlot slot in tuple table for marked tuple
1521 * NullOuterTupleSlot prepared null tuple for right outer joins
1522 * NullInnerTupleSlot prepared null tuple for left outer joins
1523 * OuterEContext workspace for computing outer tuple's join values
1524 * InnerEContext workspace for computing inner tuple's join values
1527 /* private in nodeMergejoin.c: */
1528 typedef struct MergeJoinClauseData *MergeJoinClause;
1530 typedef struct MergeJoinState
1532 JoinState js; /* its first field is NodeTag */
1534 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1537 bool mj_ConstFalseJoin;
1540 bool mj_MatchedOuter;
1541 bool mj_MatchedInner;
1542 TupleTableSlot *mj_OuterTupleSlot;
1543 TupleTableSlot *mj_InnerTupleSlot;
1544 TupleTableSlot *mj_MarkedTupleSlot;
1545 TupleTableSlot *mj_NullOuterTupleSlot;
1546 TupleTableSlot *mj_NullInnerTupleSlot;
1547 ExprContext *mj_OuterEContext;
1548 ExprContext *mj_InnerEContext;
1552 * HashJoinState information
1554 * hashclauses original form of the hashjoin condition
1555 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1556 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1557 * hj_HashOperators the join operators in the hashjoin condition
1558 * hj_HashTable hash table for the hashjoin
1559 * (NULL if table not built yet)
1560 * hj_CurHashValue hash value for current outer tuple
1561 * hj_CurBucketNo regular bucket# for current outer tuple
1562 * hj_CurSkewBucketNo skew bucket# for current outer tuple
1563 * hj_CurTuple last inner tuple matched to current outer
1564 * tuple, or NULL if starting search
1565 * (hj_CurXXX variables are undefined if
1566 * OuterTupleSlot is empty!)
1567 * hj_OuterTupleSlot tuple slot for outer tuples
1568 * hj_HashTupleSlot tuple slot for inner (hashed) tuples
1569 * hj_NullOuterTupleSlot prepared null tuple for right/full outer joins
1570 * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
1571 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1572 * hj_JoinState current state of ExecHashJoin state machine
1573 * hj_MatchedOuter true if found a join match for current outer
1574 * hj_OuterNotEmpty true if outer relation known not empty
1578 /* these structs are defined in executor/hashjoin.h: */
1579 typedef struct HashJoinTupleData *HashJoinTuple;
1580 typedef struct HashJoinTableData *HashJoinTable;
1582 typedef struct HashJoinState
1584 JoinState js; /* its first field is NodeTag */
1585 List *hashclauses; /* list of ExprState nodes */
1586 List *hj_OuterHashKeys; /* list of ExprState nodes */
1587 List *hj_InnerHashKeys; /* list of ExprState nodes */
1588 List *hj_HashOperators; /* list of operator OIDs */
1589 HashJoinTable hj_HashTable;
1590 uint32 hj_CurHashValue;
1592 int hj_CurSkewBucketNo;
1593 HashJoinTuple hj_CurTuple;
1594 TupleTableSlot *hj_OuterTupleSlot;
1595 TupleTableSlot *hj_HashTupleSlot;
1596 TupleTableSlot *hj_NullOuterTupleSlot;
1597 TupleTableSlot *hj_NullInnerTupleSlot;
1598 TupleTableSlot *hj_FirstOuterTupleSlot;
1600 bool hj_MatchedOuter;
1601 bool hj_OuterNotEmpty;
1605 /* ----------------------------------------------------------------
1606 * Materialization State Information
1607 * ----------------------------------------------------------------
1611 * MaterialState information
1613 * materialize nodes are used to materialize the results
1614 * of a subplan into a temporary file.
1616 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1619 typedef struct MaterialState
1621 ScanState ss; /* its first field is NodeTag */
1622 int eflags; /* capability flags to pass to tuplestore */
1623 bool eof_underlying; /* reached end of underlying plan? */
1624 Tuplestorestate *tuplestorestate;
1628 * SortState information
1631 typedef struct SortState
1633 ScanState ss; /* its first field is NodeTag */
1634 bool randomAccess; /* need random access to sort output? */
1635 bool bounded; /* is the result set bounded? */
1636 int64 bound; /* if bounded, how many tuples are needed */
1637 bool sort_Done; /* sort completed yet? */
1638 bool bounded_Done; /* value of bounded we did the sort with */
1639 int64 bound_Done; /* value of bound we did the sort with */
1640 void *tuplesortstate; /* private state of tuplesort.c */
1643 /* ---------------------
1644 * GroupState information
1645 * -------------------------
1647 typedef struct GroupState
1649 ScanState ss; /* its first field is NodeTag */
1650 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1651 bool grp_done; /* indicates completion of Group scan */
1654 /* ---------------------
1655 * AggState information
1657 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1659 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1660 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1661 * input group during evaluation of an Agg node's output tuple(s). We
1662 * create a second ExprContext, tmpcontext, in which to evaluate input
1663 * expressions and run the aggregate transition functions.
1664 * -------------------------
1666 /* these structs are private in nodeAgg.c: */
1667 typedef struct AggStatePerAggData *AggStatePerAgg;
1668 typedef struct AggStatePerGroupData *AggStatePerGroup;
1670 typedef struct AggState
1672 ScanState ss; /* its first field is NodeTag */
1673 List *aggs; /* all Aggref nodes in targetlist & quals */
1674 int numaggs; /* length of list (could be zero!) */
1675 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1676 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1677 AggStatePerAgg peragg; /* per-Aggref information */
1678 MemoryContext aggcontext; /* memory context for long-lived data */
1679 ExprContext *tmpcontext; /* econtext for input expressions */
1680 bool agg_done; /* indicates completion of Agg scan */
1681 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1682 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1683 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1684 /* these fields are used in AGG_HASHED mode: */
1685 TupleHashTable hashtable; /* hash table with one entry per group */
1686 TupleTableSlot *hashslot; /* slot for loading hash table */
1687 List *hash_needed; /* list of columns needed in hash table */
1688 bool table_filled; /* hash table filled yet? */
1689 TupleHashIterator hashiter; /* for iterating through hash table */
1693 * WindowAggState information
1696 /* these structs are private in nodeWindowAgg.c: */
1697 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1698 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1700 typedef struct WindowAggState
1702 ScanState ss; /* its first field is NodeTag */
1704 /* these fields are filled in by ExecInitExpr: */
1705 List *funcs; /* all WindowFunc nodes in targetlist */
1706 int numfuncs; /* total number of window functions */
1707 int numaggs; /* number that are plain aggregates */
1709 WindowStatePerFunc perfunc; /* per-window-function information */
1710 WindowStatePerAgg peragg; /* per-plain-aggregate information */
1711 FmgrInfo *partEqfunctions; /* equality funcs for partition columns */
1712 FmgrInfo *ordEqfunctions; /* equality funcs for ordering columns */
1713 Tuplestorestate *buffer; /* stores rows of current partition */
1714 int current_ptr; /* read pointer # for current */
1715 int64 spooled_rows; /* total # of rows in buffer */
1716 int64 currentpos; /* position of current row in partition */
1717 int64 frameheadpos; /* current frame head position */
1718 int64 frametailpos; /* current frame tail position */
1719 /* use struct pointer to avoid including windowapi.h here */
1720 struct WindowObjectData *agg_winobj; /* winobj for aggregate
1722 int64 aggregatedbase; /* start row for current aggregates */
1723 int64 aggregatedupto; /* rows before this one are aggregated */
1725 int frameOptions; /* frame_clause options, see WindowDef */
1726 ExprState *startOffset; /* expression for starting bound offset */
1727 ExprState *endOffset; /* expression for ending bound offset */
1728 Datum startOffsetValue; /* result of startOffset evaluation */
1729 Datum endOffsetValue; /* result of endOffset evaluation */
1731 MemoryContext partcontext; /* context for partition-lifespan data */
1732 MemoryContext aggcontext; /* context for each aggregate data */
1733 ExprContext *tmpcontext; /* short-term evaluation context */
1735 bool all_first; /* true if the scan is starting */
1736 bool all_done; /* true if the scan is finished */
1737 bool partition_spooled; /* true if all tuples in current
1738 * partition have been spooled into
1740 bool more_partitions;/* true if there's more partitions after this
1742 bool framehead_valid;/* true if frameheadpos is known up to date
1743 * for current row */
1744 bool frametail_valid;/* true if frametailpos is known up to date
1745 * for current row */
1747 TupleTableSlot *first_part_slot; /* first tuple of current or next
1750 /* temporary slots for tuples fetched back from tuplestore */
1751 TupleTableSlot *agg_row_slot;
1752 TupleTableSlot *temp_slot_1;
1753 TupleTableSlot *temp_slot_2;
1757 * UniqueState information
1759 * Unique nodes are used "on top of" sort nodes to discard
1760 * duplicate tuples returned from the sort phase. Basically
1761 * all it does is compare the current tuple from the subplan
1762 * with the previously fetched tuple (stored in its result slot).
1763 * If the two are identical in all interesting fields, then
1764 * we just fetch another tuple from the sort and try again.
1767 typedef struct UniqueState
1769 PlanState ps; /* its first field is NodeTag */
1770 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1771 MemoryContext tempContext; /* short-term context for comparisons */
1775 * HashState information
1778 typedef struct HashState
1780 PlanState ps; /* its first field is NodeTag */
1781 HashJoinTable hashtable; /* hash table for the hashjoin */
1782 List *hashkeys; /* list of ExprState nodes */
1783 /* hashkeys is same as parent's hj_InnerHashKeys */
1787 * SetOpState information
1789 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1790 * Unique, since we have to count how many duplicates to return. But
1791 * we also support hashing, so this is really more like a cut-down
1795 /* this struct is private in nodeSetOp.c: */
1796 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1798 typedef struct SetOpState
1800 PlanState ps; /* its first field is NodeTag */
1801 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1802 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1803 bool setop_done; /* indicates completion of output scan */
1804 long numOutput; /* number of dups left to output */
1805 MemoryContext tempContext; /* short-term context for comparisons */
1806 /* these fields are used in SETOP_SORTED mode: */
1807 SetOpStatePerGroup pergroup; /* per-group working state */
1808 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1809 /* these fields are used in SETOP_HASHED mode: */
1810 TupleHashTable hashtable; /* hash table with one entry per group */
1811 MemoryContext tableContext; /* memory context containing hash table */
1812 bool table_filled; /* hash table filled yet? */
1813 TupleHashIterator hashiter; /* for iterating through hash table */
1817 * LockRowsState information
1819 * LockRows nodes are used to enforce FOR UPDATE/FOR SHARE locking.
1822 typedef struct LockRowsState
1824 PlanState ps; /* its first field is NodeTag */
1825 List *lr_arowMarks; /* List of ExecAuxRowMarks */
1826 EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
1830 * LimitState information
1832 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1833 * They just select the desired subrange of their subplan's output.
1835 * offset is the number of initial tuples to skip (0 does nothing).
1836 * count is the number of tuples to return after skipping the offset tuples.
1837 * If no limit count was specified, count is undefined and noCount is true.
1838 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1843 LIMIT_INITIAL, /* initial state for LIMIT node */
1844 LIMIT_RESCAN, /* rescan after recomputing parameters */
1845 LIMIT_EMPTY, /* there are no returnable rows */
1846 LIMIT_INWINDOW, /* have returned a row in the window */
1847 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1848 LIMIT_WINDOWEND, /* stepped off end of window */
1849 LIMIT_WINDOWSTART /* stepped off beginning of window */
1852 typedef struct LimitState
1854 PlanState ps; /* its first field is NodeTag */
1855 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1856 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1857 int64 offset; /* current OFFSET value */
1858 int64 count; /* current COUNT, if any */
1859 bool noCount; /* if true, ignore count */
1860 LimitStateCond lstate; /* state machine status, as above */
1861 int64 position; /* 1-based index of last tuple returned */
1862 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1865 #endif /* EXECNODES_H */