1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * $Id: execnodes.h,v 1.74 2002/08/30 23:59:46 tgl Exp $
12 *-------------------------------------------------------------------------
17 #include "access/relscan.h"
18 #include "access/sdir.h"
19 #include "executor/hashjoin.h"
20 #include "executor/tuptable.h"
22 #include "nodes/params.h"
23 #include "nodes/primnodes.h"
24 #include "utils/tuplestore.h"
28 * IndexInfo information
30 * this class holds the information needed to construct new index
31 * entries for a particular index. Used for both index_build and
32 * retail creation of index entries.
34 * NumIndexAttrs number of columns in this index
35 * (1 if a func. index, else same as NumKeyAttrs)
36 * NumKeyAttrs number of key attributes for this index
37 * (ie, number of attrs from underlying relation)
38 * KeyAttrNumbers underlying-rel attribute numbers used as keys
39 * Predicate partial-index predicate, or NIL if none
40 * FuncOid OID of function, or InvalidOid if not f. index
41 * FuncInfo fmgr lookup data for function, if FuncOid valid
42 * Unique is it a unique index?
45 typedef struct IndexInfo
50 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
60 * List of callbacks to be called at ExprContext shutdown.
63 typedef void (*ExprContextCallbackFunction) (Datum arg);
65 typedef struct ExprContext_CB
67 struct ExprContext_CB *next;
68 ExprContextCallbackFunction function;
75 * This class holds the "current context" information
76 * needed to evaluate expressions for doing tuple qualifications
77 * and tuple projections. For example, if an expression refers
78 * to an attribute in the current inner tuple then we need to know
79 * what the current inner tuple is and so we look at the expression
82 * There are two memory contexts associated with an ExprContext:
83 * * ecxt_per_query_memory is a relatively long-lived context (such as
84 * TransactionCommandContext); typically it's the same context the
85 * ExprContext node itself is allocated in. This context can be
86 * used for purposes such as storing operator/function fcache nodes.
87 * * ecxt_per_tuple_memory is a short-term context for expression results.
88 * As the name suggests, it will typically be reset once per tuple,
89 * before we begin to evaluate expressions for that tuple. Each
90 * ExprContext normally has its very own per-tuple memory context.
91 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
92 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
95 typedef struct ExprContext
99 /* Tuples that Var nodes in expression may refer to */
100 TupleTableSlot *ecxt_scantuple;
101 TupleTableSlot *ecxt_innertuple;
102 TupleTableSlot *ecxt_outertuple;
104 /* Memory contexts for expression evaluation --- see notes above */
105 MemoryContext ecxt_per_query_memory;
106 MemoryContext ecxt_per_tuple_memory;
108 /* Values to substitute for Param nodes in expression */
109 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
110 ParamListInfo ecxt_param_list_info; /* for other param types */
112 /* Values to substitute for Aggref nodes in expression */
113 Datum *ecxt_aggvalues; /* precomputed values for Aggref nodes */
114 bool *ecxt_aggnulls; /* null flags for Aggref nodes */
116 /* Functions to call back when ExprContext is shut down */
117 ExprContext_CB *ecxt_callbacks;
121 * Set-result status returned by ExecEvalExpr()
125 ExprSingleResult, /* expression does not return a set */
126 ExprMultipleResult, /* this result is an element of a set */
127 ExprEndResult /* there are no more elements in the set */
131 * Return modes for functions returning sets. Note values must be chosen
132 * as separate bits so that a bitmask can be formed to indicate supported
137 SFRM_ValuePerCall = 0x01, /* one value returned per call */
138 SFRM_Materialize = 0x02 /* result set instantiated in Tuplestore */
139 } SetFunctionReturnMode;
142 * When calling a function that might return a set (multiple rows),
143 * a node of this type is passed as fcinfo->resultinfo to allow
144 * return status to be passed back. A function returning set should
145 * raise an error if no such resultinfo is provided.
147 typedef struct ReturnSetInfo
150 /* values set by caller: */
151 ExprContext *econtext; /* context function is being called in */
152 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
153 int allowedModes; /* bitmask: return modes caller can handle */
154 /* result status from function (but pre-initialized by caller): */
155 SetFunctionReturnMode returnMode; /* actual return mode */
156 ExprDoneCond isDone; /* status for ValuePerCall mode */
157 /* fields filled by function in Materialize return mode: */
158 Tuplestorestate *setResult; /* holds the complete returned tuple set */
159 TupleDesc setDesc; /* actual descriptor for returned tuples */
163 * ProjectionInfo node information
165 * This is all the information needed to perform projections
166 * on a tuple. Nodes which need to do projections create one
167 * of these. In theory, when a node wants to perform a projection
168 * it should just update this information as necessary and then
169 * call ExecProject(). -cim 6/3/91
171 * targetlist target list for projection
172 * len length of target list
173 * tupValue array of pointers to projection results
174 * exprContext expression context for ExecTargetList
175 * slot slot to place projection result in
178 typedef struct ProjectionInfo
184 ExprContext *pi_exprContext;
185 TupleTableSlot *pi_slot;
191 * This class is used to store information regarding junk attributes.
192 * A junk attribute is an attribute in a tuple that is needed only for
193 * storing intermediate information in the executor, and does not belong
194 * in emitted tuples. For example, when we do an UPDATE query,
195 * the planner adds a "junk" entry to the targetlist so that the tuples
196 * returned to ExecutePlan() contain an extra attribute: the ctid of
197 * the tuple to be updated. This is needed to do the update, but we
198 * don't want the ctid to be part of the stored new tuple! So, we
199 * apply a "junk filter" to remove the junk attributes and form the
202 * targetList: the original target list (including junk attributes).
203 * length: the length of 'targetList'.
204 * tupType: the tuple descriptor for the "original" tuple
205 * (including the junk attributes).
206 * cleanTargetList: the "clean" target list (junk attributes removed).
207 * cleanLength: the length of 'cleanTargetList'
208 * cleanTupType: the tuple descriptor of the "clean" tuple (with
209 * junk attributes removed).
210 * cleanMap: A map with the correspondence between the non-junk
211 * attribute numbers of the "original" tuple and the
212 * attribute numbers of the "clean" tuple.
213 * junkContext: memory context holding the JunkFilter node and all
214 * its subsidiary data structures.
215 * resultSlot: tuple slot that can be used to hold cleaned tuple.
217 * NOTE: the original targetList and tupType are passed to ExecInitJunkFilter,
218 * as is the resultSlot. These items do not belong to the JunkFilter. All
219 * the other subsidiary structures are created during ExecInitJunkFilter,
220 * and all of them can be freed by deleting the memory context junkContext.
221 * This would not be needed if we had a cleaner approach to managing
222 * query-lifetime data structures...
225 typedef struct JunkFilter
230 TupleDesc jf_tupType;
231 List *jf_cleanTargetList;
233 TupleDesc jf_cleanTupType;
234 AttrNumber *jf_cleanMap;
235 MemoryContext jf_junkContext;
236 TupleTableSlot *jf_resultSlot;
240 * ResultRelInfo information
242 * Whenever we update an existing relation, we have to
243 * update indices on the relation, and perhaps also fire triggers.
244 * The ResultRelInfo class is used to hold all the information needed
245 * about a result relation, including indices.. -cim 10/15/89
247 * RangeTableIndex result relation's range table index
248 * RelationDesc relation descriptor for result relation
249 * NumIndices # of indices existing on result relation
250 * IndexRelationDescs array of relation descriptors for indices
251 * IndexRelationInfo array of key/attr info for indices
252 * TrigDesc triggers to be fired, if any
253 * TrigFunctions cached lookup info for trigger functions
254 * ConstraintExprs array of constraint-checking expressions
255 * junkFilter for removing junk attributes from tuples
258 typedef struct ResultRelInfo
261 Index ri_RangeTableIndex;
262 Relation ri_RelationDesc;
264 RelationPtr ri_IndexRelationDescs;
265 IndexInfo **ri_IndexRelationInfo;
266 TriggerDesc *ri_TrigDesc;
267 FmgrInfo *ri_TrigFunctions;
268 List **ri_ConstraintExprs;
269 JunkFilter *ri_junkFilter;
275 * direction direction of the scan
277 * range_table array of scan relation information
279 * result_relation information for insert/update/delete queries
281 * into_relation_descriptor relation being retrieved "into"
283 * param_list_info information needed to transform
284 * Param nodes into Const nodes
286 * tupleTable this is a pointer to an array
287 * of pointers to tuples used by
288 * the executor at any given moment.
291 typedef struct EState
294 ScanDirection es_direction;
295 Snapshot es_snapshot;
296 List *es_range_table;
297 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
298 int es_num_result_relations; /* length of array */
299 ResultRelInfo *es_result_relation_info; /* currently active array
301 JunkFilter *es_junkFilter; /* currently active junk filter */
302 Relation es_into_relation_descriptor;
303 ParamListInfo es_param_list_info;
304 ParamExecData *es_param_exec_vals; /* this is for subselects */
305 TupleTable es_tupleTable;
306 uint32 es_processed; /* # of tuples processed */
307 Oid es_lastoid; /* last oid processed (by INSERT) */
308 List *es_rowMark; /* not good place, but there is no other */
309 MemoryContext es_query_cxt; /* per-query context in which EState lives */
312 * this ExprContext is for per-output-tuple operations, such as
313 * constraint checks and index-value computations. It will be reset
314 * for each output tuple. Note that it will be created only if
317 ExprContext *es_per_tuple_exprcontext;
318 /* Below is to re-evaluate plan qual in READ COMMITTED mode */
319 struct Plan *es_origPlan;
320 Pointer es_evalPlanQual;
321 bool *es_evTupleNull;
322 HeapTuple *es_evTuple;
327 * Executor Type information needed by plannodes.h
329 *| Note: the bogus classes CommonState and CommonScanState exist only
330 *| because our inheritance system only allows single inheritance
331 *| and we have to have unique slot names. Hence two or more
332 *| classes which want to have a common slot must ALL inherit
333 *| the slot from some other class. (This is a big hack to
334 *| allow our classes to share slot names..)
337 *| the class Result and the class NestLoop nodes both want
338 *| a slot called "OuterTuple" so they both have to inherit
339 *| it from some other class. In this case they inherit
340 *| it from CommonState. "CommonState" and "CommonScanState" are
341 *| the best names I could come up with for this sort of
344 *| As a result, many classes have extra slots which they
345 *| don't use. These slots are denoted (unused) in the
346 *| comment preceding the class definition. If you
347 *| comes up with a better idea of a way of doing things
348 *| along these lines, then feel free to make your idea
349 *| known to me.. -cim 10/15/89
353 /* ----------------------------------------------------------------
354 * Common Executor State Information
355 * ----------------------------------------------------------------
359 * CommonState information
361 * Superclass for all executor node-state object types.
363 * OuterTupleSlot pointer to slot containing current "outer" tuple
364 * ResultTupleSlot pointer to slot in tuple table for projected tuple
365 * ExprContext node's expression-evaluation context
366 * ProjInfo info this node uses to form tuple projections
367 * TupFromTlist state flag used by some node types (why kept here?)
370 typedef struct CommonState
372 NodeTag type; /* its first field is NodeTag */
373 TupleTableSlot *cs_OuterTupleSlot;
374 TupleTableSlot *cs_ResultTupleSlot;
375 ExprContext *cs_ExprContext;
376 ProjectionInfo *cs_ProjInfo;
377 bool cs_TupFromTlist;
381 /* ----------------------------------------------------------------
382 * Control Node State Information
383 * ----------------------------------------------------------------
387 * ResultState information
389 * done flag which tells us to quit when we
390 * have already returned a constant tuple.
393 typedef struct ResultState
395 CommonState cstate; /* its first field is NodeTag */
401 * AppendState information
403 * whichplan which plan is being executed (0 .. n-1)
404 * firstplan first plan to execute (usually 0)
405 * lastplan last plan to execute (usually n-1)
406 * nplans how many plans are in the list
407 * initialized array of ExecInitNode() results
410 typedef struct AppendState
412 CommonState cstate; /* its first field is NodeTag */
417 bool *as_initialized;
420 /* ----------------------------------------------------------------
421 * Scan State Information
422 * ----------------------------------------------------------------
426 * CommonScanState information
428 * CommonScanState extends CommonState for node types that represent
429 * scans of an underlying relation. It can also be used for nodes
430 * that scan the output of an underlying plan node --- in that case,
431 * only ScanTupleSlot is actually useful, and it refers to the tuple
432 * retrieved from the subplan.
434 * currentRelation relation being scanned (NULL if none)
435 * currentScanDesc current scan descriptor for scan (NULL if none)
436 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
439 typedef struct CommonScanState
441 CommonState cstate; /* its first field is NodeTag */
442 Relation css_currentRelation;
443 HeapScanDesc css_currentScanDesc;
444 TupleTableSlot *css_ScanTupleSlot;
448 * SeqScan uses a bare CommonScanState as its state item, since it needs
449 * no additional fields.
453 * IndexScanState information
455 * Note that an IndexScan node *also* has a CommonScanState state item.
456 * IndexScanState stores the info needed specifically for indexing.
457 * There's probably no good reason why this is a separate node type
458 * rather than an extension of CommonScanState.
460 * NumIndices number of indices in this scan
461 * IndexPtr current index in use
462 * ScanKeys Skey structures to scan index rels
463 * NumScanKeys array of no of keys in each Skey struct
464 * RuntimeKeyInfo array of array of flags for Skeys evaled at runtime
465 * RuntimeContext expr context for evaling runtime Skeys
466 * RuntimeKeysReady true if runtime Skeys have been computed
467 * RelationDescs ptr to array of relation descriptors
468 * ScanDescs ptr to array of scan descriptors
471 typedef struct IndexScanState
476 int iss_MarkIndexPtr;
477 ScanKey *iss_ScanKeys;
478 int *iss_NumScanKeys;
479 int **iss_RuntimeKeyInfo;
480 ExprContext *iss_RuntimeContext;
481 bool iss_RuntimeKeysReady;
482 RelationPtr iss_RelationDescs;
483 IndexScanDescPtr iss_ScanDescs;
487 * TidScanState information
489 * Note that a TidScan node *also* has a CommonScanState state item.
490 * There's probably no good reason why this is a separate node type
491 * rather than an extension of CommonScanState.
493 * NumTids number of tids in this scan
494 * TidPtr current tid in use
495 * TidList evaluated item pointers
498 typedef struct TidScanState
504 ItemPointerData *tss_TidList;
505 HeapTupleData tss_htup;
509 * SubqueryScanState information
511 * SubqueryScanState is used for scanning a sub-query in the range table.
512 * The sub-query will have its own EState, which we save here.
513 * ScanTupleSlot references the current output tuple of the sub-query.
515 * SubEState exec state for sub-query
518 typedef struct SubqueryScanState
520 CommonScanState csstate; /* its first field is NodeTag */
521 EState *sss_SubEState;
525 * FunctionScanState information
527 * Function nodes are used to scan the results of a
528 * function appearing in FROM (typically a function returning set).
530 * tupdesc expected return tuple description
531 * tuplestorestate private state of tuplestore.c
532 * funcexpr function expression being evaluated
535 typedef struct FunctionScanState
537 CommonScanState csstate; /* its first field is NodeTag */
539 Tuplestorestate *tuplestorestate;
543 /* ----------------------------------------------------------------
544 * Join State Information
545 * ----------------------------------------------------------------
549 * JoinState information
551 * Superclass for state items of join nodes.
552 * Currently this is the same as CommonState.
555 typedef CommonState JoinState;
558 * NestLoopState information
560 * NeedNewOuter true if need new outer tuple on next call
561 * MatchedOuter true if found a join match for current outer tuple
562 * NullInnerTupleSlot prepared null tuple for left outer joins
565 typedef struct NestLoopState
567 JoinState jstate; /* its first field is NodeTag */
568 bool nl_NeedNewOuter;
569 bool nl_MatchedOuter;
570 TupleTableSlot *nl_NullInnerTupleSlot;
574 * MergeJoinState information
576 * OuterSkipQual outerKey1 < innerKey1 ...
577 * InnerSkipQual outerKey1 > innerKey1 ...
578 * JoinState current "state" of join. see executor.h
579 * MatchedOuter true if found a join match for current outer tuple
580 * MatchedInner true if found a join match for current inner tuple
581 * OuterTupleSlot pointer to slot in tuple table for cur outer tuple
582 * InnerTupleSlot pointer to slot in tuple table for cur inner tuple
583 * MarkedTupleSlot pointer to slot in tuple table for marked tuple
584 * NullOuterTupleSlot prepared null tuple for right outer joins
585 * NullInnerTupleSlot prepared null tuple for left outer joins
588 typedef struct MergeJoinState
590 JoinState jstate; /* its first field is NodeTag */
591 List *mj_OuterSkipQual;
592 List *mj_InnerSkipQual;
594 bool mj_MatchedOuter;
595 bool mj_MatchedInner;
596 TupleTableSlot *mj_OuterTupleSlot;
597 TupleTableSlot *mj_InnerTupleSlot;
598 TupleTableSlot *mj_MarkedTupleSlot;
599 TupleTableSlot *mj_NullOuterTupleSlot;
600 TupleTableSlot *mj_NullInnerTupleSlot;
604 * HashJoinState information
606 * hj_HashTable hash table for the hashjoin
607 * hj_CurBucketNo bucket# for current outer tuple
608 * hj_CurTuple last inner tuple matched to current outer
609 * tuple, or NULL if starting search
610 * (CurBucketNo and CurTuple are meaningless
611 * unless OuterTupleSlot is nonempty!)
612 * hj_InnerHashKey the inner hash key in the hashjoin condition
613 * hj_OuterTupleSlot tuple slot for outer tuples
614 * hj_HashTupleSlot tuple slot for hashed tuples
615 * hj_NullInnerTupleSlot prepared null tuple for left outer joins
616 * hj_NeedNewOuter true if need new outer tuple on next call
617 * hj_MatchedOuter true if found a join match for current outer
618 * hj_hashdone true if hash-table-build phase is done
621 typedef struct HashJoinState
623 JoinState jstate; /* its first field is NodeTag */
624 HashJoinTable hj_HashTable;
626 HashJoinTuple hj_CurTuple;
627 Node *hj_InnerHashKey;
628 TupleTableSlot *hj_OuterTupleSlot;
629 TupleTableSlot *hj_HashTupleSlot;
630 TupleTableSlot *hj_NullInnerTupleSlot;
631 bool hj_NeedNewOuter;
632 bool hj_MatchedOuter;
637 /* ----------------------------------------------------------------
638 * Materialization State Information
639 * ----------------------------------------------------------------
643 * MaterialState information
645 * materialize nodes are used to materialize the results
646 * of a subplan into a temporary file.
648 * csstate.css_ScanTupleSlot refers to output of underlying plan.
650 * tuplestorestate private state of tuplestore.c
653 typedef struct MaterialState
655 CommonScanState csstate; /* its first field is NodeTag */
656 void *tuplestorestate;
659 /* ---------------------
660 * AggregateState information
662 * csstate.css_ScanTupleSlot refers to output of underlying plan.
664 * Note: the associated ExprContext contains ecxt_aggvalues and ecxt_aggnulls
665 * arrays, which hold the computed agg values for the current input group
666 * during evaluation of an Agg node's output tuple(s).
667 * -------------------------
669 typedef struct AggStatePerAggData *AggStatePerAgg; /* private in nodeAgg.c */
671 typedef struct AggState
673 CommonScanState csstate; /* its first field is NodeTag */
674 List *aggs; /* all Aggref nodes in targetlist & quals */
675 int numaggs; /* length of list (could be zero!) */
676 AggStatePerAgg peragg; /* per-Aggref working state */
677 MemoryContext tup_cxt; /* context for per-output-tuple
679 MemoryContext agg_cxt[2]; /* pair of expression eval memory contexts */
680 int which_cxt; /* 0 or 1, indicates current agg_cxt */
681 bool agg_done; /* indicates completion of Agg scan */
684 /* ---------------------
685 * GroupState information
686 * -------------------------
688 typedef struct GroupState
690 CommonScanState csstate; /* its first field is NodeTag */
691 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
692 bool grp_useFirstTuple; /* first tuple not processed yet */
694 HeapTuple grp_firstTuple;
698 * SortState information
700 * sort_Done indicates whether sort has been performed yet
701 * tuplesortstate private state of tuplesort.c
704 typedef struct SortState
706 CommonScanState csstate; /* its first field is NodeTag */
708 void *tuplesortstate;
712 * UniqueState information
714 * Unique nodes are used "on top of" sort nodes to discard
715 * duplicate tuples returned from the sort phase. Basically
716 * all it does is compare the current tuple from the subplan
717 * with the previously fetched tuple stored in priorTuple.
718 * If the two are identical in all interesting fields, then
719 * we just fetch another tuple from the sort and try again.
722 typedef struct UniqueState
724 CommonState cstate; /* its first field is NodeTag */
725 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
726 HeapTuple priorTuple; /* most recently returned tuple, or NULL */
727 MemoryContext tempContext; /* short-term context for comparisons */
731 * SetOpState information
733 * SetOp nodes are used "on top of" sort nodes to discard
734 * duplicate tuples returned from the sort phase. These are
735 * more complex than a simple Unique since we have to count
736 * how many duplicates to return.
739 typedef struct SetOpState
741 CommonState cstate; /* its first field is NodeTag */
742 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
743 bool subplan_done; /* has subplan returned EOF? */
744 long numLeft; /* number of left-input dups of cur group */
745 long numRight; /* number of right-input dups of cur group */
746 long numOutput; /* number of dups left to output */
747 MemoryContext tempContext; /* short-term context for comparisons */
751 * LimitState information
753 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
754 * They just select the desired subrange of their subplan's output.
756 * offset is the number of initial tuples to skip (0 does nothing).
757 * count is the number of tuples to return after skipping the offset tuples.
758 * If no limit count was specified, count is undefined and noCount is true.
761 typedef struct LimitState
763 CommonState cstate; /* its first field is NodeTag */
764 long offset; /* current OFFSET value */
765 long count; /* current COUNT, if any */
766 long position; /* 1-based index of last tuple fetched */
767 bool parmsSet; /* have we calculated offset/limit yet? */
768 bool noCount; /* if true, ignore count */
769 bool atEnd; /* if true, we've reached EOF of subplan */
774 * HashState information
776 * hashtable hash table for the hashjoin
779 typedef struct HashState
781 CommonState cstate; /* its first field is NodeTag */
782 HashJoinTable hashtable;
786 /* -----------------------
787 * TeeState information
788 * leftPlace : next item in the queue unseen by the left parent
789 * rightPlace : next item in the queue unseen by the right parent
790 * lastPlace : last item in the queue
791 * bufferRelname : name of the relation used as the buffer queue
792 * bufferRel : the relation used as the buffer queue
793 * mcxt : for now, tee's have their own memory context
794 * may be cleaned up later if portals are cleaned up
796 * initially, a Tee starts with [left/right]Place variables set to -1.
797 * on cleanup, queue is free'd when both leftPlace and rightPlace = -1
798 * -------------------------
800 typedef struct TeeState
802 CommonState cstate; /* its first field is NodeTag */
806 char *tee_bufferRelname;
807 Relation tee_bufferRel;
808 MemoryContext tee_mcxt;
809 HeapScanDesc tee_leftScanDesc,
814 #endif /* EXECNODES_H */