1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2007, 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.181 2007/11/15 22:25:17 momjian 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?
40 * ReadyForInserts is it valid for inserts?
41 * Concurrent are we doing a concurrent index build?
42 * BrokenHotChain did we detect any broken HOT chains?
44 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
45 * they're conventionally set to false otherwise.
48 typedef struct IndexInfo
52 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
53 List *ii_Expressions; /* list of Expr */
54 List *ii_ExpressionsState; /* list of ExprState */
55 List *ii_Predicate; /* list of Expr */
56 List *ii_PredicateState; /* list of ExprState */
58 bool ii_ReadyForInserts;
60 bool ii_BrokenHotChain;
66 * List of callbacks to be called at ExprContext shutdown.
69 typedef void (*ExprContextCallbackFunction) (Datum arg);
71 typedef struct ExprContext_CB
73 struct ExprContext_CB *next;
74 ExprContextCallbackFunction function;
81 * This class holds the "current context" information
82 * needed to evaluate expressions for doing tuple qualifications
83 * and tuple projections. For example, if an expression refers
84 * to an attribute in the current inner tuple then we need to know
85 * what the current inner tuple is and so we look at the expression
88 * There are two memory contexts associated with an ExprContext:
89 * * ecxt_per_query_memory is a query-lifespan context, typically the same
90 * context the ExprContext node itself is allocated in. This context
91 * can be used for purposes such as storing function call cache info.
92 * * ecxt_per_tuple_memory is a short-term context for expression results.
93 * As the name suggests, it will typically be reset once per tuple,
94 * before we begin to evaluate expressions for that tuple. Each
95 * ExprContext normally has its very own per-tuple memory context.
97 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
98 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
101 typedef struct ExprContext
105 /* Tuples that Var nodes in expression may refer to */
106 TupleTableSlot *ecxt_scantuple;
107 TupleTableSlot *ecxt_innertuple;
108 TupleTableSlot *ecxt_outertuple;
110 /* Memory contexts for expression evaluation --- see notes above */
111 MemoryContext ecxt_per_query_memory;
112 MemoryContext ecxt_per_tuple_memory;
114 /* Values to substitute for Param nodes in expression */
115 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
116 ParamListInfo ecxt_param_list_info; /* for other param types */
118 /* Values to substitute for Aggref nodes in expression */
119 Datum *ecxt_aggvalues; /* precomputed values for Aggref nodes */
120 bool *ecxt_aggnulls; /* null flags for Aggref nodes */
122 /* Value to substitute for CaseTestExpr nodes in expression */
123 Datum caseValue_datum;
124 bool caseValue_isNull;
126 /* Value to substitute for CoerceToDomainValue nodes in expression */
127 Datum domainValue_datum;
128 bool domainValue_isNull;
130 /* Link to containing EState (NULL if a standalone ExprContext) */
131 struct EState *ecxt_estate;
133 /* Functions to call back when ExprContext is shut down */
134 ExprContext_CB *ecxt_callbacks;
138 * Set-result status returned by ExecEvalExpr()
142 ExprSingleResult, /* expression does not return a set */
143 ExprMultipleResult, /* this result is an element of a set */
144 ExprEndResult /* there are no more elements in the set */
148 * Return modes for functions returning sets. Note values must be chosen
149 * as separate bits so that a bitmask can be formed to indicate supported
154 SFRM_ValuePerCall = 0x01, /* one value returned per call */
155 SFRM_Materialize = 0x02 /* result set instantiated in Tuplestore */
156 } SetFunctionReturnMode;
159 * When calling a function that might return a set (multiple rows),
160 * a node of this type is passed as fcinfo->resultinfo to allow
161 * return status to be passed back. A function returning set should
162 * raise an error if no such resultinfo is provided.
164 typedef struct ReturnSetInfo
167 /* values set by caller: */
168 ExprContext *econtext; /* context function is being called in */
169 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
170 int allowedModes; /* bitmask: return modes caller can handle */
171 /* result status from function (but pre-initialized by caller): */
172 SetFunctionReturnMode returnMode; /* actual return mode */
173 ExprDoneCond isDone; /* status for ValuePerCall mode */
174 /* fields filled by function in Materialize return mode: */
175 Tuplestorestate *setResult; /* holds the complete returned tuple set */
176 TupleDesc setDesc; /* actual descriptor for returned tuples */
180 * ProjectionInfo node information
182 * This is all the information needed to perform projections ---
183 * that is, form new tuples by evaluation of targetlist expressions.
184 * Nodes which need to do projections create one of these.
186 * ExecProject() evaluates the tlist, forms a tuple, and stores it
187 * in the given slot. Note that the result will be a "virtual" tuple
188 * unless ExecMaterializeSlot() is then called to force it to be
189 * converted to a physical tuple. The slot must have a tupledesc
190 * that matches the output of the tlist!
192 * The planner very often produces tlists that consist entirely of
193 * simple Var references (lower levels of a plan tree almost always
194 * look like that). So we have an optimization to handle that case
195 * with minimum overhead.
197 * targetlist target list for projection
198 * exprContext expression context in which to evaluate targetlist
199 * slot slot to place projection result in
200 * itemIsDone workspace for ExecProject
201 * isVarList TRUE if simple-Var-list optimization applies
202 * varSlotOffsets array indicating which slot each simple Var is from
203 * varNumbers array indicating attr numbers of simple Vars
204 * lastInnerVar highest attnum from inner tuple slot (0 if none)
205 * lastOuterVar highest attnum from outer tuple slot (0 if none)
206 * lastScanVar highest attnum from scan tuple slot (0 if none)
209 typedef struct ProjectionInfo
213 ExprContext *pi_exprContext;
214 TupleTableSlot *pi_slot;
215 ExprDoneCond *pi_itemIsDone;
217 int *pi_varSlotOffsets;
227 * This class is used to store information regarding junk attributes.
228 * A junk attribute is an attribute in a tuple that is needed only for
229 * storing intermediate information in the executor, and does not belong
230 * in emitted tuples. For example, when we do an UPDATE query,
231 * the planner adds a "junk" entry to the targetlist so that the tuples
232 * returned to ExecutePlan() contain an extra attribute: the ctid of
233 * the tuple to be updated. This is needed to do the update, but we
234 * don't want the ctid to be part of the stored new tuple! So, we
235 * apply a "junk filter" to remove the junk attributes and form the
236 * real output tuple. The junkfilter code also provides routines to
237 * extract the values of the junk attribute(s) from the input tuple.
239 * targetList: the original target list (including junk attributes).
240 * cleanTupType: the tuple descriptor for the "clean" tuple (with
241 * junk attributes removed).
242 * cleanMap: A map with the correspondence between the non-junk
243 * attribute numbers of the "original" tuple and the
244 * attribute numbers of the "clean" tuple.
245 * resultSlot: tuple slot used to hold cleaned tuple.
246 * junkAttNo: not used by junkfilter code. Can be used by caller
247 * to remember the attno of a specific junk attribute
248 * (execMain.c stores the "ctid" attno here).
251 typedef struct JunkFilter
255 TupleDesc jf_cleanTupType;
256 AttrNumber *jf_cleanMap;
257 TupleTableSlot *jf_resultSlot;
258 AttrNumber jf_junkAttNo;
262 * ResultRelInfo information
264 * Whenever we update an existing relation, we have to
265 * update indices on the relation, and perhaps also fire triggers.
266 * The ResultRelInfo class is used to hold all the information needed
267 * about a result relation, including indices.. -cim 10/15/89
269 * RangeTableIndex result relation's range table index
270 * RelationDesc relation descriptor for result relation
271 * NumIndices # of indices existing on result relation
272 * IndexRelationDescs array of relation descriptors for indices
273 * IndexRelationInfo array of key/attr info for indices
274 * TrigDesc triggers to be fired, if any
275 * TrigFunctions cached lookup info for trigger functions
276 * TrigInstrument optional runtime measurements for triggers
277 * ConstraintExprs array of constraint-checking expr states
278 * junkFilter for removing junk attributes from tuples
279 * projectReturning for computing a RETURNING list
282 typedef struct ResultRelInfo
285 Index ri_RangeTableIndex;
286 Relation ri_RelationDesc;
288 RelationPtr ri_IndexRelationDescs;
289 IndexInfo **ri_IndexRelationInfo;
290 TriggerDesc *ri_TrigDesc;
291 FmgrInfo *ri_TrigFunctions;
292 struct Instrumentation *ri_TrigInstrument;
293 List **ri_ConstraintExprs;
294 JunkFilter *ri_junkFilter;
295 ProjectionInfo *ri_projectReturning;
301 * Master working state for an Executor invocation
304 typedef struct EState
308 /* Basic state for all query types: */
309 ScanDirection es_direction; /* current scan direction */
310 Snapshot es_snapshot; /* time qual to use */
311 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
312 List *es_range_table; /* List of RangeTblEntry */
314 /* Info about target table for insert/update/delete queries: */
315 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
316 int es_num_result_relations; /* length of array */
317 ResultRelInfo *es_result_relation_info; /* currently active array elt */
318 JunkFilter *es_junkFilter; /* currently active junk filter */
320 /* Stuff used for firing triggers: */
321 List *es_trig_target_relations; /* trigger-only ResultRelInfos */
322 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
324 /* Stuff used for SELECT INTO: */
325 Relation es_into_relation_descriptor;
326 bool es_into_relation_use_wal;
328 /* Parameter info: */
329 ParamListInfo es_param_list_info; /* values of external params */
330 ParamExecData *es_param_exec_vals; /* values of internal params */
332 /* Other working state: */
333 MemoryContext es_query_cxt; /* per-query context in which EState lives */
335 TupleTable es_tupleTable; /* Array of TupleTableSlots */
337 uint32 es_processed; /* # of tuples processed */
338 Oid es_lastoid; /* last oid processed (by INSERT) */
339 List *es_rowMarks; /* not good place, but there is no other */
341 bool es_instrument; /* true requests runtime instrumentation */
342 bool es_select_into; /* true if doing SELECT INTO */
343 bool es_into_oids; /* true to generate OIDs in SELECT INTO */
345 List *es_exprcontexts; /* List of ExprContexts within EState */
347 List *es_subplanstates; /* List of PlanState for SubPlans */
350 * this ExprContext is for per-output-tuple operations, such as constraint
351 * checks and index-value computations. It will be reset for each output
352 * tuple. Note that it will be created only if needed.
354 ExprContext *es_per_tuple_exprcontext;
356 /* Below is to re-evaluate plan qual in READ COMMITTED mode */
357 PlannedStmt *es_plannedstmt; /* link to top of plan tree */
358 struct evalPlanQual *es_evalPlanQual; /* chain of PlanQual states */
359 bool *es_evTupleNull; /* local array of EPQ status */
360 HeapTuple *es_evTuple; /* shared array of EPQ substitute tuples */
361 bool es_useEvalPlan; /* evaluating EPQ tuples? */
365 /* es_rowMarks is a list of these structs: */
366 typedef struct ExecRowMark
368 Relation relation; /* opened and RowShareLock'd relation */
369 Index rti; /* its range table index */
370 bool forUpdate; /* true = FOR UPDATE, false = FOR SHARE */
371 bool noWait; /* NOWAIT option */
372 AttrNumber ctidAttNo; /* resno of its ctid junk attribute */
376 /* ----------------------------------------------------------------
379 * All-in-memory tuple hash tables are used for a number of purposes.
381 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
382 * and tab_eq_funcs are non-cross-type equality operators for those types.
383 * Normally these are the only functions used, but FindTupleHashEntry()
384 * supports searching a hashtable using cross-data-type hashing. For that,
385 * the caller must supply hash functions for the LHS datatype as well as
386 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
387 * are set to point to the caller's function arrays while doing such a search.
388 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
389 * tab_eq_funcs respectively.
390 * ----------------------------------------------------------------
392 typedef struct TupleHashEntryData *TupleHashEntry;
393 typedef struct TupleHashTableData *TupleHashTable;
395 typedef struct TupleHashEntryData
397 /* firstTuple must be the first field in this struct! */
398 MinimalTuple firstTuple; /* copy of first tuple in this group */
399 /* there may be additional data beyond the end of this struct */
400 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
402 typedef struct TupleHashTableData
404 HTAB *hashtab; /* underlying dynahash table */
405 int numCols; /* number of columns in lookup key */
406 AttrNumber *keyColIdx; /* attr numbers of key columns */
407 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
408 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
409 MemoryContext tablecxt; /* memory context containing table */
410 MemoryContext tempcxt; /* context for function evaluations */
411 Size entrysize; /* actual size to make each hash entry */
412 TupleTableSlot *tableslot; /* slot for referencing table entries */
413 /* The following fields are set transiently for each table search: */
414 TupleTableSlot *inputslot; /* current input tuple's slot */
415 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
416 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
417 } TupleHashTableData;
419 typedef HASH_SEQ_STATUS TupleHashIterator;
422 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
423 * Use ResetTupleHashIterator if the table can be frozen (in this case no
424 * explicit scan termination is needed).
426 #define InitTupleHashIterator(htable, iter) \
427 hash_seq_init(iter, (htable)->hashtab)
428 #define TermTupleHashIterator(iter) \
430 #define ResetTupleHashIterator(htable, iter) \
432 hash_freeze((htable)->hashtab); \
433 hash_seq_init(iter, (htable)->hashtab); \
435 #define ScanTupleHashTable(iter) \
436 ((TupleHashEntry) hash_seq_search(iter))
439 /* ----------------------------------------------------------------
440 * Expression State Trees
442 * Each executable expression tree has a parallel ExprState tree.
444 * Unlike PlanState, there is not an exact one-for-one correspondence between
445 * ExprState node types and Expr node types. Many Expr node types have no
446 * need for node-type-specific run-time state, and so they can use plain
447 * ExprState or GenericExprState as their associated ExprState node type.
448 * ----------------------------------------------------------------
454 * ExprState is the common superclass for all ExprState-type nodes.
456 * It can also be instantiated directly for leaf Expr nodes that need no
457 * local run-time state (such as Var, Const, or Param).
459 * To save on dispatch overhead, each ExprState node contains a function
460 * pointer to the routine to execute to evaluate the node.
464 typedef struct ExprState ExprState;
466 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
467 ExprContext *econtext,
469 ExprDoneCond *isDone);
474 Expr *expr; /* associated Expr node */
475 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
479 * GenericExprState node
481 * This is used for Expr node types that need no local run-time state,
482 * but have one child Expr node.
485 typedef struct GenericExprState
488 ExprState *arg; /* state of my child node */
492 * AggrefExprState node
495 typedef struct AggrefExprState
498 List *args; /* states of argument expressions */
499 int aggno; /* ID number for agg within its plan node */
503 * ArrayRefExprState node
505 * Note: array types can be fixed-length (typlen > 0), but only when the
506 * element type is itself fixed-length. Otherwise they are varlena structures
507 * and have typlen = -1. In any case, an array type is never pass-by-value.
510 typedef struct ArrayRefExprState
513 List *refupperindexpr; /* states for child nodes */
514 List *reflowerindexpr;
516 ExprState *refassgnexpr;
517 int16 refattrlength; /* typlen of array type */
518 int16 refelemlength; /* typlen of the array element type */
519 bool refelembyval; /* is the element type pass-by-value? */
520 char refelemalign; /* typalign of the element type */
526 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
527 * and NullIf nodes; be careful to check what xprstate.expr is actually
531 typedef struct FuncExprState
534 List *args; /* states of argument expressions */
537 * Function manager's lookup info for the target function. If func.fn_oid
538 * is InvalidOid, we haven't initialized it yet.
543 * We also need to store argument values across calls when evaluating a
544 * function-returning-set.
546 * setArgsValid is true when we are evaluating a set-valued function and
547 * we are in the middle of a call series; we want to pass the same
548 * argument values to the function again (and again, until it returns
554 * Flag to remember whether we found a set-valued argument to the
555 * function. This causes the function result to be a set as well. Valid
556 * only when setArgsValid is true.
558 bool setHasSetArg; /* some argument returns a set */
561 * Flag to remember whether we have registered a shutdown callback for
562 * this FuncExprState. We do so only if setArgsValid has been true at
563 * least once (since all the callback is for is to clear setArgsValid).
565 bool shutdown_reg; /* a shutdown callback is registered */
568 * Current argument data for a set-valued function; contains valid data
569 * only if setArgsValid is true.
571 FunctionCallInfoData setArgs;
575 * ScalarArrayOpExprState node
577 * This is a FuncExprState plus some additional data.
580 typedef struct ScalarArrayOpExprState
582 FuncExprState fxprstate;
583 /* Cached info about array element type */
588 } ScalarArrayOpExprState;
594 typedef struct BoolExprState
597 List *args; /* states of argument expression(s) */
604 typedef struct SubPlanState
607 struct PlanState *planstate; /* subselect plan's state tree */
608 ExprState *testexpr; /* state of combining expression */
609 List *args; /* states of argument expression(s) */
610 HeapTuple curTuple; /* copy of most recent tuple from subplan */
611 /* these are used when hashing the subselect's output: */
612 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
613 ProjectionInfo *projRight; /* for projecting subselect output */
614 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
615 TupleHashTable hashnulls; /* hash table for rows with null(s) */
616 bool havehashrows; /* TRUE if hashtable is not empty */
617 bool havenullrows; /* TRUE if hashnulls is not empty */
618 MemoryContext tablecxt; /* memory context containing tables */
619 ExprContext *innerecontext; /* working context for comparisons */
620 AttrNumber *keyColIdx; /* control data for hash tables */
621 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
622 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
623 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
624 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
628 * FieldSelectState node
631 typedef struct FieldSelectState
634 ExprState *arg; /* input expression */
635 TupleDesc argdesc; /* tupdesc for most recent input */
639 * FieldStoreState node
642 typedef struct FieldStoreState
645 ExprState *arg; /* input tuple value */
646 List *newvals; /* new value(s) for field(s) */
647 TupleDesc argdesc; /* tupdesc for most recent input */
651 * CoerceViaIOState node
654 typedef struct CoerceViaIOState
657 ExprState *arg; /* input expression */
658 FmgrInfo outfunc; /* lookup info for source output function */
659 FmgrInfo infunc; /* lookup info for result input function */
660 Oid intypioparam; /* argument needed for input function */
664 * ArrayCoerceExprState node
667 typedef struct ArrayCoerceExprState
670 ExprState *arg; /* input array value */
671 Oid resultelemtype; /* element type of result array */
672 FmgrInfo elemfunc; /* lookup info for element coercion function */
673 /* use struct pointer to avoid including array.h here */
674 struct ArrayMapState *amstate; /* workspace for array_map */
675 } ArrayCoerceExprState;
678 * ConvertRowtypeExprState node
681 typedef struct ConvertRowtypeExprState
684 ExprState *arg; /* input tuple value */
685 TupleDesc indesc; /* tupdesc for source rowtype */
686 TupleDesc outdesc; /* tupdesc for result rowtype */
687 AttrNumber *attrMap; /* indexes of input fields, or 0 for null */
688 Datum *invalues; /* workspace for deconstructing source */
690 Datum *outvalues; /* workspace for constructing result */
692 } ConvertRowtypeExprState;
698 typedef struct CaseExprState
701 ExprState *arg; /* implicit equality comparison argument */
702 List *args; /* the arguments (list of WHEN clauses) */
703 ExprState *defresult; /* the default result (ELSE clause) */
710 typedef struct CaseWhenState
713 ExprState *expr; /* condition expression */
714 ExprState *result; /* substitution result */
718 * ArrayExprState node
720 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
724 typedef struct ArrayExprState
727 List *elements; /* states for child nodes */
728 int16 elemlength; /* typlen of the array element type */
729 bool elembyval; /* is the element type pass-by-value? */
730 char elemalign; /* typalign of the element type */
737 typedef struct RowExprState
740 List *args; /* the arguments */
741 TupleDesc tupdesc; /* descriptor for result tuples */
745 * RowCompareExprState node
748 typedef struct RowCompareExprState
751 List *largs; /* the left-hand input arguments */
752 List *rargs; /* the right-hand input arguments */
753 FmgrInfo *funcs; /* array of comparison function info */
754 } RowCompareExprState;
757 * CoalesceExprState node
760 typedef struct CoalesceExprState
763 List *args; /* the arguments */
767 * MinMaxExprState node
770 typedef struct MinMaxExprState
773 List *args; /* the arguments */
774 FmgrInfo cfunc; /* lookup info for comparison func */
781 typedef struct XmlExprState
784 List *named_args; /* ExprStates for named arguments */
785 FmgrInfo *named_outfuncs; /* array of output fns for named arguments */
786 List *args; /* ExprStates for other arguments */
793 typedef struct NullTestState
796 ExprState *arg; /* input expression */
797 bool argisrow; /* T if input is of a composite type */
798 /* used only if argisrow: */
799 TupleDesc argdesc; /* tupdesc for most recent input */
803 * CoerceToDomainState node
806 typedef struct CoerceToDomainState
809 ExprState *arg; /* input expression */
810 /* Cached list of constraints that need to be checked */
811 List *constraints; /* list of DomainConstraintState nodes */
812 } CoerceToDomainState;
815 * DomainConstraintState - one item to check during CoerceToDomain
817 * Note: this is just a Node, and not an ExprState, because it has no
818 * corresponding Expr to link to. Nonetheless it is part of an ExprState
819 * tree, so we give it a name following the xxxState convention.
821 typedef enum DomainConstraintType
823 DOM_CONSTRAINT_NOTNULL,
825 } DomainConstraintType;
827 typedef struct DomainConstraintState
830 DomainConstraintType constrainttype; /* constraint type */
831 char *name; /* name of constraint (for error msgs) */
832 ExprState *check_expr; /* for CHECK, a boolean expression */
833 } DomainConstraintState;
836 /* ----------------------------------------------------------------
837 * Executor State Trees
839 * An executing query has a PlanState tree paralleling the Plan tree
840 * that describes the plan.
841 * ----------------------------------------------------------------
847 * We never actually instantiate any PlanState nodes; this is just the common
848 * abstract superclass for all PlanState-type nodes.
851 typedef struct PlanState
855 Plan *plan; /* associated Plan node */
857 EState *state; /* at execution time, state's of individual
858 * nodes point to one EState for the whole
861 struct Instrumentation *instrument; /* Optional runtime stats for this
865 * Common structural data for all Plan types. These links to subsidiary
866 * state trees parallel links in the associated plan tree (except for the
867 * subPlan list, which does not exist in the plan tree).
869 List *targetlist; /* target list to be computed at this node */
870 List *qual; /* implicitly-ANDed qual conditions */
871 struct PlanState *lefttree; /* input plan tree(s) */
872 struct PlanState *righttree;
873 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
875 List *subPlan; /* SubPlanState nodes in my expressions */
878 * State for management of parameter-change-driven rescanning
880 Bitmapset *chgParam; /* set of IDs of changed Params */
883 * Other run-time state needed by most if not all node types.
885 TupleTableSlot *ps_OuterTupleSlot; /* slot for current "outer" tuple */
886 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
887 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
888 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
889 bool ps_TupFromTlist;/* state flag for processing set-valued
890 * functions in targetlist */
894 * these are are defined to avoid confusion problems with "left"
895 * and "right" and "inner" and "outer". The convention is that
896 * the "left" plan is the "outer" plan and the "right" plan is
897 * the inner plan, but these make the code more readable.
900 #define innerPlanState(node) (((PlanState *)(node))->righttree)
901 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
905 * ResultState information
908 typedef struct ResultState
910 PlanState ps; /* its first field is NodeTag */
911 ExprState *resconstantqual;
912 bool rs_done; /* are we done? */
913 bool rs_checkqual; /* do we need to check the qual? */
917 * AppendState information
919 * nplans how many plans are in the list
920 * whichplan which plan is being executed (0 .. n-1)
921 * firstplan first plan to execute (usually 0)
922 * lastplan last plan to execute (usually n-1)
925 typedef struct AppendState
927 PlanState ps; /* its first field is NodeTag */
928 PlanState **appendplans; /* array of PlanStates for my inputs */
936 * BitmapAndState information
939 typedef struct BitmapAndState
941 PlanState ps; /* its first field is NodeTag */
942 PlanState **bitmapplans; /* array of PlanStates for my inputs */
943 int nplans; /* number of input plans */
947 * BitmapOrState information
950 typedef struct BitmapOrState
952 PlanState ps; /* its first field is NodeTag */
953 PlanState **bitmapplans; /* array of PlanStates for my inputs */
954 int nplans; /* number of input plans */
957 /* ----------------------------------------------------------------
958 * Scan State Information
959 * ----------------------------------------------------------------
963 * ScanState information
965 * ScanState extends PlanState for node types that represent
966 * scans of an underlying relation. It can also be used for nodes
967 * that scan the output of an underlying plan node --- in that case,
968 * only ScanTupleSlot is actually useful, and it refers to the tuple
969 * retrieved from the subplan.
971 * currentRelation relation being scanned (NULL if none)
972 * currentScanDesc current scan descriptor for scan (NULL if none)
973 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
976 typedef struct ScanState
978 PlanState ps; /* its first field is NodeTag */
979 Relation ss_currentRelation;
980 HeapScanDesc ss_currentScanDesc;
981 TupleTableSlot *ss_ScanTupleSlot;
985 * SeqScan uses a bare ScanState as its state node, since it needs
986 * no additional fields.
988 typedef ScanState SeqScanState;
991 * These structs store information about index quals that don't have simple
992 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
997 ScanKey scan_key; /* scankey to put value into */
998 ExprState *key_expr; /* expr to evaluate to get value */
999 } IndexRuntimeKeyInfo;
1003 ScanKey scan_key; /* scankey to put value into */
1004 ExprState *array_expr; /* expr to evaluate to get array value */
1005 int next_elem; /* next array element to use */
1006 int num_elems; /* number of elems in current array value */
1007 Datum *elem_values; /* array of num_elems Datums */
1008 bool *elem_nulls; /* array of num_elems is-null flags */
1009 } IndexArrayKeyInfo;
1012 * IndexScanState information
1014 * indexqualorig execution state for indexqualorig expressions
1015 * ScanKeys Skey structures to scan index rel
1016 * NumScanKeys number of Skey structs
1017 * RuntimeKeys info about Skeys that must be evaluated at runtime
1018 * NumRuntimeKeys number of RuntimeKeys structs
1019 * RuntimeKeysReady true if runtime Skeys have been computed
1020 * RuntimeContext expr context for evaling runtime Skeys
1021 * RelationDesc index relation descriptor
1022 * ScanDesc index scan descriptor
1025 typedef struct IndexScanState
1027 ScanState ss; /* its first field is NodeTag */
1028 List *indexqualorig;
1029 ScanKey iss_ScanKeys;
1030 int iss_NumScanKeys;
1031 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1032 int iss_NumRuntimeKeys;
1033 bool iss_RuntimeKeysReady;
1034 ExprContext *iss_RuntimeContext;
1035 Relation iss_RelationDesc;
1036 IndexScanDesc iss_ScanDesc;
1040 * BitmapIndexScanState information
1042 * result bitmap to return output into, or NULL
1043 * ScanKeys Skey structures to scan index rel
1044 * NumScanKeys number of Skey structs
1045 * RuntimeKeys info about Skeys that must be evaluated at runtime
1046 * NumRuntimeKeys number of RuntimeKeys structs
1047 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1048 * NumArrayKeys number of ArrayKeys structs
1049 * RuntimeKeysReady true if runtime Skeys have been computed
1050 * RuntimeContext expr context for evaling runtime Skeys
1051 * RelationDesc index relation descriptor
1052 * ScanDesc index scan descriptor
1055 typedef struct BitmapIndexScanState
1057 ScanState ss; /* its first field is NodeTag */
1058 TIDBitmap *biss_result;
1059 ScanKey biss_ScanKeys;
1060 int biss_NumScanKeys;
1061 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1062 int biss_NumRuntimeKeys;
1063 IndexArrayKeyInfo *biss_ArrayKeys;
1064 int biss_NumArrayKeys;
1065 bool biss_RuntimeKeysReady;
1066 ExprContext *biss_RuntimeContext;
1067 Relation biss_RelationDesc;
1068 IndexScanDesc biss_ScanDesc;
1069 } BitmapIndexScanState;
1072 * BitmapHeapScanState information
1074 * bitmapqualorig execution state for bitmapqualorig expressions
1075 * tbm bitmap obtained from child index scan(s)
1076 * tbmres current-page data
1079 typedef struct BitmapHeapScanState
1081 ScanState ss; /* its first field is NodeTag */
1082 List *bitmapqualorig;
1084 TBMIterateResult *tbmres;
1085 } BitmapHeapScanState;
1088 * TidScanState information
1090 * isCurrentOf scan has a CurrentOfExpr qual
1091 * NumTids number of tids in this scan
1092 * TidPtr index of currently fetched tid
1093 * TidList evaluated item pointers (array of size NumTids)
1096 typedef struct TidScanState
1098 ScanState ss; /* its first field is NodeTag */
1099 List *tss_tidquals; /* list of ExprState nodes */
1100 bool tss_isCurrentOf;
1104 ItemPointerData *tss_TidList;
1105 HeapTupleData tss_htup;
1109 * SubqueryScanState information
1111 * SubqueryScanState is used for scanning a sub-query in the range table.
1112 * ScanTupleSlot references the current output tuple of the sub-query.
1115 typedef struct SubqueryScanState
1117 ScanState ss; /* its first field is NodeTag */
1119 } SubqueryScanState;
1122 * FunctionScanState information
1124 * Function nodes are used to scan the results of a
1125 * function appearing in FROM (typically a function returning set).
1127 * tupdesc expected return tuple description
1128 * tuplestorestate private state of tuplestore.c
1129 * funcexpr state for function expression being evaluated
1132 typedef struct FunctionScanState
1134 ScanState ss; /* its first field is NodeTag */
1136 Tuplestorestate *tuplestorestate;
1137 ExprState *funcexpr;
1138 } FunctionScanState;
1141 * ValuesScanState information
1143 * ValuesScan nodes are used to scan the results of a VALUES list
1145 * rowcontext per-expression-list context
1146 * exprlists array of expression lists being evaluated
1147 * array_len size of array
1148 * curr_idx current array index (0-based)
1149 * marked_idx marked position (for mark/restore)
1151 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1152 * expressions attached to the node. We create a second ExprContext,
1153 * rowcontext, in which to build the executor expression state for each
1154 * Values sublist. Resetting this context lets us get rid of expression
1155 * state for each row, avoiding major memory leakage over a long values list.
1158 typedef struct ValuesScanState
1160 ScanState ss; /* its first field is NodeTag */
1161 ExprContext *rowcontext;
1168 /* ----------------------------------------------------------------
1169 * Join State Information
1170 * ----------------------------------------------------------------
1174 * JoinState information
1176 * Superclass for state nodes of join plans.
1179 typedef struct JoinState
1183 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1187 * NestLoopState information
1189 * NeedNewOuter true if need new outer tuple on next call
1190 * MatchedOuter true if found a join match for current outer tuple
1191 * NullInnerTupleSlot prepared null tuple for left outer joins
1194 typedef struct NestLoopState
1196 JoinState js; /* its first field is NodeTag */
1197 bool nl_NeedNewOuter;
1198 bool nl_MatchedOuter;
1199 TupleTableSlot *nl_NullInnerTupleSlot;
1203 * MergeJoinState information
1205 * NumClauses number of mergejoinable join clauses
1206 * Clauses info for each mergejoinable clause
1207 * JoinState current "state" of join. see execdefs.h
1208 * ExtraMarks true to issue extra Mark operations on inner scan
1209 * FillOuter true if should emit unjoined outer tuples anyway
1210 * FillInner true if should emit unjoined inner tuples anyway
1211 * MatchedOuter true if found a join match for current outer tuple
1212 * MatchedInner true if found a join match for current inner tuple
1213 * OuterTupleSlot slot in tuple table for cur outer tuple
1214 * InnerTupleSlot slot in tuple table for cur inner tuple
1215 * MarkedTupleSlot slot in tuple table for marked tuple
1216 * NullOuterTupleSlot prepared null tuple for right outer joins
1217 * NullInnerTupleSlot prepared null tuple for left outer joins
1218 * OuterEContext workspace for computing outer tuple's join values
1219 * InnerEContext workspace for computing inner tuple's join values
1222 /* private in nodeMergejoin.c: */
1223 typedef struct MergeJoinClauseData *MergeJoinClause;
1225 typedef struct MergeJoinState
1227 JoinState js; /* its first field is NodeTag */
1229 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1234 bool mj_MatchedOuter;
1235 bool mj_MatchedInner;
1236 TupleTableSlot *mj_OuterTupleSlot;
1237 TupleTableSlot *mj_InnerTupleSlot;
1238 TupleTableSlot *mj_MarkedTupleSlot;
1239 TupleTableSlot *mj_NullOuterTupleSlot;
1240 TupleTableSlot *mj_NullInnerTupleSlot;
1241 ExprContext *mj_OuterEContext;
1242 ExprContext *mj_InnerEContext;
1246 * HashJoinState information
1248 * hj_HashTable hash table for the hashjoin
1249 * (NULL if table not built yet)
1250 * hj_CurHashValue hash value for current outer tuple
1251 * hj_CurBucketNo bucket# for current outer tuple
1252 * hj_CurTuple last inner tuple matched to current outer
1253 * tuple, or NULL if starting search
1254 * (CurHashValue, CurBucketNo and CurTuple are
1255 * undefined if OuterTupleSlot is empty!)
1256 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1257 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1258 * hj_HashOperators the join operators in the hashjoin condition
1259 * hj_OuterTupleSlot tuple slot for outer tuples
1260 * hj_HashTupleSlot tuple slot for hashed tuples
1261 * hj_NullInnerTupleSlot prepared null tuple for left outer joins
1262 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1263 * hj_NeedNewOuter true if need new outer tuple on next call
1264 * hj_MatchedOuter true if found a join match for current outer
1265 * hj_OuterNotEmpty true if outer relation known not empty
1269 /* these structs are defined in executor/hashjoin.h: */
1270 typedef struct HashJoinTupleData *HashJoinTuple;
1271 typedef struct HashJoinTableData *HashJoinTable;
1273 typedef struct HashJoinState
1275 JoinState js; /* its first field is NodeTag */
1276 List *hashclauses; /* list of ExprState nodes */
1277 HashJoinTable hj_HashTable;
1278 uint32 hj_CurHashValue;
1280 HashJoinTuple hj_CurTuple;
1281 List *hj_OuterHashKeys; /* list of ExprState nodes */
1282 List *hj_InnerHashKeys; /* list of ExprState nodes */
1283 List *hj_HashOperators; /* list of operator OIDs */
1284 TupleTableSlot *hj_OuterTupleSlot;
1285 TupleTableSlot *hj_HashTupleSlot;
1286 TupleTableSlot *hj_NullInnerTupleSlot;
1287 TupleTableSlot *hj_FirstOuterTupleSlot;
1288 bool hj_NeedNewOuter;
1289 bool hj_MatchedOuter;
1290 bool hj_OuterNotEmpty;
1294 /* ----------------------------------------------------------------
1295 * Materialization State Information
1296 * ----------------------------------------------------------------
1300 * MaterialState information
1302 * materialize nodes are used to materialize the results
1303 * of a subplan into a temporary file.
1305 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1308 typedef struct MaterialState
1310 ScanState ss; /* its first field is NodeTag */
1311 int eflags; /* capability flags to pass to tuplestore */
1312 bool eof_underlying; /* reached end of underlying plan? */
1313 void *tuplestorestate; /* private state of tuplestore.c */
1317 * SortState information
1320 typedef struct SortState
1322 ScanState ss; /* its first field is NodeTag */
1323 bool randomAccess; /* need random access to sort output? */
1324 bool bounded; /* is the result set bounded? */
1325 int64 bound; /* if bounded, how many tuples are needed */
1326 bool sort_Done; /* sort completed yet? */
1327 bool bounded_Done; /* value of bounded we did the sort with */
1328 int64 bound_Done; /* value of bound we did the sort with */
1329 void *tuplesortstate; /* private state of tuplesort.c */
1332 /* ---------------------
1333 * GroupState information
1334 * -------------------------
1336 typedef struct GroupState
1338 ScanState ss; /* its first field is NodeTag */
1339 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1340 bool grp_done; /* indicates completion of Group scan */
1343 /* ---------------------
1344 * AggState information
1346 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1348 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1349 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1350 * input group during evaluation of an Agg node's output tuple(s). We
1351 * create a second ExprContext, tmpcontext, in which to evaluate input
1352 * expressions and run the aggregate transition functions.
1353 * -------------------------
1355 /* these structs are private in nodeAgg.c: */
1356 typedef struct AggStatePerAggData *AggStatePerAgg;
1357 typedef struct AggStatePerGroupData *AggStatePerGroup;
1359 typedef struct AggState
1361 ScanState ss; /* its first field is NodeTag */
1362 List *aggs; /* all Aggref nodes in targetlist & quals */
1363 int numaggs; /* length of list (could be zero!) */
1364 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1365 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1366 AggStatePerAgg peragg; /* per-Aggref information */
1367 MemoryContext aggcontext; /* memory context for long-lived data */
1368 ExprContext *tmpcontext; /* econtext for input expressions */
1369 bool agg_done; /* indicates completion of Agg scan */
1370 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1371 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1372 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1373 /* these fields are used in AGG_HASHED mode: */
1374 TupleHashTable hashtable; /* hash table with one entry per group */
1375 TupleTableSlot *hashslot; /* slot for loading hash table */
1376 List *hash_needed; /* list of columns needed in hash table */
1377 bool table_filled; /* hash table filled yet? */
1378 TupleHashIterator hashiter; /* for iterating through hash table */
1382 * UniqueState information
1384 * Unique nodes are used "on top of" sort nodes to discard
1385 * duplicate tuples returned from the sort phase. Basically
1386 * all it does is compare the current tuple from the subplan
1387 * with the previously fetched tuple (stored in its result slot).
1388 * If the two are identical in all interesting fields, then
1389 * we just fetch another tuple from the sort and try again.
1392 typedef struct UniqueState
1394 PlanState ps; /* its first field is NodeTag */
1395 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1396 MemoryContext tempContext; /* short-term context for comparisons */
1400 * HashState information
1403 typedef struct HashState
1405 PlanState ps; /* its first field is NodeTag */
1406 HashJoinTable hashtable; /* hash table for the hashjoin */
1407 List *hashkeys; /* list of ExprState nodes */
1408 /* hashkeys is same as parent's hj_InnerHashKeys */
1412 * SetOpState information
1414 * SetOp nodes are used "on top of" sort nodes to discard
1415 * duplicate tuples returned from the sort phase. These are
1416 * more complex than a simple Unique since we have to count
1417 * how many duplicates to return.
1420 typedef struct SetOpState
1422 PlanState ps; /* its first field is NodeTag */
1423 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1424 bool subplan_done; /* has subplan returned EOF? */
1425 long numLeft; /* number of left-input dups of cur group */
1426 long numRight; /* number of right-input dups of cur group */
1427 long numOutput; /* number of dups left to output */
1428 MemoryContext tempContext; /* short-term context for comparisons */
1432 * LimitState information
1434 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1435 * They just select the desired subrange of their subplan's output.
1437 * offset is the number of initial tuples to skip (0 does nothing).
1438 * count is the number of tuples to return after skipping the offset tuples.
1439 * If no limit count was specified, count is undefined and noCount is true.
1440 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1445 LIMIT_INITIAL, /* initial state for LIMIT node */
1446 LIMIT_RESCAN, /* rescan after recomputing parameters */
1447 LIMIT_EMPTY, /* there are no returnable rows */
1448 LIMIT_INWINDOW, /* have returned a row in the window */
1449 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1450 LIMIT_WINDOWEND, /* stepped off end of window */
1451 LIMIT_WINDOWSTART /* stepped off beginning of window */
1454 typedef struct LimitState
1456 PlanState ps; /* its first field is NodeTag */
1457 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1458 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1459 int64 offset; /* current OFFSET value */
1460 int64 count; /* current COUNT, if any */
1461 bool noCount; /* if true, ignore count */
1462 LimitStateCond lstate; /* state machine status, as above */
1463 int64 position; /* 1-based index of last tuple returned */
1464 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1467 #endif /* EXECNODES_H */