1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/include/nodes/execnodes.h
12 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "executor/instrument.h"
20 #include "nodes/params.h"
21 #include "nodes/plannodes.h"
22 #include "utils/reltrigger.h"
23 #include "utils/sortsupport.h"
24 #include "utils/tuplestore.h"
28 * IndexInfo information
30 * this struct holds the information needed to construct new index
31 * entries for a particular index. Used for both index_build and
32 * retail creation of index entries.
34 * NumIndexAttrs number of columns in this index
35 * KeyAttrNumbers underlying-rel attribute numbers used as keys
36 * (zeroes indicate expressions)
37 * Expressions expr trees for expression entries, or NIL if none
38 * ExpressionsState exec state for expressions, or NIL if none
39 * Predicate partial-index predicate, or NIL if none
40 * PredicateState exec state for predicate, or NIL if none
41 * ExclusionOps Per-column exclusion operators, or NULL if none
42 * ExclusionProcs Underlying function OIDs for ExclusionOps
43 * ExclusionStrats Opclass strategy numbers for ExclusionOps
44 * Unique is it a unique index?
45 * ReadyForInserts is it valid for inserts?
46 * Concurrent are we doing a concurrent index build?
47 * BrokenHotChain did we detect any broken HOT chains?
49 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
50 * they're conventionally set to false otherwise.
53 typedef struct IndexInfo
57 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
58 List *ii_Expressions; /* list of Expr */
59 List *ii_ExpressionsState; /* list of ExprState */
60 List *ii_Predicate; /* list of Expr */
61 List *ii_PredicateState; /* list of ExprState */
62 Oid *ii_ExclusionOps; /* array with one entry per column */
63 Oid *ii_ExclusionProcs; /* array with one entry per column */
64 uint16 *ii_ExclusionStrats; /* array with one entry per column */
66 bool ii_ReadyForInserts;
68 bool ii_BrokenHotChain;
74 * List of callbacks to be called at ExprContext shutdown.
77 typedef void (*ExprContextCallbackFunction) (Datum arg);
79 typedef struct ExprContext_CB
81 struct ExprContext_CB *next;
82 ExprContextCallbackFunction function;
89 * This class holds the "current context" information
90 * needed to evaluate expressions for doing tuple qualifications
91 * and tuple projections. For example, if an expression refers
92 * to an attribute in the current inner tuple then we need to know
93 * what the current inner tuple is and so we look at the expression
96 * There are two memory contexts associated with an ExprContext:
97 * * ecxt_per_query_memory is a query-lifespan context, typically the same
98 * context the ExprContext node itself is allocated in. This context
99 * can be used for purposes such as storing function call cache info.
100 * * ecxt_per_tuple_memory is a short-term context for expression results.
101 * As the name suggests, it will typically be reset once per tuple,
102 * before we begin to evaluate expressions for that tuple. Each
103 * ExprContext normally has its very own per-tuple memory context.
105 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
106 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
109 typedef struct ExprContext
113 /* Tuples that Var nodes in expression may refer to */
114 TupleTableSlot *ecxt_scantuple;
115 TupleTableSlot *ecxt_innertuple;
116 TupleTableSlot *ecxt_outertuple;
118 /* Memory contexts for expression evaluation --- see notes above */
119 MemoryContext ecxt_per_query_memory;
120 MemoryContext ecxt_per_tuple_memory;
122 /* Values to substitute for Param nodes in expression */
123 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
124 ParamListInfo ecxt_param_list_info; /* for other param types */
127 * Values to substitute for Aggref nodes in the expressions of an Agg
128 * node, or for WindowFunc nodes within a WindowAgg node.
130 Datum *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
131 bool *ecxt_aggnulls; /* null flags for aggs/windowfuncs */
133 /* Value to substitute for CaseTestExpr nodes in expression */
134 Datum caseValue_datum;
135 bool caseValue_isNull;
137 /* Value to substitute for CoerceToDomainValue nodes in expression */
138 Datum domainValue_datum;
139 bool domainValue_isNull;
141 /* Link to containing EState (NULL if a standalone ExprContext) */
142 struct EState *ecxt_estate;
144 /* Functions to call back when ExprContext is shut down or rescanned */
145 ExprContext_CB *ecxt_callbacks;
149 * Set-result status returned by ExecEvalExpr()
153 ExprSingleResult, /* expression does not return a set */
154 ExprMultipleResult, /* this result is an element of a set */
155 ExprEndResult /* there are no more elements in the set */
159 * Return modes for functions returning sets. Note values must be chosen
160 * as separate bits so that a bitmask can be formed to indicate supported
161 * modes. SFRM_Materialize_Random and SFRM_Materialize_Preferred are
162 * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
166 SFRM_ValuePerCall = 0x01, /* one value returned per call */
167 SFRM_Materialize = 0x02, /* result set instantiated in Tuplestore */
168 SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */
169 SFRM_Materialize_Preferred = 0x08 /* caller prefers Tuplestore */
170 } SetFunctionReturnMode;
173 * When calling a function that might return a set (multiple rows),
174 * a node of this type is passed as fcinfo->resultinfo to allow
175 * return status to be passed back. A function returning set should
176 * raise an error if no such resultinfo is provided.
178 typedef struct ReturnSetInfo
181 /* values set by caller: */
182 ExprContext *econtext; /* context function is being called in */
183 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
184 int allowedModes; /* bitmask: return modes caller can handle */
185 /* result status from function (but pre-initialized by caller): */
186 SetFunctionReturnMode returnMode; /* actual return mode */
187 ExprDoneCond isDone; /* status for ValuePerCall mode */
188 /* fields filled by function in Materialize return mode: */
189 Tuplestorestate *setResult; /* holds the complete returned tuple set */
190 TupleDesc setDesc; /* actual descriptor for returned tuples */
194 * ProjectionInfo node information
196 * This is all the information needed to perform projections ---
197 * that is, form new tuples by evaluation of targetlist expressions.
198 * Nodes which need to do projections create one of these.
200 * ExecProject() evaluates the tlist, forms a tuple, and stores it
201 * in the given slot. Note that the result will be a "virtual" tuple
202 * unless ExecMaterializeSlot() is then called to force it to be
203 * converted to a physical tuple. The slot must have a tupledesc
204 * that matches the output of the tlist!
206 * The planner very often produces tlists that consist entirely of
207 * simple Var references (lower levels of a plan tree almost always
208 * look like that). And top-level tlists are often mostly Vars too.
209 * We therefore optimize execution of simple-Var tlist entries.
210 * The pi_targetlist list actually contains only the tlist entries that
211 * aren't simple Vars, while those that are Vars are processed using the
212 * varSlotOffsets/varNumbers/varOutputCols arrays.
214 * The lastXXXVar fields are used to optimize fetching of fields from
215 * input tuples: they let us do a slot_getsomeattrs() call to ensure
216 * that all needed attributes are extracted in one pass.
218 * targetlist target list for projection (non-Var expressions only)
219 * exprContext expression context in which to evaluate targetlist
220 * slot slot to place projection result in
221 * itemIsDone workspace array for ExecProject
222 * directMap true if varOutputCols[] is an identity map
223 * numSimpleVars number of simple Vars found in original tlist
224 * varSlotOffsets array indicating which slot each simple Var is from
225 * varNumbers array containing input attr numbers of simple Vars
226 * varOutputCols array containing output attr numbers of simple Vars
227 * lastInnerVar highest attnum from inner tuple slot (0 if none)
228 * lastOuterVar highest attnum from outer tuple slot (0 if none)
229 * lastScanVar highest attnum from scan tuple slot (0 if none)
232 typedef struct ProjectionInfo
236 ExprContext *pi_exprContext;
237 TupleTableSlot *pi_slot;
238 ExprDoneCond *pi_itemIsDone;
240 int pi_numSimpleVars;
241 int *pi_varSlotOffsets;
243 int *pi_varOutputCols;
252 * This class is used to store information regarding junk attributes.
253 * A junk attribute is an attribute in a tuple that is needed only for
254 * storing intermediate information in the executor, and does not belong
255 * in emitted tuples. For example, when we do an UPDATE query,
256 * the planner adds a "junk" entry to the targetlist so that the tuples
257 * returned to ExecutePlan() contain an extra attribute: the ctid of
258 * the tuple to be updated. This is needed to do the update, but we
259 * don't want the ctid to be part of the stored new tuple! So, we
260 * apply a "junk filter" to remove the junk attributes and form the
261 * real output tuple. The junkfilter code also provides routines to
262 * extract the values of the junk attribute(s) from the input tuple.
264 * targetList: the original target list (including junk attributes).
265 * cleanTupType: the tuple descriptor for the "clean" tuple (with
266 * junk attributes removed).
267 * cleanMap: A map with the correspondence between the non-junk
268 * attribute numbers of the "original" tuple and the
269 * attribute numbers of the "clean" tuple.
270 * resultSlot: tuple slot used to hold cleaned tuple.
271 * junkAttNo: not used by junkfilter code. Can be used by caller
272 * to remember the attno of a specific junk attribute
273 * (nodeModifyTable.c keeps the "ctid" or "wholerow"
277 typedef struct JunkFilter
281 TupleDesc jf_cleanTupType;
282 AttrNumber *jf_cleanMap;
283 TupleTableSlot *jf_resultSlot;
284 AttrNumber jf_junkAttNo;
288 * ResultRelInfo information
290 * Whenever we update an existing relation, we have to
291 * update indices on the relation, and perhaps also fire triggers.
292 * The ResultRelInfo class is used to hold all the information needed
293 * about a result relation, including indices.. -cim 10/15/89
295 * RangeTableIndex result relation's range table index
296 * RelationDesc relation descriptor for result relation
297 * NumIndices # of indices existing on result relation
298 * IndexRelationDescs array of relation descriptors for indices
299 * IndexRelationInfo array of key/attr info for indices
300 * TrigDesc triggers to be fired, if any
301 * TrigFunctions cached lookup info for trigger functions
302 * TrigWhenExprs array of trigger WHEN expr states
303 * TrigInstrument optional runtime measurements for triggers
304 * FdwRoutine FDW callback functions, if foreign table
305 * FdwState available to save private state of FDW
306 * WithCheckOptions list of WithCheckOption's for views
307 * WithCheckOptionExprs list of WithCheckOption expr states
308 * ConstraintExprs array of constraint-checking expr states
309 * junkFilter for removing junk attributes from tuples
310 * projectReturning for computing a RETURNING list
313 typedef struct ResultRelInfo
316 Index ri_RangeTableIndex;
317 Relation ri_RelationDesc;
319 RelationPtr ri_IndexRelationDescs;
320 IndexInfo **ri_IndexRelationInfo;
321 TriggerDesc *ri_TrigDesc;
322 FmgrInfo *ri_TrigFunctions;
323 List **ri_TrigWhenExprs;
324 Instrumentation *ri_TrigInstrument;
325 struct FdwRoutine *ri_FdwRoutine;
327 List *ri_WithCheckOptions;
328 List *ri_WithCheckOptionExprs;
329 List **ri_ConstraintExprs;
330 JunkFilter *ri_junkFilter;
331 ProjectionInfo *ri_projectReturning;
337 * Master working state for an Executor invocation
340 typedef struct EState
344 /* Basic state for all query types: */
345 ScanDirection es_direction; /* current scan direction */
346 Snapshot es_snapshot; /* time qual to use */
347 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
348 List *es_range_table; /* List of RangeTblEntry */
349 PlannedStmt *es_plannedstmt; /* link to top of plan tree */
351 JunkFilter *es_junkFilter; /* top-level junk filter, if any */
353 /* If query can insert/delete tuples, the command ID to mark them with */
354 CommandId es_output_cid;
356 /* Info about target table(s) for insert/update/delete queries: */
357 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
358 int es_num_result_relations; /* length of array */
359 ResultRelInfo *es_result_relation_info; /* currently active array elt */
361 /* Stuff used for firing triggers: */
362 List *es_trig_target_relations; /* trigger-only ResultRelInfos */
363 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
364 TupleTableSlot *es_trig_oldtup_slot; /* for TriggerEnabled */
365 TupleTableSlot *es_trig_newtup_slot; /* for TriggerEnabled */
367 /* Parameter info: */
368 ParamListInfo es_param_list_info; /* values of external params */
369 ParamExecData *es_param_exec_vals; /* values of internal params */
371 /* Other working state: */
372 MemoryContext es_query_cxt; /* per-query context in which EState lives */
374 List *es_tupleTable; /* List of TupleTableSlots */
376 List *es_rowMarks; /* List of ExecRowMarks */
378 uint32 es_processed; /* # of tuples processed */
379 Oid es_lastoid; /* last oid processed (by INSERT) */
381 int es_top_eflags; /* eflags passed to ExecutorStart */
382 int es_instrument; /* OR of InstrumentOption flags */
383 bool es_finished; /* true when ExecutorFinish is done */
385 List *es_exprcontexts; /* List of ExprContexts within EState */
387 List *es_subplanstates; /* List of PlanState for SubPlans */
389 List *es_auxmodifytables; /* List of secondary ModifyTableStates */
392 * this ExprContext is for per-output-tuple operations, such as constraint
393 * checks and index-value computations. It will be reset for each output
394 * tuple. Note that it will be created only if needed.
396 ExprContext *es_per_tuple_exprcontext;
399 * These fields are for re-evaluating plan quals when an updated tuple is
400 * substituted in READ COMMITTED mode. es_epqTuple[] contains tuples that
401 * scan plan nodes should return instead of whatever they'd normally
402 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
403 * particular array entry is valid; and es_epqScanDone[] is state to
404 * remember if the tuple has been returned already. Arrays are of size
405 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
407 HeapTuple *es_epqTuple; /* array of EPQ substitute tuples */
408 bool *es_epqTupleSet; /* true if EPQ tuple is provided */
409 bool *es_epqScanDone; /* true if EPQ tuple has been fetched */
415 * runtime representation of FOR [KEY] UPDATE/SHARE clauses
417 * When doing UPDATE, DELETE, or SELECT FOR [KEY] UPDATE/SHARE, we should have an
418 * ExecRowMark for each non-target relation in the query (except inheritance
419 * parent RTEs, which can be ignored at runtime). See PlanRowMark for details
420 * about most of the fields. In addition to fields directly derived from
421 * PlanRowMark, we store curCtid, which is used by the WHERE CURRENT OF code.
423 * EState->es_rowMarks is a list of these structs.
425 typedef struct ExecRowMark
427 Relation relation; /* opened and suitably locked relation */
428 Index rti; /* its range table index */
429 Index prti; /* parent range table index, if child */
430 Index rowmarkId; /* unique identifier for resjunk columns */
431 RowMarkType markType; /* see enum in nodes/plannodes.h */
432 LockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
433 ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
438 * additional runtime representation of FOR [KEY] UPDATE/SHARE clauses
440 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
441 * deal with. In addition to a pointer to the related entry in es_rowMarks,
442 * this struct carries the column number(s) of the resjunk columns associated
443 * with the rowmark (see comments for PlanRowMark for more detail). In the
444 * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
445 * each child plan, because the resjunk columns could be at different physical
446 * column positions in different subplans.
448 typedef struct ExecAuxRowMark
450 ExecRowMark *rowmark; /* related entry in es_rowMarks */
451 AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
452 AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
453 AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
457 /* ----------------------------------------------------------------
460 * All-in-memory tuple hash tables are used for a number of purposes.
462 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
463 * and tab_eq_funcs are non-cross-type equality operators for those types.
464 * Normally these are the only functions used, but FindTupleHashEntry()
465 * supports searching a hashtable using cross-data-type hashing. For that,
466 * the caller must supply hash functions for the LHS datatype as well as
467 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
468 * are set to point to the caller's function arrays while doing such a search.
469 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
470 * tab_eq_funcs respectively.
471 * ----------------------------------------------------------------
473 typedef struct TupleHashEntryData *TupleHashEntry;
474 typedef struct TupleHashTableData *TupleHashTable;
476 typedef struct TupleHashEntryData
478 /* firstTuple must be the first field in this struct! */
479 MinimalTuple firstTuple; /* copy of first tuple in this group */
480 /* there may be additional data beyond the end of this struct */
481 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
483 typedef struct TupleHashTableData
485 HTAB *hashtab; /* underlying dynahash table */
486 int numCols; /* number of columns in lookup key */
487 AttrNumber *keyColIdx; /* attr numbers of key columns */
488 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
489 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
490 MemoryContext tablecxt; /* memory context containing table */
491 MemoryContext tempcxt; /* context for function evaluations */
492 Size entrysize; /* actual size to make each hash entry */
493 TupleTableSlot *tableslot; /* slot for referencing table entries */
494 /* The following fields are set transiently for each table search: */
495 TupleTableSlot *inputslot; /* current input tuple's slot */
496 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
497 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
498 } TupleHashTableData;
500 typedef HASH_SEQ_STATUS TupleHashIterator;
503 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
504 * Use ResetTupleHashIterator if the table can be frozen (in this case no
505 * explicit scan termination is needed).
507 #define InitTupleHashIterator(htable, iter) \
508 hash_seq_init(iter, (htable)->hashtab)
509 #define TermTupleHashIterator(iter) \
511 #define ResetTupleHashIterator(htable, iter) \
513 hash_freeze((htable)->hashtab); \
514 hash_seq_init(iter, (htable)->hashtab); \
516 #define ScanTupleHashTable(iter) \
517 ((TupleHashEntry) hash_seq_search(iter))
520 /* ----------------------------------------------------------------
521 * Expression State Trees
523 * Each executable expression tree has a parallel ExprState tree.
525 * Unlike PlanState, there is not an exact one-for-one correspondence between
526 * ExprState node types and Expr node types. Many Expr node types have no
527 * need for node-type-specific run-time state, and so they can use plain
528 * ExprState or GenericExprState as their associated ExprState node type.
529 * ----------------------------------------------------------------
535 * ExprState is the common superclass for all ExprState-type nodes.
537 * It can also be instantiated directly for leaf Expr nodes that need no
538 * local run-time state (such as Var, Const, or Param).
540 * To save on dispatch overhead, each ExprState node contains a function
541 * pointer to the routine to execute to evaluate the node.
545 typedef struct ExprState ExprState;
547 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
548 ExprContext *econtext,
550 ExprDoneCond *isDone);
555 Expr *expr; /* associated Expr node */
556 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
560 * GenericExprState node
562 * This is used for Expr node types that need no local run-time state,
563 * but have one child Expr node.
566 typedef struct GenericExprState
569 ExprState *arg; /* state of my child node */
573 * WholeRowVarExprState node
576 typedef struct WholeRowVarExprState
579 struct PlanState *parent; /* parent PlanState, or NULL if none */
580 TupleDesc wrv_tupdesc; /* descriptor for resulting tuples */
581 JunkFilter *wrv_junkFilter; /* JunkFilter to remove resjunk cols */
582 } WholeRowVarExprState;
585 * AggrefExprState node
588 typedef struct AggrefExprState
591 List *aggdirectargs; /* states of direct-argument expressions */
592 List *args; /* states of aggregated-argument expressions */
593 ExprState *aggfilter; /* state of FILTER expression, if any */
594 int aggno; /* ID number for agg within its plan node */
598 * WindowFuncExprState node
601 typedef struct WindowFuncExprState
604 List *args; /* states of argument expressions */
605 ExprState *aggfilter; /* FILTER expression */
606 int wfuncno; /* ID number for wfunc within its plan node */
607 } WindowFuncExprState;
610 * ArrayRefExprState node
612 * Note: array types can be fixed-length (typlen > 0), but only when the
613 * element type is itself fixed-length. Otherwise they are varlena structures
614 * and have typlen = -1. In any case, an array type is never pass-by-value.
617 typedef struct ArrayRefExprState
620 List *refupperindexpr; /* states for child nodes */
621 List *reflowerindexpr;
623 ExprState *refassgnexpr;
624 int16 refattrlength; /* typlen of array type */
625 int16 refelemlength; /* typlen of the array element type */
626 bool refelembyval; /* is the element type pass-by-value? */
627 char refelemalign; /* typalign of the element type */
633 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
634 * and NullIf nodes; be careful to check what xprstate.expr is actually
638 typedef struct FuncExprState
641 List *args; /* states of argument expressions */
644 * Function manager's lookup info for the target function. If func.fn_oid
645 * is InvalidOid, we haven't initialized it yet (nor any of the following
651 * For a set-returning function (SRF) that returns a tuplestore, we keep
652 * the tuplestore here and dole out the result rows one at a time. The
653 * slot holds the row currently being returned.
655 Tuplestorestate *funcResultStore;
656 TupleTableSlot *funcResultSlot;
659 * In some cases we need to compute a tuple descriptor for the function's
660 * output. If so, it's stored here.
662 TupleDesc funcResultDesc;
663 bool funcReturnsTuple; /* valid when funcResultDesc isn't
667 * setArgsValid is true when we are evaluating a set-returning function
668 * that uses value-per-call mode and we are in the middle of a call
669 * series; we want to pass the same argument values to the function again
670 * (and again, until it returns ExprEndResult). This indicates that
671 * fcinfo_data already contains valid argument data.
676 * Flag to remember whether we found a set-valued argument to the
677 * function. This causes the function result to be a set as well. Valid
678 * only when setArgsValid is true or funcResultStore isn't NULL.
680 bool setHasSetArg; /* some argument returns a set */
683 * Flag to remember whether we have registered a shutdown callback for
684 * this FuncExprState. We do so only if funcResultStore or setArgsValid
685 * has been set at least once (since all the callback is for is to release
686 * the tuplestore or clear setArgsValid).
688 bool shutdown_reg; /* a shutdown callback is registered */
691 * Call parameter structure for the function. This has been initialized
692 * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
693 * argument values between calls, when setArgsValid is true.
695 FunctionCallInfoData fcinfo_data;
699 * ScalarArrayOpExprState node
701 * This is a FuncExprState plus some additional data.
704 typedef struct ScalarArrayOpExprState
706 FuncExprState fxprstate;
707 /* Cached info about array element type */
712 } ScalarArrayOpExprState;
718 typedef struct BoolExprState
721 List *args; /* states of argument expression(s) */
728 typedef struct SubPlanState
731 struct PlanState *planstate; /* subselect plan's state tree */
732 struct PlanState *parent; /* parent plan node's state tree */
733 ExprState *testexpr; /* state of combining expression */
734 List *args; /* states of argument expression(s) */
735 HeapTuple curTuple; /* copy of most recent tuple from subplan */
736 Datum curArray; /* most recent array from ARRAY() subplan */
737 /* these are used when hashing the subselect's output: */
738 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
739 ProjectionInfo *projRight; /* for projecting subselect output */
740 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
741 TupleHashTable hashnulls; /* hash table for rows with null(s) */
742 bool havehashrows; /* TRUE if hashtable is not empty */
743 bool havenullrows; /* TRUE if hashnulls is not empty */
744 MemoryContext hashtablecxt; /* memory context containing hash tables */
745 MemoryContext hashtempcxt; /* temp memory context for hash tables */
746 ExprContext *innerecontext; /* econtext for computing inner tuples */
747 AttrNumber *keyColIdx; /* control data for hash tables */
748 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
749 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
750 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
751 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
755 * AlternativeSubPlanState node
758 typedef struct AlternativeSubPlanState
761 List *subplans; /* states of alternative subplans */
762 int active; /* list index of the one we're using */
763 } AlternativeSubPlanState;
766 * FieldSelectState node
769 typedef struct FieldSelectState
772 ExprState *arg; /* input expression */
773 TupleDesc argdesc; /* tupdesc for most recent input */
777 * FieldStoreState node
780 typedef struct FieldStoreState
783 ExprState *arg; /* input tuple value */
784 List *newvals; /* new value(s) for field(s) */
785 TupleDesc argdesc; /* tupdesc for most recent input */
789 * CoerceViaIOState node
792 typedef struct CoerceViaIOState
795 ExprState *arg; /* input expression */
796 FmgrInfo outfunc; /* lookup info for source output function */
797 FmgrInfo infunc; /* lookup info for result input function */
798 Oid intypioparam; /* argument needed for input function */
802 * ArrayCoerceExprState node
805 typedef struct ArrayCoerceExprState
808 ExprState *arg; /* input array value */
809 Oid resultelemtype; /* element type of result array */
810 FmgrInfo elemfunc; /* lookup info for element coercion function */
811 /* use struct pointer to avoid including array.h here */
812 struct ArrayMapState *amstate; /* workspace for array_map */
813 } ArrayCoerceExprState;
816 * ConvertRowtypeExprState node
819 typedef struct ConvertRowtypeExprState
822 ExprState *arg; /* input tuple value */
823 TupleDesc indesc; /* tupdesc for source rowtype */
824 TupleDesc outdesc; /* tupdesc for result rowtype */
825 /* use "struct" so we needn't include tupconvert.h here */
826 struct TupleConversionMap *map;
828 } ConvertRowtypeExprState;
834 typedef struct CaseExprState
837 ExprState *arg; /* implicit equality comparison argument */
838 List *args; /* the arguments (list of WHEN clauses) */
839 ExprState *defresult; /* the default result (ELSE clause) */
846 typedef struct CaseWhenState
849 ExprState *expr; /* condition expression */
850 ExprState *result; /* substitution result */
854 * ArrayExprState node
856 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
860 typedef struct ArrayExprState
863 List *elements; /* states for child nodes */
864 int16 elemlength; /* typlen of the array element type */
865 bool elembyval; /* is the element type pass-by-value? */
866 char elemalign; /* typalign of the element type */
873 typedef struct RowExprState
876 List *args; /* the arguments */
877 TupleDesc tupdesc; /* descriptor for result tuples */
881 * RowCompareExprState node
884 typedef struct RowCompareExprState
887 List *largs; /* the left-hand input arguments */
888 List *rargs; /* the right-hand input arguments */
889 FmgrInfo *funcs; /* array of comparison function info */
890 Oid *collations; /* array of collations to use */
891 } RowCompareExprState;
894 * CoalesceExprState node
897 typedef struct CoalesceExprState
900 List *args; /* the arguments */
904 * MinMaxExprState node
907 typedef struct MinMaxExprState
910 List *args; /* the arguments */
911 FmgrInfo cfunc; /* lookup info for comparison func */
918 typedef struct XmlExprState
921 List *named_args; /* ExprStates for named arguments */
922 List *args; /* ExprStates for other arguments */
929 typedef struct NullTestState
932 ExprState *arg; /* input expression */
933 /* used only if input is of composite type: */
934 TupleDesc argdesc; /* tupdesc for most recent input */
938 * CoerceToDomainState node
941 typedef struct CoerceToDomainState
944 ExprState *arg; /* input expression */
945 /* Cached list of constraints that need to be checked */
946 List *constraints; /* list of DomainConstraintState nodes */
947 } CoerceToDomainState;
950 * DomainConstraintState - one item to check during CoerceToDomain
952 * Note: this is just a Node, and not an ExprState, because it has no
953 * corresponding Expr to link to. Nonetheless it is part of an ExprState
954 * tree, so we give it a name following the xxxState convention.
956 typedef enum DomainConstraintType
958 DOM_CONSTRAINT_NOTNULL,
960 } DomainConstraintType;
962 typedef struct DomainConstraintState
965 DomainConstraintType constrainttype; /* constraint type */
966 char *name; /* name of constraint (for error msgs) */
967 ExprState *check_expr; /* for CHECK, a boolean expression */
968 } DomainConstraintState;
971 /* ----------------------------------------------------------------
972 * Executor State Trees
974 * An executing query has a PlanState tree paralleling the Plan tree
975 * that describes the plan.
976 * ----------------------------------------------------------------
982 * We never actually instantiate any PlanState nodes; this is just the common
983 * abstract superclass for all PlanState-type nodes.
986 typedef struct PlanState
990 Plan *plan; /* associated Plan node */
992 EState *state; /* at execution time, states of individual
993 * nodes point to one EState for the whole
996 Instrumentation *instrument; /* Optional runtime stats for this node */
999 * Common structural data for all Plan types. These links to subsidiary
1000 * state trees parallel links in the associated plan tree (except for the
1001 * subPlan list, which does not exist in the plan tree).
1003 List *targetlist; /* target list to be computed at this node */
1004 List *qual; /* implicitly-ANDed qual conditions */
1005 struct PlanState *lefttree; /* input plan tree(s) */
1006 struct PlanState *righttree;
1007 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
1009 List *subPlan; /* SubPlanState nodes in my expressions */
1012 * State for management of parameter-change-driven rescanning
1014 Bitmapset *chgParam; /* set of IDs of changed Params */
1017 * Other run-time state needed by most if not all node types.
1019 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
1020 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
1021 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
1022 bool ps_TupFromTlist;/* state flag for processing set-valued
1023 * functions in targetlist */
1027 * these are defined to avoid confusion problems with "left"
1028 * and "right" and "inner" and "outer". The convention is that
1029 * the "left" plan is the "outer" plan and the "right" plan is
1030 * the inner plan, but these make the code more readable.
1033 #define innerPlanState(node) (((PlanState *)(node))->righttree)
1034 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
1036 /* Macros for inline access to certain instrumentation counters */
1037 #define InstrCountFiltered1(node, delta) \
1039 if (((PlanState *)(node))->instrument) \
1040 ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
1042 #define InstrCountFiltered2(node, delta) \
1044 if (((PlanState *)(node))->instrument) \
1045 ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
1049 * EPQState is state for executing an EvalPlanQual recheck on a candidate
1050 * tuple in ModifyTable or LockRows. The estate and planstate fields are
1053 typedef struct EPQState
1055 EState *estate; /* subsidiary EState */
1056 PlanState *planstate; /* plan state tree ready to be executed */
1057 TupleTableSlot *origslot; /* original output tuple to be rechecked */
1058 Plan *plan; /* plan tree to be executed */
1059 List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
1060 int epqParam; /* ID of Param to force scan node re-eval */
1065 * ResultState information
1068 typedef struct ResultState
1070 PlanState ps; /* its first field is NodeTag */
1071 ExprState *resconstantqual;
1072 bool rs_done; /* are we done? */
1073 bool rs_checkqual; /* do we need to check the qual? */
1077 * ModifyTableState information
1080 typedef struct ModifyTableState
1082 PlanState ps; /* its first field is NodeTag */
1083 CmdType operation; /* INSERT, UPDATE, or DELETE */
1084 bool canSetTag; /* do we set the command tag/es_processed? */
1085 bool mt_done; /* are we done? */
1086 PlanState **mt_plans; /* subplans (one per target rel) */
1087 int mt_nplans; /* number of plans in the array */
1088 int mt_whichplan; /* which one is being executed (0..n-1) */
1089 ResultRelInfo *resultRelInfo; /* per-subplan target relations */
1090 List **mt_arowmarks; /* per-subplan ExecAuxRowMark lists */
1091 EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
1092 bool fireBSTriggers; /* do we need to fire stmt triggers? */
1096 * AppendState information
1098 * nplans how many plans are in the array
1099 * whichplan which plan is being executed (0 .. n-1)
1102 typedef struct AppendState
1104 PlanState ps; /* its first field is NodeTag */
1105 PlanState **appendplans; /* array of PlanStates for my inputs */
1111 * MergeAppendState information
1113 * nplans how many plans are in the array
1114 * nkeys number of sort key columns
1115 * sortkeys sort keys in SortSupport representation
1116 * slots current output tuple of each subplan
1117 * heap heap of active tuples
1118 * initialized true if we have fetched first tuple from each subplan
1121 typedef struct MergeAppendState
1123 PlanState ps; /* its first field is NodeTag */
1124 PlanState **mergeplans; /* array of PlanStates for my inputs */
1127 SortSupport ms_sortkeys; /* array of length ms_nkeys */
1128 TupleTableSlot **ms_slots; /* array of length ms_nplans */
1129 struct binaryheap *ms_heap; /* binary heap of slot indices */
1130 bool ms_initialized; /* are subplans started? */
1134 * RecursiveUnionState information
1136 * RecursiveUnionState is used for performing a recursive union.
1138 * recursing T when we're done scanning the non-recursive term
1139 * intermediate_empty T if intermediate_table is currently empty
1140 * working_table working table (to be scanned by recursive term)
1141 * intermediate_table current recursive output (next generation of WT)
1144 typedef struct RecursiveUnionState
1146 PlanState ps; /* its first field is NodeTag */
1148 bool intermediate_empty;
1149 Tuplestorestate *working_table;
1150 Tuplestorestate *intermediate_table;
1151 /* Remaining fields are unused in UNION ALL case */
1152 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1153 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1154 MemoryContext tempContext; /* short-term context for comparisons */
1155 TupleHashTable hashtable; /* hash table for tuples already seen */
1156 MemoryContext tableContext; /* memory context containing hash table */
1157 } RecursiveUnionState;
1160 * BitmapAndState information
1163 typedef struct BitmapAndState
1165 PlanState ps; /* its first field is NodeTag */
1166 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1167 int nplans; /* number of input plans */
1171 * BitmapOrState information
1174 typedef struct BitmapOrState
1176 PlanState ps; /* its first field is NodeTag */
1177 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1178 int nplans; /* number of input plans */
1181 /* ----------------------------------------------------------------
1182 * Scan State Information
1183 * ----------------------------------------------------------------
1187 * ScanState information
1189 * ScanState extends PlanState for node types that represent
1190 * scans of an underlying relation. It can also be used for nodes
1191 * that scan the output of an underlying plan node --- in that case,
1192 * only ScanTupleSlot is actually useful, and it refers to the tuple
1193 * retrieved from the subplan.
1195 * currentRelation relation being scanned (NULL if none)
1196 * currentScanDesc current scan descriptor for scan (NULL if none)
1197 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
1200 typedef struct ScanState
1202 PlanState ps; /* its first field is NodeTag */
1203 Relation ss_currentRelation;
1204 HeapScanDesc ss_currentScanDesc;
1205 TupleTableSlot *ss_ScanTupleSlot;
1209 * SeqScan uses a bare ScanState as its state node, since it needs
1210 * no additional fields.
1212 typedef ScanState SeqScanState;
1215 * These structs store information about index quals that don't have simple
1216 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1221 ScanKey scan_key; /* scankey to put value into */
1222 ExprState *key_expr; /* expr to evaluate to get value */
1223 bool key_toastable; /* is expr's result a toastable datatype? */
1224 } IndexRuntimeKeyInfo;
1228 ScanKey scan_key; /* scankey to put value into */
1229 ExprState *array_expr; /* expr to evaluate to get array value */
1230 int next_elem; /* next array element to use */
1231 int num_elems; /* number of elems in current array value */
1232 Datum *elem_values; /* array of num_elems Datums */
1233 bool *elem_nulls; /* array of num_elems is-null flags */
1234 } IndexArrayKeyInfo;
1237 * IndexScanState information
1239 * indexqualorig execution state for indexqualorig expressions
1240 * ScanKeys Skey structures for index quals
1241 * NumScanKeys number of ScanKeys
1242 * OrderByKeys Skey structures for index ordering operators
1243 * NumOrderByKeys number of OrderByKeys
1244 * RuntimeKeys info about Skeys that must be evaluated at runtime
1245 * NumRuntimeKeys number of RuntimeKeys
1246 * RuntimeKeysReady true if runtime Skeys have been computed
1247 * RuntimeContext expr context for evaling runtime Skeys
1248 * RelationDesc index relation descriptor
1249 * ScanDesc index scan descriptor
1252 typedef struct IndexScanState
1254 ScanState ss; /* its first field is NodeTag */
1255 List *indexqualorig;
1256 ScanKey iss_ScanKeys;
1257 int iss_NumScanKeys;
1258 ScanKey iss_OrderByKeys;
1259 int iss_NumOrderByKeys;
1260 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1261 int iss_NumRuntimeKeys;
1262 bool iss_RuntimeKeysReady;
1263 ExprContext *iss_RuntimeContext;
1264 Relation iss_RelationDesc;
1265 IndexScanDesc iss_ScanDesc;
1269 * IndexOnlyScanState information
1271 * indexqual execution state for indexqual expressions
1272 * ScanKeys Skey structures for index quals
1273 * NumScanKeys number of ScanKeys
1274 * OrderByKeys Skey structures for index ordering operators
1275 * NumOrderByKeys number of OrderByKeys
1276 * RuntimeKeys info about Skeys that must be evaluated at runtime
1277 * NumRuntimeKeys number of RuntimeKeys
1278 * RuntimeKeysReady true if runtime Skeys have been computed
1279 * RuntimeContext expr context for evaling runtime Skeys
1280 * RelationDesc index relation descriptor
1281 * ScanDesc index scan descriptor
1282 * VMBuffer buffer in use for visibility map testing, if any
1283 * HeapFetches number of tuples we were forced to fetch from heap
1286 typedef struct IndexOnlyScanState
1288 ScanState ss; /* its first field is NodeTag */
1290 ScanKey ioss_ScanKeys;
1291 int ioss_NumScanKeys;
1292 ScanKey ioss_OrderByKeys;
1293 int ioss_NumOrderByKeys;
1294 IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1295 int ioss_NumRuntimeKeys;
1296 bool ioss_RuntimeKeysReady;
1297 ExprContext *ioss_RuntimeContext;
1298 Relation ioss_RelationDesc;
1299 IndexScanDesc ioss_ScanDesc;
1300 Buffer ioss_VMBuffer;
1301 long ioss_HeapFetches;
1302 } IndexOnlyScanState;
1305 * BitmapIndexScanState information
1307 * result bitmap to return output into, or NULL
1308 * ScanKeys Skey structures for index quals
1309 * NumScanKeys number of ScanKeys
1310 * RuntimeKeys info about Skeys that must be evaluated at runtime
1311 * NumRuntimeKeys number of RuntimeKeys
1312 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1313 * NumArrayKeys number of ArrayKeys
1314 * RuntimeKeysReady true if runtime Skeys have been computed
1315 * RuntimeContext expr context for evaling runtime Skeys
1316 * RelationDesc index relation descriptor
1317 * ScanDesc index scan descriptor
1320 typedef struct BitmapIndexScanState
1322 ScanState ss; /* its first field is NodeTag */
1323 TIDBitmap *biss_result;
1324 ScanKey biss_ScanKeys;
1325 int biss_NumScanKeys;
1326 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1327 int biss_NumRuntimeKeys;
1328 IndexArrayKeyInfo *biss_ArrayKeys;
1329 int biss_NumArrayKeys;
1330 bool biss_RuntimeKeysReady;
1331 ExprContext *biss_RuntimeContext;
1332 Relation biss_RelationDesc;
1333 IndexScanDesc biss_ScanDesc;
1334 } BitmapIndexScanState;
1337 * BitmapHeapScanState information
1339 * bitmapqualorig execution state for bitmapqualorig expressions
1340 * tbm bitmap obtained from child index scan(s)
1341 * tbmiterator iterator for scanning current pages
1342 * tbmres current-page data
1343 * exact_pages total number of exact pages retrieved
1344 * lossy_pages total number of lossy pages retrieved
1345 * prefetch_iterator iterator for prefetching ahead of current page
1346 * prefetch_pages # pages prefetch iterator is ahead of current
1347 * prefetch_target target prefetch distance
1350 typedef struct BitmapHeapScanState
1352 ScanState ss; /* its first field is NodeTag */
1353 List *bitmapqualorig;
1355 TBMIterator *tbmiterator;
1356 TBMIterateResult *tbmres;
1359 TBMIterator *prefetch_iterator;
1361 int prefetch_target;
1362 } BitmapHeapScanState;
1365 * TidScanState information
1367 * isCurrentOf scan has a CurrentOfExpr qual
1368 * NumTids number of tids in this scan
1369 * TidPtr index of currently fetched tid
1370 * TidList evaluated item pointers (array of size NumTids)
1373 typedef struct TidScanState
1375 ScanState ss; /* its first field is NodeTag */
1376 List *tss_tidquals; /* list of ExprState nodes */
1377 bool tss_isCurrentOf;
1380 ItemPointerData *tss_TidList;
1381 HeapTupleData tss_htup;
1385 * SubqueryScanState information
1387 * SubqueryScanState is used for scanning a sub-query in the range table.
1388 * ScanTupleSlot references the current output tuple of the sub-query.
1391 typedef struct SubqueryScanState
1393 ScanState ss; /* its first field is NodeTag */
1395 } SubqueryScanState;
1398 * FunctionScanState information
1400 * Function nodes are used to scan the results of a
1401 * function appearing in FROM (typically a function returning set).
1403 * eflags node's capability flags
1404 * ordinality is this scan WITH ORDINALITY?
1405 * simple true if we have 1 function and no ordinality
1406 * ordinal current ordinal column value
1407 * nfuncs number of functions being executed
1408 * funcstates per-function execution states (private in
1409 * nodeFunctionscan.c)
1410 * argcontext memory context to evaluate function arguments in
1413 struct FunctionScanPerFuncState;
1415 typedef struct FunctionScanState
1417 ScanState ss; /* its first field is NodeTag */
1423 struct FunctionScanPerFuncState *funcstates; /* array of length
1425 MemoryContext argcontext;
1426 } FunctionScanState;
1429 * ValuesScanState information
1431 * ValuesScan nodes are used to scan the results of a VALUES list
1433 * rowcontext per-expression-list context
1434 * exprlists array of expression lists being evaluated
1435 * array_len size of array
1436 * curr_idx current array index (0-based)
1438 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1439 * expressions attached to the node. We create a second ExprContext,
1440 * rowcontext, in which to build the executor expression state for each
1441 * Values sublist. Resetting this context lets us get rid of expression
1442 * state for each row, avoiding major memory leakage over a long values list.
1445 typedef struct ValuesScanState
1447 ScanState ss; /* its first field is NodeTag */
1448 ExprContext *rowcontext;
1455 * CteScanState information
1457 * CteScan nodes are used to scan a CommonTableExpr query.
1459 * Multiple CteScan nodes can read out from the same CTE query. We use
1460 * a tuplestore to hold rows that have been read from the CTE query but
1461 * not yet consumed by all readers.
1464 typedef struct CteScanState
1466 ScanState ss; /* its first field is NodeTag */
1467 int eflags; /* capability flags to pass to tuplestore */
1468 int readptr; /* index of my tuplestore read pointer */
1469 PlanState *cteplanstate; /* PlanState for the CTE query itself */
1470 /* Link to the "leader" CteScanState (possibly this same node) */
1471 struct CteScanState *leader;
1472 /* The remaining fields are only valid in the "leader" CteScanState */
1473 Tuplestorestate *cte_table; /* rows already read from the CTE query */
1474 bool eof_cte; /* reached end of CTE query? */
1478 * WorkTableScanState information
1480 * WorkTableScan nodes are used to scan the work table created by
1481 * a RecursiveUnion node. We locate the RecursiveUnion node
1482 * during executor startup.
1485 typedef struct WorkTableScanState
1487 ScanState ss; /* its first field is NodeTag */
1488 RecursiveUnionState *rustate;
1489 } WorkTableScanState;
1492 * ForeignScanState information
1494 * ForeignScan nodes are used to scan foreign-data tables.
1497 typedef struct ForeignScanState
1499 ScanState ss; /* its first field is NodeTag */
1500 /* use struct pointer to avoid including fdwapi.h here */
1501 struct FdwRoutine *fdwroutine;
1502 void *fdw_state; /* foreign-data wrapper can keep state here */
1506 * CustomScanState information
1508 * CustomScan nodes are used to execute custom code within executor.
1511 struct ExplainState; /* avoid including explain.h here */
1512 struct CustomScanState;
1514 typedef struct CustomExecMethods
1516 const char *CustomName;
1518 /* EXECUTOR methods */
1519 void (*BeginCustomScan) (struct CustomScanState *node,
1522 TupleTableSlot *(*ExecCustomScan) (struct CustomScanState *node);
1523 void (*EndCustomScan) (struct CustomScanState *node);
1524 void (*ReScanCustomScan) (struct CustomScanState *node);
1525 void (*MarkPosCustomScan) (struct CustomScanState *node);
1526 void (*RestrPosCustomScan) (struct CustomScanState *node);
1528 /* EXPLAIN support */
1529 void (*ExplainCustomScan) (struct CustomScanState *node,
1531 struct ExplainState *es);
1532 Node *(*GetSpecialCustomVar) (struct CustomScanState *node,
1534 PlanState **child_ps);
1535 } CustomExecMethods;
1537 typedef struct CustomScanState
1540 uint32 flags; /* mask of CUSTOMPATH_* flags, see relation.h */
1541 const CustomExecMethods *methods;
1544 /* ----------------------------------------------------------------
1545 * Join State Information
1546 * ----------------------------------------------------------------
1550 * JoinState information
1552 * Superclass for state nodes of join plans.
1555 typedef struct JoinState
1559 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1563 * NestLoopState information
1565 * NeedNewOuter true if need new outer tuple on next call
1566 * MatchedOuter true if found a join match for current outer tuple
1567 * NullInnerTupleSlot prepared null tuple for left outer joins
1570 typedef struct NestLoopState
1572 JoinState js; /* its first field is NodeTag */
1573 bool nl_NeedNewOuter;
1574 bool nl_MatchedOuter;
1575 TupleTableSlot *nl_NullInnerTupleSlot;
1579 * MergeJoinState information
1581 * NumClauses number of mergejoinable join clauses
1582 * Clauses info for each mergejoinable clause
1583 * JoinState current state of ExecMergeJoin state machine
1584 * ExtraMarks true to issue extra Mark operations on inner scan
1585 * ConstFalseJoin true if we have a constant-false joinqual
1586 * FillOuter true if should emit unjoined outer tuples anyway
1587 * FillInner true if should emit unjoined inner tuples anyway
1588 * MatchedOuter true if found a join match for current outer tuple
1589 * MatchedInner true if found a join match for current inner tuple
1590 * OuterTupleSlot slot in tuple table for cur outer tuple
1591 * InnerTupleSlot slot in tuple table for cur inner tuple
1592 * MarkedTupleSlot slot in tuple table for marked tuple
1593 * NullOuterTupleSlot prepared null tuple for right outer joins
1594 * NullInnerTupleSlot prepared null tuple for left outer joins
1595 * OuterEContext workspace for computing outer tuple's join values
1596 * InnerEContext workspace for computing inner tuple's join values
1599 /* private in nodeMergejoin.c: */
1600 typedef struct MergeJoinClauseData *MergeJoinClause;
1602 typedef struct MergeJoinState
1604 JoinState js; /* its first field is NodeTag */
1606 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1609 bool mj_ConstFalseJoin;
1612 bool mj_MatchedOuter;
1613 bool mj_MatchedInner;
1614 TupleTableSlot *mj_OuterTupleSlot;
1615 TupleTableSlot *mj_InnerTupleSlot;
1616 TupleTableSlot *mj_MarkedTupleSlot;
1617 TupleTableSlot *mj_NullOuterTupleSlot;
1618 TupleTableSlot *mj_NullInnerTupleSlot;
1619 ExprContext *mj_OuterEContext;
1620 ExprContext *mj_InnerEContext;
1624 * HashJoinState information
1626 * hashclauses original form of the hashjoin condition
1627 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1628 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1629 * hj_HashOperators the join operators in the hashjoin condition
1630 * hj_HashTable hash table for the hashjoin
1631 * (NULL if table not built yet)
1632 * hj_CurHashValue hash value for current outer tuple
1633 * hj_CurBucketNo regular bucket# for current outer tuple
1634 * hj_CurSkewBucketNo skew bucket# for current outer tuple
1635 * hj_CurTuple last inner tuple matched to current outer
1636 * tuple, or NULL if starting search
1637 * (hj_CurXXX variables are undefined if
1638 * OuterTupleSlot is empty!)
1639 * hj_OuterTupleSlot tuple slot for outer tuples
1640 * hj_HashTupleSlot tuple slot for inner (hashed) tuples
1641 * hj_NullOuterTupleSlot prepared null tuple for right/full outer joins
1642 * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
1643 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1644 * hj_JoinState current state of ExecHashJoin state machine
1645 * hj_MatchedOuter true if found a join match for current outer
1646 * hj_OuterNotEmpty true if outer relation known not empty
1650 /* these structs are defined in executor/hashjoin.h: */
1651 typedef struct HashJoinTupleData *HashJoinTuple;
1652 typedef struct HashJoinTableData *HashJoinTable;
1654 typedef struct HashJoinState
1656 JoinState js; /* its first field is NodeTag */
1657 List *hashclauses; /* list of ExprState nodes */
1658 List *hj_OuterHashKeys; /* list of ExprState nodes */
1659 List *hj_InnerHashKeys; /* list of ExprState nodes */
1660 List *hj_HashOperators; /* list of operator OIDs */
1661 HashJoinTable hj_HashTable;
1662 uint32 hj_CurHashValue;
1664 int hj_CurSkewBucketNo;
1665 HashJoinTuple hj_CurTuple;
1666 TupleTableSlot *hj_OuterTupleSlot;
1667 TupleTableSlot *hj_HashTupleSlot;
1668 TupleTableSlot *hj_NullOuterTupleSlot;
1669 TupleTableSlot *hj_NullInnerTupleSlot;
1670 TupleTableSlot *hj_FirstOuterTupleSlot;
1672 bool hj_MatchedOuter;
1673 bool hj_OuterNotEmpty;
1677 /* ----------------------------------------------------------------
1678 * Materialization State Information
1679 * ----------------------------------------------------------------
1683 * MaterialState information
1685 * materialize nodes are used to materialize the results
1686 * of a subplan into a temporary file.
1688 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1691 typedef struct MaterialState
1693 ScanState ss; /* its first field is NodeTag */
1694 int eflags; /* capability flags to pass to tuplestore */
1695 bool eof_underlying; /* reached end of underlying plan? */
1696 Tuplestorestate *tuplestorestate;
1700 * SortState information
1703 typedef struct SortState
1705 ScanState ss; /* its first field is NodeTag */
1706 bool randomAccess; /* need random access to sort output? */
1707 bool bounded; /* is the result set bounded? */
1708 int64 bound; /* if bounded, how many tuples are needed */
1709 bool sort_Done; /* sort completed yet? */
1710 bool bounded_Done; /* value of bounded we did the sort with */
1711 int64 bound_Done; /* value of bound we did the sort with */
1712 void *tuplesortstate; /* private state of tuplesort.c */
1715 /* ---------------------
1716 * GroupState information
1717 * -------------------------
1719 typedef struct GroupState
1721 ScanState ss; /* its first field is NodeTag */
1722 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1723 bool grp_done; /* indicates completion of Group scan */
1726 /* ---------------------
1727 * AggState information
1729 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1731 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1732 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1733 * input group during evaluation of an Agg node's output tuple(s). We
1734 * create a second ExprContext, tmpcontext, in which to evaluate input
1735 * expressions and run the aggregate transition functions.
1736 * -------------------------
1738 /* these structs are private in nodeAgg.c: */
1739 typedef struct AggStatePerAggData *AggStatePerAgg;
1740 typedef struct AggStatePerGroupData *AggStatePerGroup;
1742 typedef struct AggState
1744 ScanState ss; /* its first field is NodeTag */
1745 List *aggs; /* all Aggref nodes in targetlist & quals */
1746 int numaggs; /* length of list (could be zero!) */
1747 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1748 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1749 AggStatePerAgg peragg; /* per-Aggref information */
1750 MemoryContext aggcontext; /* memory context for long-lived data */
1751 ExprContext *tmpcontext; /* econtext for input expressions */
1752 AggStatePerAgg curperagg; /* identifies currently active aggregate */
1753 bool agg_done; /* indicates completion of Agg scan */
1754 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1755 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1756 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1757 /* these fields are used in AGG_HASHED mode: */
1758 TupleHashTable hashtable; /* hash table with one entry per group */
1759 TupleTableSlot *hashslot; /* slot for loading hash table */
1760 List *hash_needed; /* list of columns needed in hash table */
1761 bool table_filled; /* hash table filled yet? */
1762 TupleHashIterator hashiter; /* for iterating through hash table */
1766 * WindowAggState information
1769 /* these structs are private in nodeWindowAgg.c: */
1770 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1771 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1773 typedef struct WindowAggState
1775 ScanState ss; /* its first field is NodeTag */
1777 /* these fields are filled in by ExecInitExpr: */
1778 List *funcs; /* all WindowFunc nodes in targetlist */
1779 int numfuncs; /* total number of window functions */
1780 int numaggs; /* number that are plain aggregates */
1782 WindowStatePerFunc perfunc; /* per-window-function information */
1783 WindowStatePerAgg peragg; /* per-plain-aggregate information */
1784 FmgrInfo *partEqfunctions; /* equality funcs for partition columns */
1785 FmgrInfo *ordEqfunctions; /* equality funcs for ordering columns */
1786 Tuplestorestate *buffer; /* stores rows of current partition */
1787 int current_ptr; /* read pointer # for current */
1788 int64 spooled_rows; /* total # of rows in buffer */
1789 int64 currentpos; /* position of current row in partition */
1790 int64 frameheadpos; /* current frame head position */
1791 int64 frametailpos; /* current frame tail position */
1792 /* use struct pointer to avoid including windowapi.h here */
1793 struct WindowObjectData *agg_winobj; /* winobj for aggregate
1795 int64 aggregatedbase; /* start row for current aggregates */
1796 int64 aggregatedupto; /* rows before this one are aggregated */
1798 int frameOptions; /* frame_clause options, see WindowDef */
1799 ExprState *startOffset; /* expression for starting bound offset */
1800 ExprState *endOffset; /* expression for ending bound offset */
1801 Datum startOffsetValue; /* result of startOffset evaluation */
1802 Datum endOffsetValue; /* result of endOffset evaluation */
1804 MemoryContext partcontext; /* context for partition-lifespan data */
1805 MemoryContext aggcontext; /* shared context for aggregate working data */
1806 MemoryContext curaggcontext; /* current aggregate's working data */
1807 ExprContext *tmpcontext; /* short-term evaluation context */
1809 bool all_first; /* true if the scan is starting */
1810 bool all_done; /* true if the scan is finished */
1811 bool partition_spooled; /* true if all tuples in current
1812 * partition have been spooled into
1814 bool more_partitions;/* true if there's more partitions after this
1816 bool framehead_valid;/* true if frameheadpos is known up to date
1817 * for current row */
1818 bool frametail_valid;/* true if frametailpos is known up to date
1819 * for current row */
1821 TupleTableSlot *first_part_slot; /* first tuple of current or next
1824 /* temporary slots for tuples fetched back from tuplestore */
1825 TupleTableSlot *agg_row_slot;
1826 TupleTableSlot *temp_slot_1;
1827 TupleTableSlot *temp_slot_2;
1831 * UniqueState information
1833 * Unique nodes are used "on top of" sort nodes to discard
1834 * duplicate tuples returned from the sort phase. Basically
1835 * all it does is compare the current tuple from the subplan
1836 * with the previously fetched tuple (stored in its result slot).
1837 * If the two are identical in all interesting fields, then
1838 * we just fetch another tuple from the sort and try again.
1841 typedef struct UniqueState
1843 PlanState ps; /* its first field is NodeTag */
1844 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1845 MemoryContext tempContext; /* short-term context for comparisons */
1849 * HashState information
1852 typedef struct HashState
1854 PlanState ps; /* its first field is NodeTag */
1855 HashJoinTable hashtable; /* hash table for the hashjoin */
1856 List *hashkeys; /* list of ExprState nodes */
1857 /* hashkeys is same as parent's hj_InnerHashKeys */
1861 * SetOpState information
1863 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1864 * Unique, since we have to count how many duplicates to return. But
1865 * we also support hashing, so this is really more like a cut-down
1869 /* this struct is private in nodeSetOp.c: */
1870 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1872 typedef struct SetOpState
1874 PlanState ps; /* its first field is NodeTag */
1875 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1876 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1877 bool setop_done; /* indicates completion of output scan */
1878 long numOutput; /* number of dups left to output */
1879 MemoryContext tempContext; /* short-term context for comparisons */
1880 /* these fields are used in SETOP_SORTED mode: */
1881 SetOpStatePerGroup pergroup; /* per-group working state */
1882 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1883 /* these fields are used in SETOP_HASHED mode: */
1884 TupleHashTable hashtable; /* hash table with one entry per group */
1885 MemoryContext tableContext; /* memory context containing hash table */
1886 bool table_filled; /* hash table filled yet? */
1887 TupleHashIterator hashiter; /* for iterating through hash table */
1891 * LockRowsState information
1893 * LockRows nodes are used to enforce FOR [KEY] UPDATE/SHARE locking.
1896 typedef struct LockRowsState
1898 PlanState ps; /* its first field is NodeTag */
1899 List *lr_arowMarks; /* List of ExecAuxRowMarks */
1900 EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
1904 * LimitState information
1906 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1907 * They just select the desired subrange of their subplan's output.
1909 * offset is the number of initial tuples to skip (0 does nothing).
1910 * count is the number of tuples to return after skipping the offset tuples.
1911 * If no limit count was specified, count is undefined and noCount is true.
1912 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1917 LIMIT_INITIAL, /* initial state for LIMIT node */
1918 LIMIT_RESCAN, /* rescan after recomputing parameters */
1919 LIMIT_EMPTY, /* there are no returnable rows */
1920 LIMIT_INWINDOW, /* have returned a row in the window */
1921 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1922 LIMIT_WINDOWEND, /* stepped off end of window */
1923 LIMIT_WINDOWSTART /* stepped off beginning of window */
1926 typedef struct LimitState
1928 PlanState ps; /* its first field is NodeTag */
1929 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1930 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1931 int64 offset; /* current OFFSET value */
1932 int64 count; /* current COUNT, if any */
1933 bool noCount; /* if true, ignore count */
1934 LimitStateCond lstate; /* state machine status, as above */
1935 int64 position; /* 1-based index of last tuple returned */
1936 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1939 #endif /* EXECNODES_H */