1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/skey.h"
20 #include "nodes/params.h"
21 #include "nodes/plannodes.h"
22 #include "nodes/tidbitmap.h"
23 #include "utils/hsearch.h"
24 #include "utils/rel.h"
25 #include "utils/snapshot.h"
26 #include "utils/tuplestore.h"
30 * IndexInfo information
32 * this struct holds the information needed to construct new index
33 * entries for a particular index. Used for both index_build and
34 * retail creation of index entries.
36 * NumIndexAttrs number of columns in this index
37 * KeyAttrNumbers underlying-rel attribute numbers used as keys
38 * (zeroes indicate expressions)
39 * Expressions expr trees for expression entries, or NIL if none
40 * ExpressionsState exec state for expressions, or NIL if none
41 * Predicate partial-index predicate, or NIL if none
42 * PredicateState exec state for predicate, or NIL if none
43 * Unique is it a unique index?
44 * ReadyForInserts is it valid for inserts?
45 * Concurrent are we doing a concurrent index build?
46 * BrokenHotChain did we detect any broken HOT chains?
48 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
49 * they're conventionally set to false otherwise.
52 typedef struct IndexInfo
56 AttrNumber ii_KeyAttrNumbers
[INDEX_MAX_KEYS
];
57 List
*ii_Expressions
; /* list of Expr */
58 List
*ii_ExpressionsState
; /* list of ExprState */
59 List
*ii_Predicate
; /* list of Expr */
60 List
*ii_PredicateState
; /* list of ExprState */
62 bool ii_ReadyForInserts
;
64 bool ii_BrokenHotChain
;
70 * List of callbacks to be called at ExprContext shutdown.
73 typedef void (*ExprContextCallbackFunction
) (Datum arg
);
75 typedef struct ExprContext_CB
77 struct ExprContext_CB
*next
;
78 ExprContextCallbackFunction function
;
85 * This class holds the "current context" information
86 * needed to evaluate expressions for doing tuple qualifications
87 * and tuple projections. For example, if an expression refers
88 * to an attribute in the current inner tuple then we need to know
89 * what the current inner tuple is and so we look at the expression
92 * There are two memory contexts associated with an ExprContext:
93 * * ecxt_per_query_memory is a query-lifespan context, typically the same
94 * context the ExprContext node itself is allocated in. This context
95 * can be used for purposes such as storing function call cache info.
96 * * ecxt_per_tuple_memory is a short-term context for expression results.
97 * As the name suggests, it will typically be reset once per tuple,
98 * before we begin to evaluate expressions for that tuple. Each
99 * ExprContext normally has its very own per-tuple memory context.
101 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
102 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
105 typedef struct ExprContext
109 /* Tuples that Var nodes in expression may refer to */
110 TupleTableSlot
*ecxt_scantuple
;
111 TupleTableSlot
*ecxt_innertuple
;
112 TupleTableSlot
*ecxt_outertuple
;
114 /* Memory contexts for expression evaluation --- see notes above */
115 MemoryContext ecxt_per_query_memory
;
116 MemoryContext ecxt_per_tuple_memory
;
118 /* Values to substitute for Param nodes in expression */
119 ParamExecData
*ecxt_param_exec_vals
; /* for PARAM_EXEC params */
120 ParamListInfo ecxt_param_list_info
; /* for other param types */
122 /* Values to substitute for Aggref nodes in expression */
123 Datum
*ecxt_aggvalues
; /* precomputed values for Aggref nodes */
124 bool *ecxt_aggnulls
; /* null flags for Aggref nodes */
126 /* Value to substitute for CaseTestExpr nodes in expression */
127 Datum caseValue_datum
;
128 bool caseValue_isNull
;
130 /* Value to substitute for CoerceToDomainValue nodes in expression */
131 Datum domainValue_datum
;
132 bool domainValue_isNull
;
134 /* Link to containing EState (NULL if a standalone ExprContext) */
135 struct EState
*ecxt_estate
;
137 /* Functions to call back when ExprContext is shut down */
138 ExprContext_CB
*ecxt_callbacks
;
142 * Set-result status returned by ExecEvalExpr()
146 ExprSingleResult
, /* expression does not return a set */
147 ExprMultipleResult
, /* this result is an element of a set */
148 ExprEndResult
/* there are no more elements in the set */
152 * Return modes for functions returning sets. Note values must be chosen
153 * as separate bits so that a bitmask can be formed to indicate supported
158 SFRM_ValuePerCall
= 0x01, /* one value returned per call */
159 SFRM_Materialize
= 0x02 /* result set instantiated in Tuplestore */
160 } SetFunctionReturnMode
;
163 * When calling a function that might return a set (multiple rows),
164 * a node of this type is passed as fcinfo->resultinfo to allow
165 * return status to be passed back. A function returning set should
166 * raise an error if no such resultinfo is provided.
168 typedef struct ReturnSetInfo
171 /* values set by caller: */
172 ExprContext
*econtext
; /* context function is being called in */
173 TupleDesc expectedDesc
; /* tuple descriptor expected by caller */
174 int allowedModes
; /* bitmask: return modes caller can handle */
175 /* result status from function (but pre-initialized by caller): */
176 SetFunctionReturnMode returnMode
; /* actual return mode */
177 ExprDoneCond isDone
; /* status for ValuePerCall mode */
178 /* fields filled by function in Materialize return mode: */
179 Tuplestorestate
*setResult
; /* holds the complete returned tuple set */
180 TupleDesc setDesc
; /* actual descriptor for returned tuples */
184 * ProjectionInfo node information
186 * This is all the information needed to perform projections ---
187 * that is, form new tuples by evaluation of targetlist expressions.
188 * Nodes which need to do projections create one of these.
190 * ExecProject() evaluates the tlist, forms a tuple, and stores it
191 * in the given slot. Note that the result will be a "virtual" tuple
192 * unless ExecMaterializeSlot() is then called to force it to be
193 * converted to a physical tuple. The slot must have a tupledesc
194 * that matches the output of the tlist!
196 * The planner very often produces tlists that consist entirely of
197 * simple Var references (lower levels of a plan tree almost always
198 * look like that). So we have an optimization to handle that case
199 * with minimum overhead.
201 * targetlist target list for projection
202 * exprContext expression context in which to evaluate targetlist
203 * slot slot to place projection result in
204 * itemIsDone workspace for ExecProject
205 * isVarList TRUE if simple-Var-list optimization applies
206 * varSlotOffsets array indicating which slot each simple Var is from
207 * varNumbers array indicating attr numbers of simple Vars
208 * lastInnerVar highest attnum from inner tuple slot (0 if none)
209 * lastOuterVar highest attnum from outer tuple slot (0 if none)
210 * lastScanVar highest attnum from scan tuple slot (0 if none)
213 typedef struct ProjectionInfo
217 ExprContext
*pi_exprContext
;
218 TupleTableSlot
*pi_slot
;
219 ExprDoneCond
*pi_itemIsDone
;
221 int *pi_varSlotOffsets
;
231 * This class is used to store information regarding junk attributes.
232 * A junk attribute is an attribute in a tuple that is needed only for
233 * storing intermediate information in the executor, and does not belong
234 * in emitted tuples. For example, when we do an UPDATE query,
235 * the planner adds a "junk" entry to the targetlist so that the tuples
236 * returned to ExecutePlan() contain an extra attribute: the ctid of
237 * the tuple to be updated. This is needed to do the update, but we
238 * don't want the ctid to be part of the stored new tuple! So, we
239 * apply a "junk filter" to remove the junk attributes and form the
240 * real output tuple. The junkfilter code also provides routines to
241 * extract the values of the junk attribute(s) from the input tuple.
243 * targetList: the original target list (including junk attributes).
244 * cleanTupType: the tuple descriptor for the "clean" tuple (with
245 * junk attributes removed).
246 * cleanMap: A map with the correspondence between the non-junk
247 * attribute numbers of the "original" tuple and the
248 * attribute numbers of the "clean" tuple.
249 * resultSlot: tuple slot used to hold cleaned tuple.
250 * junkAttNo: not used by junkfilter code. Can be used by caller
251 * to remember the attno of a specific junk attribute
252 * (execMain.c stores the "ctid" attno here).
255 typedef struct JunkFilter
259 TupleDesc jf_cleanTupType
;
260 AttrNumber
*jf_cleanMap
;
261 TupleTableSlot
*jf_resultSlot
;
262 AttrNumber jf_junkAttNo
;
266 * ResultRelInfo information
268 * Whenever we update an existing relation, we have to
269 * update indices on the relation, and perhaps also fire triggers.
270 * The ResultRelInfo class is used to hold all the information needed
271 * about a result relation, including indices.. -cim 10/15/89
273 * RangeTableIndex result relation's range table index
274 * RelationDesc relation descriptor for result relation
275 * NumIndices # of indices existing on result relation
276 * IndexRelationDescs array of relation descriptors for indices
277 * IndexRelationInfo array of key/attr info for indices
278 * TrigDesc triggers to be fired, if any
279 * TrigFunctions cached lookup info for trigger functions
280 * TrigInstrument optional runtime measurements for triggers
281 * ConstraintExprs array of constraint-checking expr states
282 * junkFilter for removing junk attributes from tuples
283 * projectReturning for computing a RETURNING list
286 typedef struct ResultRelInfo
289 Index ri_RangeTableIndex
;
290 Relation ri_RelationDesc
;
292 RelationPtr ri_IndexRelationDescs
;
293 IndexInfo
**ri_IndexRelationInfo
;
294 TriggerDesc
*ri_TrigDesc
;
295 FmgrInfo
*ri_TrigFunctions
;
296 struct Instrumentation
*ri_TrigInstrument
;
297 List
**ri_ConstraintExprs
;
298 JunkFilter
*ri_junkFilter
;
299 ProjectionInfo
*ri_projectReturning
;
305 * Master working state for an Executor invocation
308 typedef struct EState
312 /* Basic state for all query types: */
313 ScanDirection es_direction
; /* current scan direction */
314 Snapshot es_snapshot
; /* time qual to use */
315 Snapshot es_crosscheck_snapshot
; /* crosscheck time qual for RI */
316 List
*es_range_table
; /* List of RangeTblEntry */
318 /* If query can insert/delete tuples, the command ID to mark them with */
319 CommandId es_output_cid
;
321 /* Info about target table for insert/update/delete queries: */
322 ResultRelInfo
*es_result_relations
; /* array of ResultRelInfos */
323 int es_num_result_relations
; /* length of array */
324 ResultRelInfo
*es_result_relation_info
; /* currently active array elt */
325 JunkFilter
*es_junkFilter
; /* currently active junk filter */
327 /* Stuff used for firing triggers: */
328 List
*es_trig_target_relations
; /* trigger-only ResultRelInfos */
329 TupleTableSlot
*es_trig_tuple_slot
; /* for trigger output tuples */
331 /* Parameter info: */
332 ParamListInfo es_param_list_info
; /* values of external params */
333 ParamExecData
*es_param_exec_vals
; /* values of internal params */
335 /* Other working state: */
336 MemoryContext es_query_cxt
; /* per-query context in which EState lives */
338 TupleTable es_tupleTable
; /* Array of TupleTableSlots */
340 uint32 es_processed
; /* # of tuples processed */
341 Oid es_lastoid
; /* last oid processed (by INSERT) */
342 List
*es_rowMarks
; /* not good place, but there is no other */
344 bool es_instrument
; /* true requests runtime instrumentation */
345 bool es_select_into
; /* true if doing SELECT INTO */
346 bool es_into_oids
; /* true to generate OIDs in SELECT INTO */
348 List
*es_exprcontexts
; /* List of ExprContexts within EState */
350 List
*es_subplanstates
; /* List of PlanState for SubPlans */
353 * this ExprContext is for per-output-tuple operations, such as constraint
354 * checks and index-value computations. It will be reset for each output
355 * tuple. Note that it will be created only if needed.
357 ExprContext
*es_per_tuple_exprcontext
;
359 /* Below is to re-evaluate plan qual in READ COMMITTED mode */
360 PlannedStmt
*es_plannedstmt
; /* link to top of plan tree */
361 struct evalPlanQual
*es_evalPlanQual
; /* chain of PlanQual states */
362 bool *es_evTupleNull
; /* local array of EPQ status */
363 HeapTuple
*es_evTuple
; /* shared array of EPQ substitute tuples */
364 bool es_useEvalPlan
; /* evaluating EPQ tuples? */
368 /* es_rowMarks is a list of these structs: */
369 typedef struct ExecRowMark
371 Relation relation
; /* opened and RowShareLock'd relation */
372 Index rti
; /* its range table index */
373 bool forUpdate
; /* true = FOR UPDATE, false = FOR SHARE */
374 bool noWait
; /* NOWAIT option */
375 AttrNumber ctidAttNo
; /* resno of its ctid junk attribute */
379 /* ----------------------------------------------------------------
382 * All-in-memory tuple hash tables are used for a number of purposes.
384 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
385 * and tab_eq_funcs are non-cross-type equality operators for those types.
386 * Normally these are the only functions used, but FindTupleHashEntry()
387 * supports searching a hashtable using cross-data-type hashing. For that,
388 * the caller must supply hash functions for the LHS datatype as well as
389 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
390 * are set to point to the caller's function arrays while doing such a search.
391 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
392 * tab_eq_funcs respectively.
393 * ----------------------------------------------------------------
395 typedef struct TupleHashEntryData
*TupleHashEntry
;
396 typedef struct TupleHashTableData
*TupleHashTable
;
398 typedef struct TupleHashEntryData
400 /* firstTuple must be the first field in this struct! */
401 MinimalTuple firstTuple
; /* copy of first tuple in this group */
402 /* there may be additional data beyond the end of this struct */
403 } TupleHashEntryData
; /* VARIABLE LENGTH STRUCT */
405 typedef struct TupleHashTableData
407 HTAB
*hashtab
; /* underlying dynahash table */
408 int numCols
; /* number of columns in lookup key */
409 AttrNumber
*keyColIdx
; /* attr numbers of key columns */
410 FmgrInfo
*tab_hash_funcs
; /* hash functions for table datatype(s) */
411 FmgrInfo
*tab_eq_funcs
; /* equality functions for table datatype(s) */
412 MemoryContext tablecxt
; /* memory context containing table */
413 MemoryContext tempcxt
; /* context for function evaluations */
414 Size entrysize
; /* actual size to make each hash entry */
415 TupleTableSlot
*tableslot
; /* slot for referencing table entries */
416 /* The following fields are set transiently for each table search: */
417 TupleTableSlot
*inputslot
; /* current input tuple's slot */
418 FmgrInfo
*in_hash_funcs
; /* hash functions for input datatype(s) */
419 FmgrInfo
*cur_eq_funcs
; /* equality functions for input vs. table */
420 } TupleHashTableData
;
422 typedef HASH_SEQ_STATUS TupleHashIterator
;
425 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
426 * Use ResetTupleHashIterator if the table can be frozen (in this case no
427 * explicit scan termination is needed).
429 #define InitTupleHashIterator(htable, iter) \
430 hash_seq_init(iter, (htable)->hashtab)
431 #define TermTupleHashIterator(iter) \
433 #define ResetTupleHashIterator(htable, iter) \
435 hash_freeze((htable)->hashtab); \
436 hash_seq_init(iter, (htable)->hashtab); \
438 #define ScanTupleHashTable(iter) \
439 ((TupleHashEntry) hash_seq_search(iter))
442 /* ----------------------------------------------------------------
443 * Expression State Trees
445 * Each executable expression tree has a parallel ExprState tree.
447 * Unlike PlanState, there is not an exact one-for-one correspondence between
448 * ExprState node types and Expr node types. Many Expr node types have no
449 * need for node-type-specific run-time state, and so they can use plain
450 * ExprState or GenericExprState as their associated ExprState node type.
451 * ----------------------------------------------------------------
457 * ExprState is the common superclass for all ExprState-type nodes.
459 * It can also be instantiated directly for leaf Expr nodes that need no
460 * local run-time state (such as Var, Const, or Param).
462 * To save on dispatch overhead, each ExprState node contains a function
463 * pointer to the routine to execute to evaluate the node.
467 typedef struct ExprState ExprState
;
469 typedef Datum (*ExprStateEvalFunc
) (ExprState
*expression
,
470 ExprContext
*econtext
,
472 ExprDoneCond
*isDone
);
477 Expr
*expr
; /* associated Expr node */
478 ExprStateEvalFunc evalfunc
; /* routine to run to execute node */
482 * GenericExprState node
484 * This is used for Expr node types that need no local run-time state,
485 * but have one child Expr node.
488 typedef struct GenericExprState
491 ExprState
*arg
; /* state of my child node */
495 * AggrefExprState node
498 typedef struct AggrefExprState
501 List
*args
; /* states of argument expressions */
502 int aggno
; /* ID number for agg within its plan node */
506 * ArrayRefExprState node
508 * Note: array types can be fixed-length (typlen > 0), but only when the
509 * element type is itself fixed-length. Otherwise they are varlena structures
510 * and have typlen = -1. In any case, an array type is never pass-by-value.
513 typedef struct ArrayRefExprState
516 List
*refupperindexpr
; /* states for child nodes */
517 List
*reflowerindexpr
;
519 ExprState
*refassgnexpr
;
520 int16 refattrlength
; /* typlen of array type */
521 int16 refelemlength
; /* typlen of the array element type */
522 bool refelembyval
; /* is the element type pass-by-value? */
523 char refelemalign
; /* typalign of the element type */
529 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
530 * and NullIf nodes; be careful to check what xprstate.expr is actually
534 typedef struct FuncExprState
537 List
*args
; /* states of argument expressions */
540 * Function manager's lookup info for the target function. If func.fn_oid
541 * is InvalidOid, we haven't initialized it yet.
546 * We also need to store argument values across calls when evaluating a
547 * function-returning-set.
549 * setArgsValid is true when we are evaluating a set-valued function and
550 * we are in the middle of a call series; we want to pass the same
551 * argument values to the function again (and again, until it returns
557 * Flag to remember whether we found a set-valued argument to the
558 * function. This causes the function result to be a set as well. Valid
559 * only when setArgsValid is true.
561 bool setHasSetArg
; /* some argument returns a set */
564 * Flag to remember whether we have registered a shutdown callback for
565 * this FuncExprState. We do so only if setArgsValid has been true at
566 * least once (since all the callback is for is to clear setArgsValid).
568 bool shutdown_reg
; /* a shutdown callback is registered */
571 * Current argument data for a set-valued function; contains valid data
572 * only if setArgsValid is true.
574 FunctionCallInfoData setArgs
;
578 * ScalarArrayOpExprState node
580 * This is a FuncExprState plus some additional data.
583 typedef struct ScalarArrayOpExprState
585 FuncExprState fxprstate
;
586 /* Cached info about array element type */
591 } ScalarArrayOpExprState
;
597 typedef struct BoolExprState
600 List
*args
; /* states of argument expression(s) */
607 typedef struct SubPlanState
610 struct PlanState
*planstate
; /* subselect plan's state tree */
611 ExprState
*testexpr
; /* state of combining expression */
612 List
*args
; /* states of argument expression(s) */
613 HeapTuple curTuple
; /* copy of most recent tuple from subplan */
614 /* these are used when hashing the subselect's output: */
615 ProjectionInfo
*projLeft
; /* for projecting lefthand exprs */
616 ProjectionInfo
*projRight
; /* for projecting subselect output */
617 TupleHashTable hashtable
; /* hash table for no-nulls subselect rows */
618 TupleHashTable hashnulls
; /* hash table for rows with null(s) */
619 bool havehashrows
; /* TRUE if hashtable is not empty */
620 bool havenullrows
; /* TRUE if hashnulls is not empty */
621 MemoryContext tablecxt
; /* memory context containing tables */
622 ExprContext
*innerecontext
; /* working context for comparisons */
623 AttrNumber
*keyColIdx
; /* control data for hash tables */
624 FmgrInfo
*tab_hash_funcs
; /* hash functions for table datatype(s) */
625 FmgrInfo
*tab_eq_funcs
; /* equality functions for table datatype(s) */
626 FmgrInfo
*lhs_hash_funcs
; /* hash functions for lefthand datatype(s) */
627 FmgrInfo
*cur_eq_funcs
; /* equality functions for LHS vs. table */
631 * AlternativeSubPlanState node
634 typedef struct AlternativeSubPlanState
637 List
*subplans
; /* states of alternative subplans */
638 int active
; /* list index of the one we're using */
639 } AlternativeSubPlanState
;
642 * FieldSelectState node
645 typedef struct FieldSelectState
648 ExprState
*arg
; /* input expression */
649 TupleDesc argdesc
; /* tupdesc for most recent input */
653 * FieldStoreState node
656 typedef struct FieldStoreState
659 ExprState
*arg
; /* input tuple value */
660 List
*newvals
; /* new value(s) for field(s) */
661 TupleDesc argdesc
; /* tupdesc for most recent input */
665 * CoerceViaIOState node
668 typedef struct CoerceViaIOState
671 ExprState
*arg
; /* input expression */
672 FmgrInfo outfunc
; /* lookup info for source output function */
673 FmgrInfo infunc
; /* lookup info for result input function */
674 Oid intypioparam
; /* argument needed for input function */
678 * ArrayCoerceExprState node
681 typedef struct ArrayCoerceExprState
684 ExprState
*arg
; /* input array value */
685 Oid resultelemtype
; /* element type of result array */
686 FmgrInfo elemfunc
; /* lookup info for element coercion function */
687 /* use struct pointer to avoid including array.h here */
688 struct ArrayMapState
*amstate
; /* workspace for array_map */
689 } ArrayCoerceExprState
;
692 * ConvertRowtypeExprState node
695 typedef struct ConvertRowtypeExprState
698 ExprState
*arg
; /* input tuple value */
699 TupleDesc indesc
; /* tupdesc for source rowtype */
700 TupleDesc outdesc
; /* tupdesc for result rowtype */
701 AttrNumber
*attrMap
; /* indexes of input fields, or 0 for null */
702 Datum
*invalues
; /* workspace for deconstructing source */
704 Datum
*outvalues
; /* workspace for constructing result */
706 } ConvertRowtypeExprState
;
712 typedef struct CaseExprState
715 ExprState
*arg
; /* implicit equality comparison argument */
716 List
*args
; /* the arguments (list of WHEN clauses) */
717 ExprState
*defresult
; /* the default result (ELSE clause) */
724 typedef struct CaseWhenState
727 ExprState
*expr
; /* condition expression */
728 ExprState
*result
; /* substitution result */
732 * ArrayExprState node
734 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
738 typedef struct ArrayExprState
741 List
*elements
; /* states for child nodes */
742 int16 elemlength
; /* typlen of the array element type */
743 bool elembyval
; /* is the element type pass-by-value? */
744 char elemalign
; /* typalign of the element type */
751 typedef struct RowExprState
754 List
*args
; /* the arguments */
755 TupleDesc tupdesc
; /* descriptor for result tuples */
759 * RowCompareExprState node
762 typedef struct RowCompareExprState
765 List
*largs
; /* the left-hand input arguments */
766 List
*rargs
; /* the right-hand input arguments */
767 FmgrInfo
*funcs
; /* array of comparison function info */
768 } RowCompareExprState
;
771 * CoalesceExprState node
774 typedef struct CoalesceExprState
777 List
*args
; /* the arguments */
781 * MinMaxExprState node
784 typedef struct MinMaxExprState
787 List
*args
; /* the arguments */
788 FmgrInfo cfunc
; /* lookup info for comparison func */
795 typedef struct XmlExprState
798 List
*named_args
; /* ExprStates for named arguments */
799 FmgrInfo
*named_outfuncs
; /* array of output fns for named arguments */
800 List
*args
; /* ExprStates for other arguments */
807 typedef struct NullTestState
810 ExprState
*arg
; /* input expression */
811 bool argisrow
; /* T if input is of a composite type */
812 /* used only if argisrow: */
813 TupleDesc argdesc
; /* tupdesc for most recent input */
817 * CoerceToDomainState node
820 typedef struct CoerceToDomainState
823 ExprState
*arg
; /* input expression */
824 /* Cached list of constraints that need to be checked */
825 List
*constraints
; /* list of DomainConstraintState nodes */
826 } CoerceToDomainState
;
829 * DomainConstraintState - one item to check during CoerceToDomain
831 * Note: this is just a Node, and not an ExprState, because it has no
832 * corresponding Expr to link to. Nonetheless it is part of an ExprState
833 * tree, so we give it a name following the xxxState convention.
835 typedef enum DomainConstraintType
837 DOM_CONSTRAINT_NOTNULL
,
839 } DomainConstraintType
;
841 typedef struct DomainConstraintState
844 DomainConstraintType constrainttype
; /* constraint type */
845 char *name
; /* name of constraint (for error msgs) */
846 ExprState
*check_expr
; /* for CHECK, a boolean expression */
847 } DomainConstraintState
;
850 /* ----------------------------------------------------------------
851 * Executor State Trees
853 * An executing query has a PlanState tree paralleling the Plan tree
854 * that describes the plan.
855 * ----------------------------------------------------------------
861 * We never actually instantiate any PlanState nodes; this is just the common
862 * abstract superclass for all PlanState-type nodes.
865 typedef struct PlanState
869 Plan
*plan
; /* associated Plan node */
871 EState
*state
; /* at execution time, state's of individual
872 * nodes point to one EState for the whole
875 struct Instrumentation
*instrument
; /* Optional runtime stats for this
879 * Common structural data for all Plan types. These links to subsidiary
880 * state trees parallel links in the associated plan tree (except for the
881 * subPlan list, which does not exist in the plan tree).
883 List
*targetlist
; /* target list to be computed at this node */
884 List
*qual
; /* implicitly-ANDed qual conditions */
885 struct PlanState
*lefttree
; /* input plan tree(s) */
886 struct PlanState
*righttree
;
887 List
*initPlan
; /* Init SubPlanState nodes (un-correlated expr
889 List
*subPlan
; /* SubPlanState nodes in my expressions */
892 * State for management of parameter-change-driven rescanning
894 Bitmapset
*chgParam
; /* set of IDs of changed Params */
897 * Other run-time state needed by most if not all node types.
899 TupleTableSlot
*ps_OuterTupleSlot
; /* slot for current "outer" tuple */
900 TupleTableSlot
*ps_ResultTupleSlot
; /* slot for my result tuples */
901 ExprContext
*ps_ExprContext
; /* node's expression-evaluation context */
902 ProjectionInfo
*ps_ProjInfo
; /* info for doing tuple projection */
903 bool ps_TupFromTlist
;/* state flag for processing set-valued
904 * functions in targetlist */
908 * these are are defined to avoid confusion problems with "left"
909 * and "right" and "inner" and "outer". The convention is that
910 * the "left" plan is the "outer" plan and the "right" plan is
911 * the inner plan, but these make the code more readable.
914 #define innerPlanState(node) (((PlanState *)(node))->righttree)
915 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
919 * ResultState information
922 typedef struct ResultState
924 PlanState ps
; /* its first field is NodeTag */
925 ExprState
*resconstantqual
;
926 bool rs_done
; /* are we done? */
927 bool rs_checkqual
; /* do we need to check the qual? */
931 * AppendState information
933 * nplans how many plans are in the list
934 * whichplan which plan is being executed (0 .. n-1)
935 * firstplan first plan to execute (usually 0)
936 * lastplan last plan to execute (usually n-1)
939 typedef struct AppendState
941 PlanState ps
; /* its first field is NodeTag */
942 PlanState
**appendplans
; /* array of PlanStates for my inputs */
950 * BitmapAndState information
953 typedef struct BitmapAndState
955 PlanState ps
; /* its first field is NodeTag */
956 PlanState
**bitmapplans
; /* array of PlanStates for my inputs */
957 int nplans
; /* number of input plans */
961 * BitmapOrState information
964 typedef struct BitmapOrState
966 PlanState ps
; /* its first field is NodeTag */
967 PlanState
**bitmapplans
; /* array of PlanStates for my inputs */
968 int nplans
; /* number of input plans */
971 /* ----------------------------------------------------------------
972 * Scan State Information
973 * ----------------------------------------------------------------
977 * ScanState information
979 * ScanState extends PlanState for node types that represent
980 * scans of an underlying relation. It can also be used for nodes
981 * that scan the output of an underlying plan node --- in that case,
982 * only ScanTupleSlot is actually useful, and it refers to the tuple
983 * retrieved from the subplan.
985 * currentRelation relation being scanned (NULL if none)
986 * currentScanDesc current scan descriptor for scan (NULL if none)
987 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
990 typedef struct ScanState
992 PlanState ps
; /* its first field is NodeTag */
993 Relation ss_currentRelation
;
994 HeapScanDesc ss_currentScanDesc
;
995 TupleTableSlot
*ss_ScanTupleSlot
;
999 * SeqScan uses a bare ScanState as its state node, since it needs
1000 * no additional fields.
1002 typedef ScanState SeqScanState
;
1005 * These structs store information about index quals that don't have simple
1006 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1011 ScanKey scan_key
; /* scankey to put value into */
1012 ExprState
*key_expr
; /* expr to evaluate to get value */
1013 } IndexRuntimeKeyInfo
;
1017 ScanKey scan_key
; /* scankey to put value into */
1018 ExprState
*array_expr
; /* expr to evaluate to get array value */
1019 int next_elem
; /* next array element to use */
1020 int num_elems
; /* number of elems in current array value */
1021 Datum
*elem_values
; /* array of num_elems Datums */
1022 bool *elem_nulls
; /* array of num_elems is-null flags */
1023 } IndexArrayKeyInfo
;
1026 * IndexScanState information
1028 * indexqualorig execution state for indexqualorig expressions
1029 * ScanKeys Skey structures to scan index rel
1030 * NumScanKeys number of Skey structs
1031 * RuntimeKeys info about Skeys that must be evaluated at runtime
1032 * NumRuntimeKeys number of RuntimeKeys structs
1033 * RuntimeKeysReady true if runtime Skeys have been computed
1034 * RuntimeContext expr context for evaling runtime Skeys
1035 * RelationDesc index relation descriptor
1036 * ScanDesc index scan descriptor
1039 typedef struct IndexScanState
1041 ScanState ss
; /* its first field is NodeTag */
1042 List
*indexqualorig
;
1043 ScanKey iss_ScanKeys
;
1044 int iss_NumScanKeys
;
1045 IndexRuntimeKeyInfo
*iss_RuntimeKeys
;
1046 int iss_NumRuntimeKeys
;
1047 bool iss_RuntimeKeysReady
;
1048 ExprContext
*iss_RuntimeContext
;
1049 Relation iss_RelationDesc
;
1050 IndexScanDesc iss_ScanDesc
;
1054 * BitmapIndexScanState information
1056 * result bitmap to return output into, or NULL
1057 * ScanKeys Skey structures to scan index rel
1058 * NumScanKeys number of Skey structs
1059 * RuntimeKeys info about Skeys that must be evaluated at runtime
1060 * NumRuntimeKeys number of RuntimeKeys structs
1061 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1062 * NumArrayKeys number of ArrayKeys structs
1063 * RuntimeKeysReady true if runtime Skeys have been computed
1064 * RuntimeContext expr context for evaling runtime Skeys
1065 * RelationDesc index relation descriptor
1066 * ScanDesc index scan descriptor
1069 typedef struct BitmapIndexScanState
1071 ScanState ss
; /* its first field is NodeTag */
1072 TIDBitmap
*biss_result
;
1073 ScanKey biss_ScanKeys
;
1074 int biss_NumScanKeys
;
1075 IndexRuntimeKeyInfo
*biss_RuntimeKeys
;
1076 int biss_NumRuntimeKeys
;
1077 IndexArrayKeyInfo
*biss_ArrayKeys
;
1078 int biss_NumArrayKeys
;
1079 bool biss_RuntimeKeysReady
;
1080 ExprContext
*biss_RuntimeContext
;
1081 Relation biss_RelationDesc
;
1082 IndexScanDesc biss_ScanDesc
;
1083 } BitmapIndexScanState
;
1086 * BitmapHeapScanState information
1088 * bitmapqualorig execution state for bitmapqualorig expressions
1089 * tbm bitmap obtained from child index scan(s)
1090 * tbmres current-page data
1093 typedef struct BitmapHeapScanState
1095 ScanState ss
; /* its first field is NodeTag */
1096 List
*bitmapqualorig
;
1098 TBMIterateResult
*tbmres
;
1099 } BitmapHeapScanState
;
1102 * TidScanState information
1104 * isCurrentOf scan has a CurrentOfExpr qual
1105 * NumTids number of tids in this scan
1106 * TidPtr index of currently fetched tid
1107 * TidList evaluated item pointers (array of size NumTids)
1110 typedef struct TidScanState
1112 ScanState ss
; /* its first field is NodeTag */
1113 List
*tss_tidquals
; /* list of ExprState nodes */
1114 bool tss_isCurrentOf
;
1118 ItemPointerData
*tss_TidList
;
1119 HeapTupleData tss_htup
;
1123 * SubqueryScanState information
1125 * SubqueryScanState is used for scanning a sub-query in the range table.
1126 * ScanTupleSlot references the current output tuple of the sub-query.
1129 typedef struct SubqueryScanState
1131 ScanState ss
; /* its first field is NodeTag */
1133 } SubqueryScanState
;
1136 * FunctionScanState information
1138 * Function nodes are used to scan the results of a
1139 * function appearing in FROM (typically a function returning set).
1141 * tupdesc expected return tuple description
1142 * tuplestorestate private state of tuplestore.c
1143 * funcexpr state for function expression being evaluated
1146 typedef struct FunctionScanState
1148 ScanState ss
; /* its first field is NodeTag */
1150 Tuplestorestate
*tuplestorestate
;
1151 ExprState
*funcexpr
;
1152 } FunctionScanState
;
1155 * ValuesScanState information
1157 * ValuesScan nodes are used to scan the results of a VALUES list
1159 * rowcontext per-expression-list context
1160 * exprlists array of expression lists being evaluated
1161 * array_len size of array
1162 * curr_idx current array index (0-based)
1163 * marked_idx marked position (for mark/restore)
1165 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1166 * expressions attached to the node. We create a second ExprContext,
1167 * rowcontext, in which to build the executor expression state for each
1168 * Values sublist. Resetting this context lets us get rid of expression
1169 * state for each row, avoiding major memory leakage over a long values list.
1172 typedef struct ValuesScanState
1174 ScanState ss
; /* its first field is NodeTag */
1175 ExprContext
*rowcontext
;
1182 /* ----------------------------------------------------------------
1183 * Join State Information
1184 * ----------------------------------------------------------------
1188 * JoinState information
1190 * Superclass for state nodes of join plans.
1193 typedef struct JoinState
1197 List
*joinqual
; /* JOIN quals (in addition to ps.qual) */
1201 * NestLoopState information
1203 * NeedNewOuter true if need new outer tuple on next call
1204 * MatchedOuter true if found a join match for current outer tuple
1205 * NullInnerTupleSlot prepared null tuple for left outer joins
1208 typedef struct NestLoopState
1210 JoinState js
; /* its first field is NodeTag */
1211 bool nl_NeedNewOuter
;
1212 bool nl_MatchedOuter
;
1213 TupleTableSlot
*nl_NullInnerTupleSlot
;
1217 * MergeJoinState information
1219 * NumClauses number of mergejoinable join clauses
1220 * Clauses info for each mergejoinable clause
1221 * JoinState current "state" of join. see execdefs.h
1222 * ExtraMarks true to issue extra Mark operations on inner scan
1223 * FillOuter true if should emit unjoined outer tuples anyway
1224 * FillInner true if should emit unjoined inner tuples anyway
1225 * MatchedOuter true if found a join match for current outer tuple
1226 * MatchedInner true if found a join match for current inner tuple
1227 * OuterTupleSlot slot in tuple table for cur outer tuple
1228 * InnerTupleSlot slot in tuple table for cur inner tuple
1229 * MarkedTupleSlot slot in tuple table for marked tuple
1230 * NullOuterTupleSlot prepared null tuple for right outer joins
1231 * NullInnerTupleSlot prepared null tuple for left outer joins
1232 * OuterEContext workspace for computing outer tuple's join values
1233 * InnerEContext workspace for computing inner tuple's join values
1236 /* private in nodeMergejoin.c: */
1237 typedef struct MergeJoinClauseData
*MergeJoinClause
;
1239 typedef struct MergeJoinState
1241 JoinState js
; /* its first field is NodeTag */
1243 MergeJoinClause mj_Clauses
; /* array of length mj_NumClauses */
1248 bool mj_MatchedOuter
;
1249 bool mj_MatchedInner
;
1250 TupleTableSlot
*mj_OuterTupleSlot
;
1251 TupleTableSlot
*mj_InnerTupleSlot
;
1252 TupleTableSlot
*mj_MarkedTupleSlot
;
1253 TupleTableSlot
*mj_NullOuterTupleSlot
;
1254 TupleTableSlot
*mj_NullInnerTupleSlot
;
1255 ExprContext
*mj_OuterEContext
;
1256 ExprContext
*mj_InnerEContext
;
1260 * HashJoinState information
1262 * hj_HashTable hash table for the hashjoin
1263 * (NULL if table not built yet)
1264 * hj_CurHashValue hash value for current outer tuple
1265 * hj_CurBucketNo bucket# for current outer tuple
1266 * hj_CurTuple last inner tuple matched to current outer
1267 * tuple, or NULL if starting search
1268 * (CurHashValue, CurBucketNo and CurTuple are
1269 * undefined if OuterTupleSlot is empty!)
1270 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1271 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1272 * hj_HashOperators the join operators in the hashjoin condition
1273 * hj_OuterTupleSlot tuple slot for outer tuples
1274 * hj_HashTupleSlot tuple slot for hashed tuples
1275 * hj_NullInnerTupleSlot prepared null tuple for left outer joins
1276 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1277 * hj_NeedNewOuter true if need new outer tuple on next call
1278 * hj_MatchedOuter true if found a join match for current outer
1279 * hj_OuterNotEmpty true if outer relation known not empty
1283 /* these structs are defined in executor/hashjoin.h: */
1284 typedef struct HashJoinTupleData
*HashJoinTuple
;
1285 typedef struct HashJoinTableData
*HashJoinTable
;
1287 typedef struct HashJoinState
1289 JoinState js
; /* its first field is NodeTag */
1290 List
*hashclauses
; /* list of ExprState nodes */
1291 HashJoinTable hj_HashTable
;
1292 uint32 hj_CurHashValue
;
1294 HashJoinTuple hj_CurTuple
;
1295 List
*hj_OuterHashKeys
; /* list of ExprState nodes */
1296 List
*hj_InnerHashKeys
; /* list of ExprState nodes */
1297 List
*hj_HashOperators
; /* list of operator OIDs */
1298 TupleTableSlot
*hj_OuterTupleSlot
;
1299 TupleTableSlot
*hj_HashTupleSlot
;
1300 TupleTableSlot
*hj_NullInnerTupleSlot
;
1301 TupleTableSlot
*hj_FirstOuterTupleSlot
;
1302 bool hj_NeedNewOuter
;
1303 bool hj_MatchedOuter
;
1304 bool hj_OuterNotEmpty
;
1308 /* ----------------------------------------------------------------
1309 * Materialization State Information
1310 * ----------------------------------------------------------------
1314 * MaterialState information
1316 * materialize nodes are used to materialize the results
1317 * of a subplan into a temporary file.
1319 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1322 typedef struct MaterialState
1324 ScanState ss
; /* its first field is NodeTag */
1325 int eflags
; /* capability flags to pass to tuplestore */
1326 bool eof_underlying
; /* reached end of underlying plan? */
1327 void *tuplestorestate
; /* private state of tuplestore.c */
1331 * SortState information
1334 typedef struct SortState
1336 ScanState ss
; /* its first field is NodeTag */
1337 bool randomAccess
; /* need random access to sort output? */
1338 bool bounded
; /* is the result set bounded? */
1339 int64 bound
; /* if bounded, how many tuples are needed */
1340 bool sort_Done
; /* sort completed yet? */
1341 bool bounded_Done
; /* value of bounded we did the sort with */
1342 int64 bound_Done
; /* value of bound we did the sort with */
1343 void *tuplesortstate
; /* private state of tuplesort.c */
1346 /* ---------------------
1347 * GroupState information
1348 * -------------------------
1350 typedef struct GroupState
1352 ScanState ss
; /* its first field is NodeTag */
1353 FmgrInfo
*eqfunctions
; /* per-field lookup data for equality fns */
1354 bool grp_done
; /* indicates completion of Group scan */
1357 /* ---------------------
1358 * AggState information
1360 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1362 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1363 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1364 * input group during evaluation of an Agg node's output tuple(s). We
1365 * create a second ExprContext, tmpcontext, in which to evaluate input
1366 * expressions and run the aggregate transition functions.
1367 * -------------------------
1369 /* these structs are private in nodeAgg.c: */
1370 typedef struct AggStatePerAggData
*AggStatePerAgg
;
1371 typedef struct AggStatePerGroupData
*AggStatePerGroup
;
1373 typedef struct AggState
1375 ScanState ss
; /* its first field is NodeTag */
1376 List
*aggs
; /* all Aggref nodes in targetlist & quals */
1377 int numaggs
; /* length of list (could be zero!) */
1378 FmgrInfo
*eqfunctions
; /* per-grouping-field equality fns */
1379 FmgrInfo
*hashfunctions
; /* per-grouping-field hash fns */
1380 AggStatePerAgg peragg
; /* per-Aggref information */
1381 MemoryContext aggcontext
; /* memory context for long-lived data */
1382 ExprContext
*tmpcontext
; /* econtext for input expressions */
1383 bool agg_done
; /* indicates completion of Agg scan */
1384 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1385 AggStatePerGroup pergroup
; /* per-Aggref-per-group working state */
1386 HeapTuple grp_firstTuple
; /* copy of first tuple of current group */
1387 /* these fields are used in AGG_HASHED mode: */
1388 TupleHashTable hashtable
; /* hash table with one entry per group */
1389 TupleTableSlot
*hashslot
; /* slot for loading hash table */
1390 List
*hash_needed
; /* list of columns needed in hash table */
1391 bool table_filled
; /* hash table filled yet? */
1392 TupleHashIterator hashiter
; /* for iterating through hash table */
1396 * UniqueState information
1398 * Unique nodes are used "on top of" sort nodes to discard
1399 * duplicate tuples returned from the sort phase. Basically
1400 * all it does is compare the current tuple from the subplan
1401 * with the previously fetched tuple (stored in its result slot).
1402 * If the two are identical in all interesting fields, then
1403 * we just fetch another tuple from the sort and try again.
1406 typedef struct UniqueState
1408 PlanState ps
; /* its first field is NodeTag */
1409 FmgrInfo
*eqfunctions
; /* per-field lookup data for equality fns */
1410 MemoryContext tempContext
; /* short-term context for comparisons */
1414 * HashState information
1417 typedef struct HashState
1419 PlanState ps
; /* its first field is NodeTag */
1420 HashJoinTable hashtable
; /* hash table for the hashjoin */
1421 List
*hashkeys
; /* list of ExprState nodes */
1422 /* hashkeys is same as parent's hj_InnerHashKeys */
1426 * SetOpState information
1428 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1429 * Unique, since we have to count how many duplicates to return. But
1430 * we also support hashing, so this is really more like a cut-down
1434 /* this struct is private in nodeSetOp.c: */
1435 typedef struct SetOpStatePerGroupData
*SetOpStatePerGroup
;
1437 typedef struct SetOpState
1439 PlanState ps
; /* its first field is NodeTag */
1440 FmgrInfo
*eqfunctions
; /* per-grouping-field equality fns */
1441 FmgrInfo
*hashfunctions
; /* per-grouping-field hash fns */
1442 bool setop_done
; /* indicates completion of output scan */
1443 long numOutput
; /* number of dups left to output */
1444 MemoryContext tempContext
; /* short-term context for comparisons */
1445 /* these fields are used in SETOP_SORTED mode: */
1446 SetOpStatePerGroup pergroup
; /* per-group working state */
1447 HeapTuple grp_firstTuple
; /* copy of first tuple of current group */
1448 /* these fields are used in SETOP_HASHED mode: */
1449 TupleHashTable hashtable
; /* hash table with one entry per group */
1450 MemoryContext tableContext
; /* memory context containing hash table */
1451 bool table_filled
; /* hash table filled yet? */
1452 TupleHashIterator hashiter
; /* for iterating through hash table */
1456 * LimitState information
1458 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1459 * They just select the desired subrange of their subplan's output.
1461 * offset is the number of initial tuples to skip (0 does nothing).
1462 * count is the number of tuples to return after skipping the offset tuples.
1463 * If no limit count was specified, count is undefined and noCount is true.
1464 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1469 LIMIT_INITIAL
, /* initial state for LIMIT node */
1470 LIMIT_RESCAN
, /* rescan after recomputing parameters */
1471 LIMIT_EMPTY
, /* there are no returnable rows */
1472 LIMIT_INWINDOW
, /* have returned a row in the window */
1473 LIMIT_SUBPLANEOF
, /* at EOF of subplan (within window) */
1474 LIMIT_WINDOWEND
, /* stepped off end of window */
1475 LIMIT_WINDOWSTART
/* stepped off beginning of window */
1478 typedef struct LimitState
1480 PlanState ps
; /* its first field is NodeTag */
1481 ExprState
*limitOffset
; /* OFFSET parameter, or NULL if none */
1482 ExprState
*limitCount
; /* COUNT parameter, or NULL if none */
1483 int64 offset
; /* current OFFSET value */
1484 int64 count
; /* current COUNT, if any */
1485 bool noCount
; /* if true, ignore count */
1486 LimitStateCond lstate
; /* state machine status, as above */
1487 int64 position
; /* 1-based index of last tuple returned */
1488 TupleTableSlot
*subSlot
; /* tuple last obtained from subplan */
1491 #endif /* EXECNODES_H */