1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/include/nodes/execnodes.h,v 1.155 2006/07/27 19:52:07 tgl Exp $
12 *-------------------------------------------------------------------------
17 #include "access/relscan.h"
18 #include "nodes/params.h"
19 #include "nodes/plannodes.h"
20 #include "nodes/tidbitmap.h"
21 #include "utils/hsearch.h"
22 #include "utils/tuplestore.h"
26 * IndexInfo information
28 * this struct holds the information needed to construct new index
29 * entries for a particular index. Used for both index_build and
30 * retail creation of index entries.
32 * NumIndexAttrs number of columns in this index
33 * KeyAttrNumbers underlying-rel attribute numbers used as keys
34 * (zeroes indicate expressions)
35 * Expressions expr trees for expression entries, or NIL if none
36 * ExpressionsState exec state for expressions, or NIL if none
37 * Predicate partial-index predicate, or NIL if none
38 * PredicateState exec state for predicate, or NIL if none
39 * Unique is it a unique index?
42 typedef struct IndexInfo
46 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
47 List *ii_Expressions; /* list of Expr */
48 List *ii_ExpressionsState; /* list of ExprState */
49 List *ii_Predicate; /* list of Expr */
50 List *ii_PredicateState; /* list of ExprState */
57 * List of callbacks to be called at ExprContext shutdown.
60 typedef void (*ExprContextCallbackFunction) (Datum arg);
62 typedef struct ExprContext_CB
64 struct ExprContext_CB *next;
65 ExprContextCallbackFunction function;
72 * This class holds the "current context" information
73 * needed to evaluate expressions for doing tuple qualifications
74 * and tuple projections. For example, if an expression refers
75 * to an attribute in the current inner tuple then we need to know
76 * what the current inner tuple is and so we look at the expression
79 * There are two memory contexts associated with an ExprContext:
80 * * ecxt_per_query_memory is a query-lifespan context, typically the same
81 * context the ExprContext node itself is allocated in. This context
82 * can be used for purposes such as storing function call cache info.
83 * * ecxt_per_tuple_memory is a short-term context for expression results.
84 * As the name suggests, it will typically be reset once per tuple,
85 * before we begin to evaluate expressions for that tuple. Each
86 * ExprContext normally has its very own per-tuple memory context.
88 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
89 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
92 typedef struct ExprContext
96 /* Tuples that Var nodes in expression may refer to */
97 TupleTableSlot *ecxt_scantuple;
98 TupleTableSlot *ecxt_innertuple;
99 TupleTableSlot *ecxt_outertuple;
101 /* Memory contexts for expression evaluation --- see notes above */
102 MemoryContext ecxt_per_query_memory;
103 MemoryContext ecxt_per_tuple_memory;
105 /* Values to substitute for Param nodes in expression */
106 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
107 ParamListInfo ecxt_param_list_info; /* for other param types */
109 /* Values to substitute for Aggref nodes in expression */
110 Datum *ecxt_aggvalues; /* precomputed values for Aggref nodes */
111 bool *ecxt_aggnulls; /* null flags for Aggref nodes */
113 /* Value to substitute for CaseTestExpr nodes in expression */
114 Datum caseValue_datum;
115 bool caseValue_isNull;
117 /* Value to substitute for CoerceToDomainValue nodes in expression */
118 Datum domainValue_datum;
119 bool domainValue_isNull;
121 /* Link to containing EState */
122 struct EState *ecxt_estate;
124 /* Functions to call back when ExprContext is shut down */
125 ExprContext_CB *ecxt_callbacks;
129 * Set-result status returned by ExecEvalExpr()
133 ExprSingleResult, /* expression does not return a set */
134 ExprMultipleResult, /* this result is an element of a set */
135 ExprEndResult /* there are no more elements in the set */
139 * Return modes for functions returning sets. Note values must be chosen
140 * as separate bits so that a bitmask can be formed to indicate supported
145 SFRM_ValuePerCall = 0x01, /* one value returned per call */
146 SFRM_Materialize = 0x02 /* result set instantiated in Tuplestore */
147 } SetFunctionReturnMode;
150 * When calling a function that might return a set (multiple rows),
151 * a node of this type is passed as fcinfo->resultinfo to allow
152 * return status to be passed back. A function returning set should
153 * raise an error if no such resultinfo is provided.
155 typedef struct ReturnSetInfo
158 /* values set by caller: */
159 ExprContext *econtext; /* context function is being called in */
160 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
161 int allowedModes; /* bitmask: return modes caller can handle */
162 /* result status from function (but pre-initialized by caller): */
163 SetFunctionReturnMode returnMode; /* actual return mode */
164 ExprDoneCond isDone; /* status for ValuePerCall mode */
165 /* fields filled by function in Materialize return mode: */
166 Tuplestorestate *setResult; /* holds the complete returned tuple set */
167 TupleDesc setDesc; /* actual descriptor for returned tuples */
171 * ProjectionInfo node information
173 * This is all the information needed to perform projections ---
174 * that is, form new tuples by evaluation of targetlist expressions.
175 * Nodes which need to do projections create one of these.
177 * ExecProject() evaluates the tlist, forms a tuple, and stores it
178 * in the given slot. Note that the result will be a "virtual" tuple
179 * unless ExecMaterializeSlot() is then called to force it to be
180 * converted to a physical tuple. The slot must have a tupledesc
181 * that matches the output of the tlist!
183 * The planner very often produces tlists that consist entirely of
184 * simple Var references (lower levels of a plan tree almost always
185 * look like that). So we have an optimization to handle that case
186 * with minimum overhead.
188 * targetlist target list for projection
189 * exprContext expression context in which to evaluate targetlist
190 * slot slot to place projection result in
191 * itemIsDone workspace for ExecProject
192 * isVarList TRUE if simple-Var-list optimization applies
193 * varSlotOffsets array indicating which slot each simple Var is from
194 * varNumbers array indicating attr numbers of simple Vars
195 * lastInnerVar highest attnum from inner tuple slot (0 if none)
196 * lastOuterVar highest attnum from outer tuple slot (0 if none)
197 * lastScanVar highest attnum from scan tuple slot (0 if none)
200 typedef struct ProjectionInfo
204 ExprContext *pi_exprContext;
205 TupleTableSlot *pi_slot;
206 ExprDoneCond *pi_itemIsDone;
208 int *pi_varSlotOffsets;
218 * This class is used to store information regarding junk attributes.
219 * A junk attribute is an attribute in a tuple that is needed only for
220 * storing intermediate information in the executor, and does not belong
221 * in emitted tuples. For example, when we do an UPDATE query,
222 * the planner adds a "junk" entry to the targetlist so that the tuples
223 * returned to ExecutePlan() contain an extra attribute: the ctid of
224 * the tuple to be updated. This is needed to do the update, but we
225 * don't want the ctid to be part of the stored new tuple! So, we
226 * apply a "junk filter" to remove the junk attributes and form the
229 * targetList: the original target list (including junk attributes).
230 * cleanTupType: the tuple descriptor for the "clean" tuple (with
231 * junk attributes removed).
232 * cleanMap: A map with the correspondence between the non-junk
233 * attribute numbers of the "original" tuple and the
234 * attribute numbers of the "clean" tuple.
235 * resultSlot: tuple slot used to hold cleaned tuple.
238 typedef struct JunkFilter
242 TupleDesc jf_cleanTupType;
243 AttrNumber *jf_cleanMap;
244 TupleTableSlot *jf_resultSlot;
248 * ResultRelInfo information
250 * Whenever we update an existing relation, we have to
251 * update indices on the relation, and perhaps also fire triggers.
252 * The ResultRelInfo class is used to hold all the information needed
253 * about a result relation, including indices.. -cim 10/15/89
255 * RangeTableIndex result relation's range table index
256 * RelationDesc relation descriptor for result relation
257 * NumIndices # of indices existing on result relation
258 * IndexRelationDescs array of relation descriptors for indices
259 * IndexRelationInfo array of key/attr info for indices
260 * TrigDesc triggers to be fired, if any
261 * TrigFunctions cached lookup info for trigger functions
262 * TrigInstrument optional runtime measurements for triggers
263 * ConstraintExprs array of constraint-checking expr states
264 * junkFilter for removing junk attributes from tuples
267 typedef struct ResultRelInfo
270 Index ri_RangeTableIndex;
271 Relation ri_RelationDesc;
273 RelationPtr ri_IndexRelationDescs;
274 IndexInfo **ri_IndexRelationInfo;
275 TriggerDesc *ri_TrigDesc;
276 FmgrInfo *ri_TrigFunctions;
277 struct Instrumentation *ri_TrigInstrument;
278 List **ri_ConstraintExprs;
279 JunkFilter *ri_junkFilter;
285 * Master working state for an Executor invocation
288 typedef struct EState
292 /* Basic state for all query types: */
293 ScanDirection es_direction; /* current scan direction */
294 Snapshot es_snapshot; /* time qual to use */
295 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
296 List *es_range_table; /* List of RangeTableEntrys */
298 /* Info about target table for insert/update/delete queries: */
299 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
300 int es_num_result_relations; /* length of array */
301 ResultRelInfo *es_result_relation_info; /* currently active array elt */
302 JunkFilter *es_junkFilter; /* currently active junk filter */
304 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
306 Relation es_into_relation_descriptor; /* for SELECT INTO */
307 bool es_into_relation_use_wal;
309 /* Parameter info: */
310 ParamListInfo es_param_list_info; /* values of external params */
311 ParamExecData *es_param_exec_vals; /* values of internal params */
313 /* Other working state: */
314 MemoryContext es_query_cxt; /* per-query context in which EState lives */
316 TupleTable es_tupleTable; /* Array of TupleTableSlots */
318 uint32 es_processed; /* # of tuples processed */
319 Oid es_lastoid; /* last oid processed (by INSERT) */
320 List *es_rowMarks; /* not good place, but there is no other */
322 bool es_instrument; /* true requests runtime instrumentation */
323 bool es_select_into; /* true if doing SELECT INTO */
324 bool es_into_oids; /* true to generate OIDs in SELECT INTO */
326 List *es_exprcontexts; /* List of ExprContexts within EState */
329 * this ExprContext is for per-output-tuple operations, such as constraint
330 * checks and index-value computations. It will be reset for each output
331 * tuple. Note that it will be created only if needed.
333 ExprContext *es_per_tuple_exprcontext;
335 /* Below is to re-evaluate plan qual in READ COMMITTED mode */
336 Plan *es_topPlan; /* link to top of plan tree */
337 struct evalPlanQual *es_evalPlanQual; /* chain of PlanQual states */
338 bool *es_evTupleNull; /* local array of EPQ status */
339 HeapTuple *es_evTuple; /* shared array of EPQ substitute tuples */
340 bool es_useEvalPlan; /* evaluating EPQ tuples? */
344 /* es_rowMarks is a list of these structs: */
345 typedef struct ExecRowMark
347 Relation relation; /* opened and RowShareLock'd relation */
348 Index rti; /* its range table index */
349 bool forUpdate; /* true = FOR UPDATE, false = FOR SHARE */
350 bool noWait; /* NOWAIT option */
351 char resname[32]; /* name for its ctid junk attribute */
355 /* ----------------------------------------------------------------
358 * All-in-memory tuple hash tables are used for a number of purposes.
359 * ----------------------------------------------------------------
361 typedef struct TupleHashEntryData *TupleHashEntry;
362 typedef struct TupleHashTableData *TupleHashTable;
364 typedef struct TupleHashEntryData
366 /* firstTuple must be the first field in this struct! */
367 MinimalTuple firstTuple; /* copy of first tuple in this group */
368 /* there may be additional data beyond the end of this struct */
369 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
371 typedef struct TupleHashTableData
373 HTAB *hashtab; /* underlying dynahash table */
374 int numCols; /* number of columns in lookup key */
375 AttrNumber *keyColIdx; /* attr numbers of key columns */
376 FmgrInfo *eqfunctions; /* lookup data for comparison functions */
377 FmgrInfo *hashfunctions; /* lookup data for hash functions */
378 MemoryContext tablecxt; /* memory context containing table */
379 MemoryContext tempcxt; /* context for function evaluations */
380 Size entrysize; /* actual size to make each hash entry */
381 TupleTableSlot *tableslot; /* slot for referencing table entries */
382 TupleTableSlot *inputslot; /* current input tuple's slot */
383 } TupleHashTableData;
385 typedef HASH_SEQ_STATUS TupleHashIterator;
387 #define ResetTupleHashIterator(htable, iter) \
388 hash_seq_init(iter, (htable)->hashtab)
389 #define ScanTupleHashTable(iter) \
390 ((TupleHashEntry) hash_seq_search(iter))
393 /* ----------------------------------------------------------------
394 * Expression State Trees
396 * Each executable expression tree has a parallel ExprState tree.
398 * Unlike PlanState, there is not an exact one-for-one correspondence between
399 * ExprState node types and Expr node types. Many Expr node types have no
400 * need for node-type-specific run-time state, and so they can use plain
401 * ExprState or GenericExprState as their associated ExprState node type.
402 * ----------------------------------------------------------------
408 * ExprState is the common superclass for all ExprState-type nodes.
410 * It can also be instantiated directly for leaf Expr nodes that need no
411 * local run-time state (such as Var, Const, or Param).
413 * To save on dispatch overhead, each ExprState node contains a function
414 * pointer to the routine to execute to evaluate the node.
418 typedef struct ExprState ExprState;
420 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
421 ExprContext *econtext,
423 ExprDoneCond *isDone);
428 Expr *expr; /* associated Expr node */
429 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
433 * GenericExprState node
435 * This is used for Expr node types that need no local run-time state,
436 * but have one child Expr node.
439 typedef struct GenericExprState
442 ExprState *arg; /* state of my child node */
446 * AggrefExprState node
449 typedef struct AggrefExprState
452 List *args; /* states of argument expressions */
453 int aggno; /* ID number for agg within its plan node */
457 * ArrayRefExprState node
459 * Note: array types can be fixed-length (typlen > 0), but only when the
460 * element type is itself fixed-length. Otherwise they are varlena structures
461 * and have typlen = -1. In any case, an array type is never pass-by-value.
464 typedef struct ArrayRefExprState
467 List *refupperindexpr; /* states for child nodes */
468 List *reflowerindexpr;
470 ExprState *refassgnexpr;
471 int16 refattrlength; /* typlen of array type */
472 int16 refelemlength; /* typlen of the array element type */
473 bool refelembyval; /* is the element type pass-by-value? */
474 char refelemalign; /* typalign of the element type */
480 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
481 * and NullIf nodes; be careful to check what xprstate.expr is actually
485 typedef struct FuncExprState
488 List *args; /* states of argument expressions */
491 * Function manager's lookup info for the target function. If func.fn_oid
492 * is InvalidOid, we haven't initialized it yet.
497 * We also need to store argument values across calls when evaluating a
498 * function-returning-set.
500 * setArgsValid is true when we are evaluating a set-valued function and
501 * we are in the middle of a call series; we want to pass the same
502 * argument values to the function again (and again, until it returns
508 * Flag to remember whether we found a set-valued argument to the
509 * function. This causes the function result to be a set as well. Valid
510 * only when setArgsValid is true.
512 bool setHasSetArg; /* some argument returns a set */
515 * Flag to remember whether we have registered a shutdown callback for
516 * this FuncExprState. We do so only if setArgsValid has been true at
517 * least once (since all the callback is for is to clear setArgsValid).
519 bool shutdown_reg; /* a shutdown callback is registered */
522 * Current argument data for a set-valued function; contains valid data
523 * only if setArgsValid is true.
525 FunctionCallInfoData setArgs;
529 * ScalarArrayOpExprState node
531 * This is a FuncExprState plus some additional data.
534 typedef struct ScalarArrayOpExprState
536 FuncExprState fxprstate;
537 /* Cached info about array element type */
542 } ScalarArrayOpExprState;
548 typedef struct BoolExprState
551 List *args; /* states of argument expression(s) */
558 typedef struct SubPlanState
561 EState *sub_estate; /* subselect plan has its own EState */
562 struct PlanState *planstate; /* subselect plan's state tree */
563 ExprState *testexpr; /* state of combining expression */
564 List *args; /* states of argument expression(s) */
565 bool needShutdown; /* TRUE = need to shutdown subplan */
566 HeapTuple curTuple; /* copy of most recent tuple from subplan */
567 /* these are used when hashing the subselect's output: */
568 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
569 ProjectionInfo *projRight; /* for projecting subselect output */
570 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
571 TupleHashTable hashnulls; /* hash table for rows with null(s) */
572 bool havehashrows; /* TRUE if hashtable is not empty */
573 bool havenullrows; /* TRUE if hashnulls is not empty */
574 MemoryContext tablecxt; /* memory context containing tables */
575 ExprContext *innerecontext; /* working context for comparisons */
576 AttrNumber *keyColIdx; /* control data for hash tables */
577 FmgrInfo *eqfunctions; /* comparison functions for hash tables */
578 FmgrInfo *hashfunctions; /* lookup data for hash functions */
582 * FieldSelectState node
585 typedef struct FieldSelectState
588 ExprState *arg; /* input expression */
589 TupleDesc argdesc; /* tupdesc for most recent input */
593 * FieldStoreState node
596 typedef struct FieldStoreState
599 ExprState *arg; /* input tuple value */
600 List *newvals; /* new value(s) for field(s) */
601 TupleDesc argdesc; /* tupdesc for most recent input */
605 * ConvertRowtypeExprState node
608 typedef struct ConvertRowtypeExprState
611 ExprState *arg; /* input tuple value */
612 TupleDesc indesc; /* tupdesc for source rowtype */
613 TupleDesc outdesc; /* tupdesc for result rowtype */
614 AttrNumber *attrMap; /* indexes of input fields, or 0 for null */
615 Datum *invalues; /* workspace for deconstructing source */
617 Datum *outvalues; /* workspace for constructing result */
619 } ConvertRowtypeExprState;
625 typedef struct CaseExprState
628 ExprState *arg; /* implicit equality comparison argument */
629 List *args; /* the arguments (list of WHEN clauses) */
630 ExprState *defresult; /* the default result (ELSE clause) */
637 typedef struct CaseWhenState
640 ExprState *expr; /* condition expression */
641 ExprState *result; /* substitution result */
645 * ArrayExprState node
647 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
651 typedef struct ArrayExprState
654 List *elements; /* states for child nodes */
655 int16 elemlength; /* typlen of the array element type */
656 bool elembyval; /* is the element type pass-by-value? */
657 char elemalign; /* typalign of the element type */
664 typedef struct RowExprState
667 List *args; /* the arguments */
668 TupleDesc tupdesc; /* descriptor for result tuples */
672 * RowCompareExprState node
675 typedef struct RowCompareExprState
678 List *largs; /* the left-hand input arguments */
679 List *rargs; /* the right-hand input arguments */
680 FmgrInfo *funcs; /* array of comparison function info */
681 } RowCompareExprState;
684 * CoalesceExprState node
687 typedef struct CoalesceExprState
690 List *args; /* the arguments */
694 * MinMaxExprState node
697 typedef struct MinMaxExprState
700 List *args; /* the arguments */
701 FmgrInfo cfunc; /* lookup info for comparison func */
705 * CoerceToDomainState node
708 typedef struct CoerceToDomainState
711 ExprState *arg; /* input expression */
712 /* Cached list of constraints that need to be checked */
713 List *constraints; /* list of DomainConstraintState nodes */
714 } CoerceToDomainState;
717 * DomainConstraintState - one item to check during CoerceToDomain
719 * Note: this is just a Node, and not an ExprState, because it has no
720 * corresponding Expr to link to. Nonetheless it is part of an ExprState
721 * tree, so we give it a name following the xxxState convention.
723 typedef enum DomainConstraintType
725 DOM_CONSTRAINT_NOTNULL,
727 } DomainConstraintType;
729 typedef struct DomainConstraintState
732 DomainConstraintType constrainttype; /* constraint type */
733 char *name; /* name of constraint (for error msgs) */
734 ExprState *check_expr; /* for CHECK, a boolean expression */
735 } DomainConstraintState;
738 /* ----------------------------------------------------------------
739 * Executor State Trees
741 * An executing query has a PlanState tree paralleling the Plan tree
742 * that describes the plan.
743 * ----------------------------------------------------------------
749 * We never actually instantiate any PlanState nodes; this is just the common
750 * abstract superclass for all PlanState-type nodes.
753 typedef struct PlanState
757 Plan *plan; /* associated Plan node */
759 EState *state; /* at execution time, state's of individual
760 * nodes point to one EState for the whole
763 struct Instrumentation *instrument; /* Optional runtime stats for this
767 * Common structural data for all Plan types. These links to subsidiary
768 * state trees parallel links in the associated plan tree (except for the
769 * subPlan list, which does not exist in the plan tree).
771 List *targetlist; /* target list to be computed at this node */
772 List *qual; /* implicitly-ANDed qual conditions */
773 struct PlanState *lefttree; /* input plan tree(s) */
774 struct PlanState *righttree;
775 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
777 List *subPlan; /* SubPlanState nodes in my expressions */
780 * State for management of parameter-change-driven rescanning
782 Bitmapset *chgParam; /* set of IDs of changed Params */
785 * Other run-time state needed by most if not all node types.
787 TupleTableSlot *ps_OuterTupleSlot; /* slot for current "outer" tuple */
788 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
789 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
790 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
791 bool ps_TupFromTlist;/* state flag for processing set-valued
792 * functions in targetlist */
796 * these are are defined to avoid confusion problems with "left"
797 * and "right" and "inner" and "outer". The convention is that
798 * the "left" plan is the "outer" plan and the "right" plan is
799 * the inner plan, but these make the code more readable.
802 #define innerPlanState(node) (((PlanState *)(node))->righttree)
803 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
807 * ResultState information
810 typedef struct ResultState
812 PlanState ps; /* its first field is NodeTag */
813 ExprState *resconstantqual;
814 bool rs_done; /* are we done? */
815 bool rs_checkqual; /* do we need to check the qual? */
819 * AppendState information
821 * nplans how many plans are in the list
822 * whichplan which plan is being executed (0 .. n-1)
823 * firstplan first plan to execute (usually 0)
824 * lastplan last plan to execute (usually n-1)
827 typedef struct AppendState
829 PlanState ps; /* its first field is NodeTag */
830 PlanState **appendplans; /* array of PlanStates for my inputs */
838 * BitmapAndState information
841 typedef struct BitmapAndState
843 PlanState ps; /* its first field is NodeTag */
844 PlanState **bitmapplans; /* array of PlanStates for my inputs */
845 int nplans; /* number of input plans */
849 * BitmapOrState information
852 typedef struct BitmapOrState
854 PlanState ps; /* its first field is NodeTag */
855 PlanState **bitmapplans; /* array of PlanStates for my inputs */
856 int nplans; /* number of input plans */
859 /* ----------------------------------------------------------------
860 * Scan State Information
861 * ----------------------------------------------------------------
865 * ScanState information
867 * ScanState extends PlanState for node types that represent
868 * scans of an underlying relation. It can also be used for nodes
869 * that scan the output of an underlying plan node --- in that case,
870 * only ScanTupleSlot is actually useful, and it refers to the tuple
871 * retrieved from the subplan.
873 * currentRelation relation being scanned (NULL if none)
874 * currentScanDesc current scan descriptor for scan (NULL if none)
875 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
878 typedef struct ScanState
880 PlanState ps; /* its first field is NodeTag */
881 Relation ss_currentRelation;
882 HeapScanDesc ss_currentScanDesc;
883 TupleTableSlot *ss_ScanTupleSlot;
887 * SeqScan uses a bare ScanState as its state node, since it needs
888 * no additional fields.
890 typedef ScanState SeqScanState;
893 * These structs store information about index quals that don't have simple
894 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
899 ScanKey scan_key; /* scankey to put value into */
900 ExprState *key_expr; /* expr to evaluate to get value */
901 } IndexRuntimeKeyInfo;
905 ScanKey scan_key; /* scankey to put value into */
906 ExprState *array_expr; /* expr to evaluate to get array value */
907 int next_elem; /* next array element to use */
908 int num_elems; /* number of elems in current array value */
909 Datum *elem_values; /* array of num_elems Datums */
910 bool *elem_nulls; /* array of num_elems is-null flags */
914 * IndexScanState information
916 * indexqualorig execution state for indexqualorig expressions
917 * ScanKeys Skey structures to scan index rel
918 * NumScanKeys number of Skey structs
919 * RuntimeKeys info about Skeys that must be evaluated at runtime
920 * NumRuntimeKeys number of RuntimeKeys structs
921 * RuntimeKeysReady true if runtime Skeys have been computed
922 * RuntimeContext expr context for evaling runtime Skeys
923 * RelationDesc index relation descriptor
924 * ScanDesc index scan descriptor
927 typedef struct IndexScanState
929 ScanState ss; /* its first field is NodeTag */
931 ScanKey iss_ScanKeys;
933 IndexRuntimeKeyInfo *iss_RuntimeKeys;
934 int iss_NumRuntimeKeys;
935 bool iss_RuntimeKeysReady;
936 ExprContext *iss_RuntimeContext;
937 Relation iss_RelationDesc;
938 IndexScanDesc iss_ScanDesc;
942 * BitmapIndexScanState information
944 * result bitmap to return output into, or NULL
945 * ScanKeys Skey structures to scan index rel
946 * NumScanKeys number of Skey structs
947 * RuntimeKeys info about Skeys that must be evaluated at runtime
948 * NumRuntimeKeys number of RuntimeKeys structs
949 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
950 * NumArrayKeys number of ArrayKeys structs
951 * RuntimeKeysReady true if runtime Skeys have been computed
952 * RuntimeContext expr context for evaling runtime Skeys
953 * RelationDesc index relation descriptor
954 * ScanDesc index scan descriptor
957 typedef struct BitmapIndexScanState
959 ScanState ss; /* its first field is NodeTag */
960 TIDBitmap *biss_result;
961 ScanKey biss_ScanKeys;
962 int biss_NumScanKeys;
963 IndexRuntimeKeyInfo *biss_RuntimeKeys;
964 int biss_NumRuntimeKeys;
965 IndexArrayKeyInfo *biss_ArrayKeys;
966 int biss_NumArrayKeys;
967 bool biss_RuntimeKeysReady;
968 ExprContext *biss_RuntimeContext;
969 Relation biss_RelationDesc;
970 IndexScanDesc biss_ScanDesc;
971 } BitmapIndexScanState;
974 * BitmapHeapScanState information
976 * bitmapqualorig execution state for bitmapqualorig expressions
977 * tbm bitmap obtained from child index scan(s)
978 * tbmres current-page data
981 typedef struct BitmapHeapScanState
983 ScanState ss; /* its first field is NodeTag */
984 List *bitmapqualorig;
986 TBMIterateResult *tbmres;
987 } BitmapHeapScanState;
990 * TidScanState information
992 * NumTids number of tids in this scan
993 * TidPtr index of currently fetched tid
994 * TidList evaluated item pointers (array of size NumTids)
997 typedef struct TidScanState
999 ScanState ss; /* its first field is NodeTag */
1000 List *tss_tidquals; /* list of ExprState nodes */
1004 ItemPointerData *tss_TidList;
1005 HeapTupleData tss_htup;
1009 * SubqueryScanState information
1011 * SubqueryScanState is used for scanning a sub-query in the range table.
1012 * The sub-query will have its own EState, which we save here.
1013 * ScanTupleSlot references the current output tuple of the sub-query.
1015 * SubEState exec state for sub-query
1018 typedef struct SubqueryScanState
1020 ScanState ss; /* its first field is NodeTag */
1022 EState *sss_SubEState;
1023 } SubqueryScanState;
1026 * FunctionScanState information
1028 * Function nodes are used to scan the results of a
1029 * function appearing in FROM (typically a function returning set).
1031 * tupdesc expected return tuple description
1032 * tuplestorestate private state of tuplestore.c
1033 * funcexpr state for function expression being evaluated
1036 typedef struct FunctionScanState
1038 ScanState ss; /* its first field is NodeTag */
1040 Tuplestorestate *tuplestorestate;
1041 ExprState *funcexpr;
1042 } FunctionScanState;
1044 /* ----------------------------------------------------------------
1045 * Join State Information
1046 * ----------------------------------------------------------------
1050 * JoinState information
1052 * Superclass for state nodes of join plans.
1055 typedef struct JoinState
1059 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1063 * NestLoopState information
1065 * NeedNewOuter true if need new outer tuple on next call
1066 * MatchedOuter true if found a join match for current outer tuple
1067 * NullInnerTupleSlot prepared null tuple for left outer joins
1070 typedef struct NestLoopState
1072 JoinState js; /* its first field is NodeTag */
1073 bool nl_NeedNewOuter;
1074 bool nl_MatchedOuter;
1075 TupleTableSlot *nl_NullInnerTupleSlot;
1079 * MergeJoinState information
1081 * NumClauses number of mergejoinable join clauses
1082 * Clauses info for each mergejoinable clause
1083 * JoinState current "state" of join. see execdefs.h
1084 * FillOuter true if should emit unjoined outer tuples anyway
1085 * FillInner true if should emit unjoined inner tuples anyway
1086 * MatchedOuter true if found a join match for current outer tuple
1087 * MatchedInner true if found a join match for current inner tuple
1088 * OuterTupleSlot slot in tuple table for cur outer tuple
1089 * InnerTupleSlot slot in tuple table for cur inner tuple
1090 * MarkedTupleSlot slot in tuple table for marked tuple
1091 * NullOuterTupleSlot prepared null tuple for right outer joins
1092 * NullInnerTupleSlot prepared null tuple for left outer joins
1093 * OuterEContext workspace for computing outer tuple's join values
1094 * InnerEContext workspace for computing inner tuple's join values
1097 /* private in nodeMergejoin.c: */
1098 typedef struct MergeJoinClauseData *MergeJoinClause;
1100 typedef struct MergeJoinState
1102 JoinState js; /* its first field is NodeTag */
1104 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1108 bool mj_MatchedOuter;
1109 bool mj_MatchedInner;
1110 TupleTableSlot *mj_OuterTupleSlot;
1111 TupleTableSlot *mj_InnerTupleSlot;
1112 TupleTableSlot *mj_MarkedTupleSlot;
1113 TupleTableSlot *mj_NullOuterTupleSlot;
1114 TupleTableSlot *mj_NullInnerTupleSlot;
1115 ExprContext *mj_OuterEContext;
1116 ExprContext *mj_InnerEContext;
1120 * HashJoinState information
1122 * hj_HashTable hash table for the hashjoin
1123 * (NULL if table not built yet)
1124 * hj_CurHashValue hash value for current outer tuple
1125 * hj_CurBucketNo bucket# for current outer tuple
1126 * hj_CurTuple last inner tuple matched to current outer
1127 * tuple, or NULL if starting search
1128 * (CurHashValue, CurBucketNo and CurTuple are
1129 * undefined if OuterTupleSlot is empty!)
1130 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1131 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1132 * hj_HashOperators the join operators in the hashjoin condition
1133 * hj_OuterTupleSlot tuple slot for outer tuples
1134 * hj_HashTupleSlot tuple slot for hashed tuples
1135 * hj_NullInnerTupleSlot prepared null tuple for left outer joins
1136 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1137 * hj_NeedNewOuter true if need new outer tuple on next call
1138 * hj_MatchedOuter true if found a join match for current outer
1139 * hj_OuterNotEmpty true if outer relation known not empty
1143 /* these structs are defined in executor/hashjoin.h: */
1144 typedef struct HashJoinTupleData *HashJoinTuple;
1145 typedef struct HashJoinTableData *HashJoinTable;
1147 typedef struct HashJoinState
1149 JoinState js; /* its first field is NodeTag */
1150 List *hashclauses; /* list of ExprState nodes */
1151 HashJoinTable hj_HashTable;
1152 uint32 hj_CurHashValue;
1154 HashJoinTuple hj_CurTuple;
1155 List *hj_OuterHashKeys; /* list of ExprState nodes */
1156 List *hj_InnerHashKeys; /* list of ExprState nodes */
1157 List *hj_HashOperators; /* list of operator OIDs */
1158 TupleTableSlot *hj_OuterTupleSlot;
1159 TupleTableSlot *hj_HashTupleSlot;
1160 TupleTableSlot *hj_NullInnerTupleSlot;
1161 TupleTableSlot *hj_FirstOuterTupleSlot;
1162 bool hj_NeedNewOuter;
1163 bool hj_MatchedOuter;
1164 bool hj_OuterNotEmpty;
1168 /* ----------------------------------------------------------------
1169 * Materialization State Information
1170 * ----------------------------------------------------------------
1174 * MaterialState information
1176 * materialize nodes are used to materialize the results
1177 * of a subplan into a temporary file.
1179 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1182 typedef struct MaterialState
1184 ScanState ss; /* its first field is NodeTag */
1185 bool randomAccess; /* need random access to subplan output? */
1186 bool eof_underlying; /* reached end of underlying plan? */
1187 void *tuplestorestate; /* private state of tuplestore.c */
1191 * SortState information
1194 typedef struct SortState
1196 ScanState ss; /* its first field is NodeTag */
1197 bool randomAccess; /* need random access to sort output? */
1198 bool sort_Done; /* sort completed yet? */
1199 void *tuplesortstate; /* private state of tuplesort.c */
1202 /* ---------------------
1203 * GroupState information
1204 * -------------------------
1206 typedef struct GroupState
1208 ScanState ss; /* its first field is NodeTag */
1209 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1210 bool grp_done; /* indicates completion of Group scan */
1213 /* ---------------------
1214 * AggState information
1216 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1218 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1219 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1220 * input group during evaluation of an Agg node's output tuple(s). We
1221 * create a second ExprContext, tmpcontext, in which to evaluate input
1222 * expressions and run the aggregate transition functions.
1223 * -------------------------
1225 /* these structs are private in nodeAgg.c: */
1226 typedef struct AggStatePerAggData *AggStatePerAgg;
1227 typedef struct AggStatePerGroupData *AggStatePerGroup;
1229 typedef struct AggState
1231 ScanState ss; /* its first field is NodeTag */
1232 List *aggs; /* all Aggref nodes in targetlist & quals */
1233 int numaggs; /* length of list (could be zero!) */
1234 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1235 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1236 AggStatePerAgg peragg; /* per-Aggref information */
1237 MemoryContext aggcontext; /* memory context for long-lived data */
1238 ExprContext *tmpcontext; /* econtext for input expressions */
1239 bool agg_done; /* indicates completion of Agg scan */
1240 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1241 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1242 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1243 /* these fields are used in AGG_HASHED mode: */
1244 TupleHashTable hashtable; /* hash table with one entry per group */
1245 TupleTableSlot *hashslot; /* slot for loading hash table */
1246 List *hash_needed; /* list of columns needed in hash table */
1247 bool table_filled; /* hash table filled yet? */
1248 TupleHashIterator hashiter; /* for iterating through hash table */
1252 * UniqueState information
1254 * Unique nodes are used "on top of" sort nodes to discard
1255 * duplicate tuples returned from the sort phase. Basically
1256 * all it does is compare the current tuple from the subplan
1257 * with the previously fetched tuple (stored in its result slot).
1258 * If the two are identical in all interesting fields, then
1259 * we just fetch another tuple from the sort and try again.
1262 typedef struct UniqueState
1264 PlanState ps; /* its first field is NodeTag */
1265 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1266 MemoryContext tempContext; /* short-term context for comparisons */
1270 * HashState information
1273 typedef struct HashState
1275 PlanState ps; /* its first field is NodeTag */
1276 HashJoinTable hashtable; /* hash table for the hashjoin */
1277 List *hashkeys; /* list of ExprState nodes */
1278 /* hashkeys is same as parent's hj_InnerHashKeys */
1282 * SetOpState information
1284 * SetOp nodes are used "on top of" sort nodes to discard
1285 * duplicate tuples returned from the sort phase. These are
1286 * more complex than a simple Unique since we have to count
1287 * how many duplicates to return.
1290 typedef struct SetOpState
1292 PlanState ps; /* its first field is NodeTag */
1293 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1294 bool subplan_done; /* has subplan returned EOF? */
1295 long numLeft; /* number of left-input dups of cur group */
1296 long numRight; /* number of right-input dups of cur group */
1297 long numOutput; /* number of dups left to output */
1298 MemoryContext tempContext; /* short-term context for comparisons */
1302 * LimitState information
1304 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1305 * They just select the desired subrange of their subplan's output.
1307 * offset is the number of initial tuples to skip (0 does nothing).
1308 * count is the number of tuples to return after skipping the offset tuples.
1309 * If no limit count was specified, count is undefined and noCount is true.
1310 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1315 LIMIT_INITIAL, /* initial state for LIMIT node */
1316 LIMIT_EMPTY, /* there are no returnable rows */
1317 LIMIT_INWINDOW, /* have returned a row in the window */
1318 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1319 LIMIT_WINDOWEND, /* stepped off end of window */
1320 LIMIT_WINDOWSTART /* stepped off beginning of window */
1323 typedef struct LimitState
1325 PlanState ps; /* its first field is NodeTag */
1326 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1327 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1328 int64 offset; /* current OFFSET value */
1329 int64 count; /* current COUNT, if any */
1330 bool noCount; /* if true, ignore count */
1331 LimitStateCond lstate; /* state machine status, as above */
1332 int64 position; /* 1-based index of last tuple returned */
1333 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1336 #endif /* EXECNODES_H */