1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2016, 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 "lib/pairingheap.h"
21 #include "nodes/params.h"
22 #include "nodes/plannodes.h"
23 #include "utils/reltrigger.h"
24 #include "utils/sortsupport.h"
25 #include "utils/tuplestore.h"
26 #include "utils/tuplesort.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 * ExclusionOps Per-column exclusion operators, or NULL if none
44 * ExclusionProcs Underlying function OIDs for ExclusionOps
45 * ExclusionStrats Opclass strategy numbers for ExclusionOps
46 * UniqueOps Theses are like Exclusion*, but for unique indexes
49 * Unique is it a unique index?
50 * ReadyForInserts is it valid for inserts?
51 * Concurrent are we doing a concurrent index build?
52 * BrokenHotChain did we detect any broken HOT chains?
54 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
55 * they're conventionally set to false otherwise.
58 typedef struct IndexInfo
62 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
63 List *ii_Expressions; /* list of Expr */
64 List *ii_ExpressionsState; /* list of ExprState */
65 List *ii_Predicate; /* list of Expr */
66 List *ii_PredicateState; /* list of ExprState */
67 Oid *ii_ExclusionOps; /* array with one entry per column */
68 Oid *ii_ExclusionProcs; /* array with one entry per column */
69 uint16 *ii_ExclusionStrats; /* array with one entry per column */
70 Oid *ii_UniqueOps; /* array with one entry per column */
71 Oid *ii_UniqueProcs; /* array with one entry per column */
72 uint16 *ii_UniqueStrats; /* array with one entry per column */
74 bool ii_ReadyForInserts;
76 bool ii_BrokenHotChain;
82 * List of callbacks to be called at ExprContext shutdown.
85 typedef void (*ExprContextCallbackFunction) (Datum arg);
87 typedef struct ExprContext_CB
89 struct ExprContext_CB *next;
90 ExprContextCallbackFunction function;
97 * This class holds the "current context" information
98 * needed to evaluate expressions for doing tuple qualifications
99 * and tuple projections. For example, if an expression refers
100 * to an attribute in the current inner tuple then we need to know
101 * what the current inner tuple is and so we look at the expression
104 * There are two memory contexts associated with an ExprContext:
105 * * ecxt_per_query_memory is a query-lifespan context, typically the same
106 * context the ExprContext node itself is allocated in. This context
107 * can be used for purposes such as storing function call cache info.
108 * * ecxt_per_tuple_memory is a short-term context for expression results.
109 * As the name suggests, it will typically be reset once per tuple,
110 * before we begin to evaluate expressions for that tuple. Each
111 * ExprContext normally has its very own per-tuple memory context.
113 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
114 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
117 typedef struct ExprContext
121 /* Tuples that Var nodes in expression may refer to */
122 TupleTableSlot *ecxt_scantuple;
123 TupleTableSlot *ecxt_innertuple;
124 TupleTableSlot *ecxt_outertuple;
126 /* Memory contexts for expression evaluation --- see notes above */
127 MemoryContext ecxt_per_query_memory;
128 MemoryContext ecxt_per_tuple_memory;
130 /* Values to substitute for Param nodes in expression */
131 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
132 ParamListInfo ecxt_param_list_info; /* for other param types */
135 * Values to substitute for Aggref nodes in the expressions of an Agg
136 * node, or for WindowFunc nodes within a WindowAgg node.
138 Datum *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
139 bool *ecxt_aggnulls; /* null flags for aggs/windowfuncs */
141 /* Value to substitute for CaseTestExpr nodes in expression */
142 Datum caseValue_datum;
143 bool caseValue_isNull;
145 /* Value to substitute for CoerceToDomainValue nodes in expression */
146 Datum domainValue_datum;
147 bool domainValue_isNull;
149 /* Link to containing EState (NULL if a standalone ExprContext) */
150 struct EState *ecxt_estate;
152 /* Functions to call back when ExprContext is shut down or rescanned */
153 ExprContext_CB *ecxt_callbacks;
157 * Set-result status returned by ExecEvalExpr()
161 ExprSingleResult, /* expression does not return a set */
162 ExprMultipleResult, /* this result is an element of a set */
163 ExprEndResult /* there are no more elements in the set */
167 * Return modes for functions returning sets. Note values must be chosen
168 * as separate bits so that a bitmask can be formed to indicate supported
169 * modes. SFRM_Materialize_Random and SFRM_Materialize_Preferred are
170 * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
174 SFRM_ValuePerCall = 0x01, /* one value returned per call */
175 SFRM_Materialize = 0x02, /* result set instantiated in Tuplestore */
176 SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */
177 SFRM_Materialize_Preferred = 0x08 /* caller prefers Tuplestore */
178 } SetFunctionReturnMode;
181 * When calling a function that might return a set (multiple rows),
182 * a node of this type is passed as fcinfo->resultinfo to allow
183 * return status to be passed back. A function returning set should
184 * raise an error if no such resultinfo is provided.
186 typedef struct ReturnSetInfo
189 /* values set by caller: */
190 ExprContext *econtext; /* context function is being called in */
191 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
192 int allowedModes; /* bitmask: return modes caller can handle */
193 /* result status from function (but pre-initialized by caller): */
194 SetFunctionReturnMode returnMode; /* actual return mode */
195 ExprDoneCond isDone; /* status for ValuePerCall mode */
196 /* fields filled by function in Materialize return mode: */
197 Tuplestorestate *setResult; /* holds the complete returned tuple set */
198 TupleDesc setDesc; /* actual descriptor for returned tuples */
202 * ProjectionInfo node information
204 * This is all the information needed to perform projections ---
205 * that is, form new tuples by evaluation of targetlist expressions.
206 * Nodes which need to do projections create one of these.
208 * ExecProject() evaluates the tlist, forms a tuple, and stores it
209 * in the given slot. Note that the result will be a "virtual" tuple
210 * unless ExecMaterializeSlot() is then called to force it to be
211 * converted to a physical tuple. The slot must have a tupledesc
212 * that matches the output of the tlist!
214 * The planner very often produces tlists that consist entirely of
215 * simple Var references (lower levels of a plan tree almost always
216 * look like that). And top-level tlists are often mostly Vars too.
217 * We therefore optimize execution of simple-Var tlist entries.
218 * The pi_targetlist list actually contains only the tlist entries that
219 * aren't simple Vars, while those that are Vars are processed using the
220 * varSlotOffsets/varNumbers/varOutputCols arrays.
222 * The lastXXXVar fields are used to optimize fetching of fields from
223 * input tuples: they let us do a slot_getsomeattrs() call to ensure
224 * that all needed attributes are extracted in one pass.
226 * targetlist target list for projection (non-Var expressions only)
227 * exprContext expression context in which to evaluate targetlist
228 * slot slot to place projection result in
229 * itemIsDone workspace array for ExecProject
230 * directMap true if varOutputCols[] is an identity map
231 * numSimpleVars number of simple Vars found in original tlist
232 * varSlotOffsets array indicating which slot each simple Var is from
233 * varNumbers array containing input attr numbers of simple Vars
234 * varOutputCols array containing output attr numbers of simple Vars
235 * lastInnerVar highest attnum from inner tuple slot (0 if none)
236 * lastOuterVar highest attnum from outer tuple slot (0 if none)
237 * lastScanVar highest attnum from scan tuple slot (0 if none)
240 typedef struct ProjectionInfo
244 ExprContext *pi_exprContext;
245 TupleTableSlot *pi_slot;
246 ExprDoneCond *pi_itemIsDone;
248 int pi_numSimpleVars;
249 int *pi_varSlotOffsets;
251 int *pi_varOutputCols;
260 * This class is used to store information regarding junk attributes.
261 * A junk attribute is an attribute in a tuple that is needed only for
262 * storing intermediate information in the executor, and does not belong
263 * in emitted tuples. For example, when we do an UPDATE query,
264 * the planner adds a "junk" entry to the targetlist so that the tuples
265 * returned to ExecutePlan() contain an extra attribute: the ctid of
266 * the tuple to be updated. This is needed to do the update, but we
267 * don't want the ctid to be part of the stored new tuple! So, we
268 * apply a "junk filter" to remove the junk attributes and form the
269 * real output tuple. The junkfilter code also provides routines to
270 * extract the values of the junk attribute(s) from the input tuple.
272 * targetList: the original target list (including junk attributes).
273 * cleanTupType: the tuple descriptor for the "clean" tuple (with
274 * junk attributes removed).
275 * cleanMap: A map with the correspondence between the non-junk
276 * attribute numbers of the "original" tuple and the
277 * attribute numbers of the "clean" tuple.
278 * resultSlot: tuple slot used to hold cleaned tuple.
279 * junkAttNo: not used by junkfilter code. Can be used by caller
280 * to remember the attno of a specific junk attribute
281 * (nodeModifyTable.c keeps the "ctid" or "wholerow"
285 typedef struct JunkFilter
289 TupleDesc jf_cleanTupType;
290 AttrNumber *jf_cleanMap;
291 TupleTableSlot *jf_resultSlot;
292 AttrNumber jf_junkAttNo;
296 * ResultRelInfo information
298 * Whenever we update an existing relation, we have to
299 * update indices on the relation, and perhaps also fire triggers.
300 * The ResultRelInfo class is used to hold all the information needed
301 * about a result relation, including indices.. -cim 10/15/89
303 * RangeTableIndex result relation's range table index
304 * RelationDesc relation descriptor for result relation
305 * NumIndices # of indices existing on result relation
306 * IndexRelationDescs array of relation descriptors for indices
307 * IndexRelationInfo array of key/attr info for indices
308 * TrigDesc triggers to be fired, if any
309 * TrigFunctions cached lookup info for trigger functions
310 * TrigWhenExprs array of trigger WHEN expr states
311 * TrigInstrument optional runtime measurements for triggers
312 * FdwRoutine FDW callback functions, if foreign table
313 * FdwState available to save private state of FDW
314 * usesFdwDirectModify true when modifying foreign table directly
315 * WithCheckOptions list of WithCheckOption's to be checked
316 * WithCheckOptionExprs list of WithCheckOption expr states
317 * ConstraintExprs array of constraint-checking expr states
318 * junkFilter for removing junk attributes from tuples
319 * projectReturning for computing a RETURNING list
320 * onConflictSetProj for computing ON CONFLICT DO UPDATE SET
321 * onConflictSetWhere list of ON CONFLICT DO UPDATE exprs (qual)
324 typedef struct ResultRelInfo
327 Index ri_RangeTableIndex;
328 Relation ri_RelationDesc;
330 RelationPtr ri_IndexRelationDescs;
331 IndexInfo **ri_IndexRelationInfo;
332 TriggerDesc *ri_TrigDesc;
333 FmgrInfo *ri_TrigFunctions;
334 List **ri_TrigWhenExprs;
335 Instrumentation *ri_TrigInstrument;
336 struct FdwRoutine *ri_FdwRoutine;
338 bool ri_usesFdwDirectModify;
339 List *ri_WithCheckOptions;
340 List *ri_WithCheckOptionExprs;
341 List **ri_ConstraintExprs;
342 JunkFilter *ri_junkFilter;
343 ProjectionInfo *ri_projectReturning;
344 ProjectionInfo *ri_onConflictSetProj;
345 List *ri_onConflictSetWhere;
351 * Master working state for an Executor invocation
354 typedef struct EState
358 /* Basic state for all query types: */
359 ScanDirection es_direction; /* current scan direction */
360 Snapshot es_snapshot; /* time qual to use */
361 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
362 List *es_range_table; /* List of RangeTblEntry */
363 PlannedStmt *es_plannedstmt; /* link to top of plan tree */
365 JunkFilter *es_junkFilter; /* top-level junk filter, if any */
367 /* If query can insert/delete tuples, the command ID to mark them with */
368 CommandId es_output_cid;
370 /* Info about target table(s) for insert/update/delete queries: */
371 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
372 int es_num_result_relations; /* length of array */
373 ResultRelInfo *es_result_relation_info; /* currently active array elt */
375 /* Stuff used for firing triggers: */
376 List *es_trig_target_relations; /* trigger-only ResultRelInfos */
377 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
378 TupleTableSlot *es_trig_oldtup_slot; /* for TriggerEnabled */
379 TupleTableSlot *es_trig_newtup_slot; /* for TriggerEnabled */
381 /* Parameter info: */
382 ParamListInfo es_param_list_info; /* values of external params */
383 ParamExecData *es_param_exec_vals; /* values of internal params */
385 /* Other working state: */
386 MemoryContext es_query_cxt; /* per-query context in which EState lives */
388 List *es_tupleTable; /* List of TupleTableSlots */
390 List *es_rowMarks; /* List of ExecRowMarks */
392 uint64 es_processed; /* # of tuples processed */
393 Oid es_lastoid; /* last oid processed (by INSERT) */
395 int es_top_eflags; /* eflags passed to ExecutorStart */
396 int es_instrument; /* OR of InstrumentOption flags */
397 bool es_finished; /* true when ExecutorFinish is done */
399 List *es_exprcontexts; /* List of ExprContexts within EState */
401 List *es_subplanstates; /* List of PlanState for SubPlans */
403 List *es_auxmodifytables; /* List of secondary ModifyTableStates */
406 * this ExprContext is for per-output-tuple operations, such as constraint
407 * checks and index-value computations. It will be reset for each output
408 * tuple. Note that it will be created only if needed.
410 ExprContext *es_per_tuple_exprcontext;
413 * These fields are for re-evaluating plan quals when an updated tuple is
414 * substituted in READ COMMITTED mode. es_epqTuple[] contains tuples that
415 * scan plan nodes should return instead of whatever they'd normally
416 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
417 * particular array entry is valid; and es_epqScanDone[] is state to
418 * remember if the tuple has been returned already. Arrays are of size
419 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
421 HeapTuple *es_epqTuple; /* array of EPQ substitute tuples */
422 bool *es_epqTupleSet; /* true if EPQ tuple is provided */
423 bool *es_epqScanDone; /* true if EPQ tuple has been fetched */
429 * runtime representation of FOR [KEY] UPDATE/SHARE clauses
431 * When doing UPDATE, DELETE, or SELECT FOR [KEY] UPDATE/SHARE, we will have an
432 * ExecRowMark for each non-target relation in the query (except inheritance
433 * parent RTEs, which can be ignored at runtime). Virtual relations such as
434 * subqueries-in-FROM will have an ExecRowMark with relation == NULL. See
435 * PlanRowMark for details about most of the fields. In addition to fields
436 * directly derived from PlanRowMark, we store an activity flag (to denote
437 * inactive children of inheritance trees), curCtid, which is used by the
438 * WHERE CURRENT OF code, and ermExtra, which is available for use by the plan
439 * node that sources the relation (e.g., for a foreign table the FDW can use
440 * ermExtra to hold information).
442 * EState->es_rowMarks is a list of these structs.
444 typedef struct ExecRowMark
446 Relation relation; /* opened and suitably locked relation */
447 Oid relid; /* its OID (or InvalidOid, if subquery) */
448 Index rti; /* its range table index */
449 Index prti; /* parent range table index, if child */
450 Index rowmarkId; /* unique identifier for resjunk columns */
451 RowMarkType markType; /* see enum in nodes/plannodes.h */
452 LockClauseStrength strength; /* LockingClause's strength, or LCS_NONE */
453 LockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
454 bool ermActive; /* is this mark relevant for current tuple? */
455 ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
456 void *ermExtra; /* available for use by relation source node */
461 * additional runtime representation of FOR [KEY] UPDATE/SHARE clauses
463 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
464 * deal with. In addition to a pointer to the related entry in es_rowMarks,
465 * this struct carries the column number(s) of the resjunk columns associated
466 * with the rowmark (see comments for PlanRowMark for more detail). In the
467 * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
468 * each child plan, because the resjunk columns could be at different physical
469 * column positions in different subplans.
471 typedef struct ExecAuxRowMark
473 ExecRowMark *rowmark; /* related entry in es_rowMarks */
474 AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
475 AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
476 AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
480 /* ----------------------------------------------------------------
483 * All-in-memory tuple hash tables are used for a number of purposes.
485 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
486 * and tab_eq_funcs are non-cross-type equality operators for those types.
487 * Normally these are the only functions used, but FindTupleHashEntry()
488 * supports searching a hashtable using cross-data-type hashing. For that,
489 * the caller must supply hash functions for the LHS datatype as well as
490 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
491 * are set to point to the caller's function arrays while doing such a search.
492 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
493 * tab_eq_funcs respectively.
494 * ----------------------------------------------------------------
496 typedef struct TupleHashEntryData *TupleHashEntry;
497 typedef struct TupleHashTableData *TupleHashTable;
499 typedef struct TupleHashEntryData
501 /* firstTuple must be the first field in this struct! */
502 MinimalTuple firstTuple; /* copy of first tuple in this group */
503 /* there may be additional data beyond the end of this struct */
504 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
506 typedef struct TupleHashTableData
508 HTAB *hashtab; /* underlying dynahash table */
509 int numCols; /* number of columns in lookup key */
510 AttrNumber *keyColIdx; /* attr numbers of key columns */
511 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
512 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
513 MemoryContext tablecxt; /* memory context containing table */
514 MemoryContext tempcxt; /* context for function evaluations */
515 Size entrysize; /* actual size to make each hash entry */
516 TupleTableSlot *tableslot; /* slot for referencing table entries */
517 /* The following fields are set transiently for each table search: */
518 TupleTableSlot *inputslot; /* current input tuple's slot */
519 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
520 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
521 } TupleHashTableData;
523 typedef HASH_SEQ_STATUS TupleHashIterator;
526 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
527 * Use ResetTupleHashIterator if the table can be frozen (in this case no
528 * explicit scan termination is needed).
530 #define InitTupleHashIterator(htable, iter) \
531 hash_seq_init(iter, (htable)->hashtab)
532 #define TermTupleHashIterator(iter) \
534 #define ResetTupleHashIterator(htable, iter) \
536 hash_freeze((htable)->hashtab); \
537 hash_seq_init(iter, (htable)->hashtab); \
539 #define ScanTupleHashTable(iter) \
540 ((TupleHashEntry) hash_seq_search(iter))
543 /* ----------------------------------------------------------------
544 * Expression State Trees
546 * Each executable expression tree has a parallel ExprState tree.
548 * Unlike PlanState, there is not an exact one-for-one correspondence between
549 * ExprState node types and Expr node types. Many Expr node types have no
550 * need for node-type-specific run-time state, and so they can use plain
551 * ExprState or GenericExprState as their associated ExprState node type.
552 * ----------------------------------------------------------------
558 * ExprState is the common superclass for all ExprState-type nodes.
560 * It can also be instantiated directly for leaf Expr nodes that need no
561 * local run-time state (such as Var, Const, or Param).
563 * To save on dispatch overhead, each ExprState node contains a function
564 * pointer to the routine to execute to evaluate the node.
568 typedef struct ExprState ExprState;
570 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
571 ExprContext *econtext,
573 ExprDoneCond *isDone);
578 Expr *expr; /* associated Expr node */
579 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
583 * GenericExprState node
585 * This is used for Expr node types that need no local run-time state,
586 * but have one child Expr node.
589 typedef struct GenericExprState
592 ExprState *arg; /* state of my child node */
596 * WholeRowVarExprState node
599 typedef struct WholeRowVarExprState
602 struct PlanState *parent; /* parent PlanState, or NULL if none */
603 TupleDesc wrv_tupdesc; /* descriptor for resulting tuples */
604 JunkFilter *wrv_junkFilter; /* JunkFilter to remove resjunk cols */
605 } WholeRowVarExprState;
608 * AggrefExprState node
611 typedef struct AggrefExprState
614 int aggno; /* ID number for agg within its plan node */
618 * GroupingFuncExprState node
620 * The list of column numbers refers to the input tuples of the Agg node to
621 * which the GroupingFunc belongs, and may contain 0 for references to columns
622 * that are only present in grouping sets processed by different Agg nodes (and
623 * which are therefore always considered "grouping" here).
626 typedef struct GroupingFuncExprState
629 struct AggState *aggstate;
630 List *clauses; /* integer list of column numbers */
631 } GroupingFuncExprState;
634 * WindowFuncExprState node
637 typedef struct WindowFuncExprState
640 List *args; /* states of argument expressions */
641 ExprState *aggfilter; /* FILTER expression */
642 int wfuncno; /* ID number for wfunc within its plan node */
643 } WindowFuncExprState;
646 * ArrayRefExprState node
648 * Note: array types can be fixed-length (typlen > 0), but only when the
649 * element type is itself fixed-length. Otherwise they are varlena structures
650 * and have typlen = -1. In any case, an array type is never pass-by-value.
653 typedef struct ArrayRefExprState
656 List *refupperindexpr; /* states for child nodes */
657 List *reflowerindexpr;
659 ExprState *refassgnexpr;
660 int16 refattrlength; /* typlen of array type */
661 int16 refelemlength; /* typlen of the array element type */
662 bool refelembyval; /* is the element type pass-by-value? */
663 char refelemalign; /* typalign of the element type */
669 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
670 * and NullIf nodes; be careful to check what xprstate.expr is actually
674 typedef struct FuncExprState
677 List *args; /* states of argument expressions */
680 * Function manager's lookup info for the target function. If func.fn_oid
681 * is InvalidOid, we haven't initialized it yet (nor any of the following
687 * For a set-returning function (SRF) that returns a tuplestore, we keep
688 * the tuplestore here and dole out the result rows one at a time. The
689 * slot holds the row currently being returned.
691 Tuplestorestate *funcResultStore;
692 TupleTableSlot *funcResultSlot;
695 * In some cases we need to compute a tuple descriptor for the function's
696 * output. If so, it's stored here.
698 TupleDesc funcResultDesc;
699 bool funcReturnsTuple; /* valid when funcResultDesc isn't
703 * setArgsValid is true when we are evaluating a set-returning function
704 * that uses value-per-call mode and we are in the middle of a call
705 * series; we want to pass the same argument values to the function again
706 * (and again, until it returns ExprEndResult). This indicates that
707 * fcinfo_data already contains valid argument data.
712 * Flag to remember whether we found a set-valued argument to the
713 * function. This causes the function result to be a set as well. Valid
714 * only when setArgsValid is true or funcResultStore isn't NULL.
716 bool setHasSetArg; /* some argument returns a set */
719 * Flag to remember whether we have registered a shutdown callback for
720 * this FuncExprState. We do so only if funcResultStore or setArgsValid
721 * has been set at least once (since all the callback is for is to release
722 * the tuplestore or clear setArgsValid).
724 bool shutdown_reg; /* a shutdown callback is registered */
727 * Call parameter structure for the function. This has been initialized
728 * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
729 * argument values between calls, when setArgsValid is true.
731 FunctionCallInfoData fcinfo_data;
735 * ScalarArrayOpExprState node
737 * This is a FuncExprState plus some additional data.
740 typedef struct ScalarArrayOpExprState
742 FuncExprState fxprstate;
743 /* Cached info about array element type */
748 } ScalarArrayOpExprState;
754 typedef struct BoolExprState
757 List *args; /* states of argument expression(s) */
764 typedef struct SubPlanState
767 struct PlanState *planstate; /* subselect plan's state tree */
768 struct PlanState *parent; /* parent plan node's state tree */
769 ExprState *testexpr; /* state of combining expression */
770 List *args; /* states of argument expression(s) */
771 HeapTuple curTuple; /* copy of most recent tuple from subplan */
772 Datum curArray; /* most recent array from ARRAY() subplan */
773 /* these are used when hashing the subselect's output: */
774 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
775 ProjectionInfo *projRight; /* for projecting subselect output */
776 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
777 TupleHashTable hashnulls; /* hash table for rows with null(s) */
778 bool havehashrows; /* TRUE if hashtable is not empty */
779 bool havenullrows; /* TRUE if hashnulls is not empty */
780 MemoryContext hashtablecxt; /* memory context containing hash tables */
781 MemoryContext hashtempcxt; /* temp memory context for hash tables */
782 ExprContext *innerecontext; /* econtext for computing inner tuples */
783 AttrNumber *keyColIdx; /* control data for hash tables */
784 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
785 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
786 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
787 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
791 * AlternativeSubPlanState node
794 typedef struct AlternativeSubPlanState
797 List *subplans; /* states of alternative subplans */
798 int active; /* list index of the one we're using */
799 } AlternativeSubPlanState;
802 * FieldSelectState node
805 typedef struct FieldSelectState
808 ExprState *arg; /* input expression */
809 TupleDesc argdesc; /* tupdesc for most recent input */
813 * FieldStoreState node
816 typedef struct FieldStoreState
819 ExprState *arg; /* input tuple value */
820 List *newvals; /* new value(s) for field(s) */
821 TupleDesc argdesc; /* tupdesc for most recent input */
825 * CoerceViaIOState node
828 typedef struct CoerceViaIOState
831 ExprState *arg; /* input expression */
832 FmgrInfo outfunc; /* lookup info for source output function */
833 FmgrInfo infunc; /* lookup info for result input function */
834 Oid intypioparam; /* argument needed for input function */
838 * ArrayCoerceExprState node
841 typedef struct ArrayCoerceExprState
844 ExprState *arg; /* input array value */
845 Oid resultelemtype; /* element type of result array */
846 FmgrInfo elemfunc; /* lookup info for element coercion function */
847 /* use struct pointer to avoid including array.h here */
848 struct ArrayMapState *amstate; /* workspace for array_map */
849 } ArrayCoerceExprState;
852 * ConvertRowtypeExprState node
855 typedef struct ConvertRowtypeExprState
858 ExprState *arg; /* input tuple value */
859 TupleDesc indesc; /* tupdesc for source rowtype */
860 TupleDesc outdesc; /* tupdesc for result rowtype */
861 /* use "struct" so we needn't include tupconvert.h here */
862 struct TupleConversionMap *map;
864 } ConvertRowtypeExprState;
870 typedef struct CaseExprState
873 ExprState *arg; /* implicit equality comparison argument */
874 List *args; /* the arguments (list of WHEN clauses) */
875 ExprState *defresult; /* the default result (ELSE clause) */
882 typedef struct CaseWhenState
885 ExprState *expr; /* condition expression */
886 ExprState *result; /* substitution result */
890 * ArrayExprState node
892 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
896 typedef struct ArrayExprState
899 List *elements; /* states for child nodes */
900 int16 elemlength; /* typlen of the array element type */
901 bool elembyval; /* is the element type pass-by-value? */
902 char elemalign; /* typalign of the element type */
909 typedef struct RowExprState
912 List *args; /* the arguments */
913 TupleDesc tupdesc; /* descriptor for result tuples */
917 * RowCompareExprState node
920 typedef struct RowCompareExprState
923 List *largs; /* the left-hand input arguments */
924 List *rargs; /* the right-hand input arguments */
925 FmgrInfo *funcs; /* array of comparison function info */
926 Oid *collations; /* array of collations to use */
927 } RowCompareExprState;
930 * CoalesceExprState node
933 typedef struct CoalesceExprState
936 List *args; /* the arguments */
940 * MinMaxExprState node
943 typedef struct MinMaxExprState
946 List *args; /* the arguments */
947 FmgrInfo cfunc; /* lookup info for comparison func */
954 typedef struct XmlExprState
957 List *named_args; /* ExprStates for named arguments */
958 List *args; /* ExprStates for other arguments */
965 typedef struct NullTestState
968 ExprState *arg; /* input expression */
969 /* used only if input is of composite type: */
970 TupleDesc argdesc; /* tupdesc for most recent input */
974 * CoerceToDomainState node
977 typedef struct CoerceToDomainState
980 ExprState *arg; /* input expression */
981 /* Cached set of constraints that need to be checked */
982 /* use struct pointer to avoid including typcache.h here */
983 struct DomainConstraintRef *constraint_ref;
984 } CoerceToDomainState;
987 * DomainConstraintState - one item to check during CoerceToDomain
989 * Note: this is just a Node, and not an ExprState, because it has no
990 * corresponding Expr to link to. Nonetheless it is part of an ExprState
991 * tree, so we give it a name following the xxxState convention.
993 typedef enum DomainConstraintType
995 DOM_CONSTRAINT_NOTNULL,
997 } DomainConstraintType;
999 typedef struct DomainConstraintState
1002 DomainConstraintType constrainttype; /* constraint type */
1003 char *name; /* name of constraint (for error msgs) */
1004 ExprState *check_expr; /* for CHECK, a boolean expression */
1005 } DomainConstraintState;
1008 /* ----------------------------------------------------------------
1009 * Executor State Trees
1011 * An executing query has a PlanState tree paralleling the Plan tree
1012 * that describes the plan.
1013 * ----------------------------------------------------------------
1019 * We never actually instantiate any PlanState nodes; this is just the common
1020 * abstract superclass for all PlanState-type nodes.
1023 typedef struct PlanState
1027 Plan *plan; /* associated Plan node */
1029 EState *state; /* at execution time, states of individual
1030 * nodes point to one EState for the whole
1033 Instrumentation *instrument; /* Optional runtime stats for this node */
1034 WorkerInstrumentation *worker_instrument; /* per-worker instrumentation */
1037 * Common structural data for all Plan types. These links to subsidiary
1038 * state trees parallel links in the associated plan tree (except for the
1039 * subPlan list, which does not exist in the plan tree).
1041 List *targetlist; /* target list to be computed at this node */
1042 List *qual; /* implicitly-ANDed qual conditions */
1043 struct PlanState *lefttree; /* input plan tree(s) */
1044 struct PlanState *righttree;
1045 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
1047 List *subPlan; /* SubPlanState nodes in my expressions */
1050 * State for management of parameter-change-driven rescanning
1052 Bitmapset *chgParam; /* set of IDs of changed Params */
1055 * Other run-time state needed by most if not all node types.
1057 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
1058 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
1059 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
1060 bool ps_TupFromTlist;/* state flag for processing set-valued
1061 * functions in targetlist */
1065 * these are defined to avoid confusion problems with "left"
1066 * and "right" and "inner" and "outer". The convention is that
1067 * the "left" plan is the "outer" plan and the "right" plan is
1068 * the inner plan, but these make the code more readable.
1071 #define innerPlanState(node) (((PlanState *)(node))->righttree)
1072 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
1074 /* Macros for inline access to certain instrumentation counters */
1075 #define InstrCountFiltered1(node, delta) \
1077 if (((PlanState *)(node))->instrument) \
1078 ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
1080 #define InstrCountFiltered2(node, delta) \
1082 if (((PlanState *)(node))->instrument) \
1083 ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
1087 * EPQState is state for executing an EvalPlanQual recheck on a candidate
1088 * tuple in ModifyTable or LockRows. The estate and planstate fields are
1091 typedef struct EPQState
1093 EState *estate; /* subsidiary EState */
1094 PlanState *planstate; /* plan state tree ready to be executed */
1095 TupleTableSlot *origslot; /* original output tuple to be rechecked */
1096 Plan *plan; /* plan tree to be executed */
1097 List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
1098 int epqParam; /* ID of Param to force scan node re-eval */
1103 * ResultState information
1106 typedef struct ResultState
1108 PlanState ps; /* its first field is NodeTag */
1109 ExprState *resconstantqual;
1110 bool rs_done; /* are we done? */
1111 bool rs_checkqual; /* do we need to check the qual? */
1115 * ModifyTableState information
1118 typedef struct ModifyTableState
1120 PlanState ps; /* its first field is NodeTag */
1121 CmdType operation; /* INSERT, UPDATE, or DELETE */
1122 bool canSetTag; /* do we set the command tag/es_processed? */
1123 bool mt_done; /* are we done? */
1124 PlanState **mt_plans; /* subplans (one per target rel) */
1125 int mt_nplans; /* number of plans in the array */
1126 int mt_whichplan; /* which one is being executed (0..n-1) */
1127 ResultRelInfo *resultRelInfo; /* per-subplan target relations */
1128 List **mt_arowmarks; /* per-subplan ExecAuxRowMark lists */
1129 EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
1130 bool fireBSTriggers; /* do we need to fire stmt triggers? */
1131 OnConflictAction mt_onconflict; /* ON CONFLICT type */
1132 List *mt_arbiterindexes; /* unique index OIDs to arbitrate
1133 * taking alt path */
1134 TupleTableSlot *mt_existing; /* slot to store existing target tuple in */
1135 List *mt_excludedtlist; /* the excluded pseudo relation's
1137 TupleTableSlot *mt_conflproj; /* CONFLICT ... SET ... projection
1142 * AppendState information
1144 * nplans how many plans are in the array
1145 * whichplan which plan is being executed (0 .. n-1)
1148 typedef struct AppendState
1150 PlanState ps; /* its first field is NodeTag */
1151 PlanState **appendplans; /* array of PlanStates for my inputs */
1157 * MergeAppendState information
1159 * nplans how many plans are in the array
1160 * nkeys number of sort key columns
1161 * sortkeys sort keys in SortSupport representation
1162 * slots current output tuple of each subplan
1163 * heap heap of active tuples
1164 * initialized true if we have fetched first tuple from each subplan
1167 typedef struct MergeAppendState
1169 PlanState ps; /* its first field is NodeTag */
1170 PlanState **mergeplans; /* array of PlanStates for my inputs */
1173 SortSupport ms_sortkeys; /* array of length ms_nkeys */
1174 TupleTableSlot **ms_slots; /* array of length ms_nplans */
1175 struct binaryheap *ms_heap; /* binary heap of slot indices */
1176 bool ms_initialized; /* are subplans started? */
1180 * RecursiveUnionState information
1182 * RecursiveUnionState is used for performing a recursive union.
1184 * recursing T when we're done scanning the non-recursive term
1185 * intermediate_empty T if intermediate_table is currently empty
1186 * working_table working table (to be scanned by recursive term)
1187 * intermediate_table current recursive output (next generation of WT)
1190 typedef struct RecursiveUnionState
1192 PlanState ps; /* its first field is NodeTag */
1194 bool intermediate_empty;
1195 Tuplestorestate *working_table;
1196 Tuplestorestate *intermediate_table;
1197 /* Remaining fields are unused in UNION ALL case */
1198 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1199 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1200 MemoryContext tempContext; /* short-term context for comparisons */
1201 TupleHashTable hashtable; /* hash table for tuples already seen */
1202 MemoryContext tableContext; /* memory context containing hash table */
1203 } RecursiveUnionState;
1206 * BitmapAndState information
1209 typedef struct BitmapAndState
1211 PlanState ps; /* its first field is NodeTag */
1212 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1213 int nplans; /* number of input plans */
1217 * BitmapOrState information
1220 typedef struct BitmapOrState
1222 PlanState ps; /* its first field is NodeTag */
1223 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1224 int nplans; /* number of input plans */
1227 /* ----------------------------------------------------------------
1228 * Scan State Information
1229 * ----------------------------------------------------------------
1233 * ScanState information
1235 * ScanState extends PlanState for node types that represent
1236 * scans of an underlying relation. It can also be used for nodes
1237 * that scan the output of an underlying plan node --- in that case,
1238 * only ScanTupleSlot is actually useful, and it refers to the tuple
1239 * retrieved from the subplan.
1241 * currentRelation relation being scanned (NULL if none)
1242 * currentScanDesc current scan descriptor for scan (NULL if none)
1243 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
1246 typedef struct ScanState
1248 PlanState ps; /* its first field is NodeTag */
1249 Relation ss_currentRelation;
1250 HeapScanDesc ss_currentScanDesc;
1251 TupleTableSlot *ss_ScanTupleSlot;
1255 * SeqScanState information
1258 typedef struct SeqScanState
1260 ScanState ss; /* its first field is NodeTag */
1261 Size pscan_len; /* size of parallel heap scan descriptor */
1265 * SampleScanState information
1268 typedef struct SampleScanState
1271 List *args; /* expr states for TABLESAMPLE params */
1272 ExprState *repeatable; /* expr state for REPEATABLE expr */
1273 /* use struct pointer to avoid including tsmapi.h here */
1274 struct TsmRoutine *tsmroutine; /* descriptor for tablesample method */
1275 void *tsm_state; /* tablesample method can keep state here */
1276 bool use_bulkread; /* use bulkread buffer access strategy? */
1277 bool use_pagemode; /* use page-at-a-time visibility checking? */
1278 bool begun; /* false means need to call BeginSampleScan */
1279 uint32 seed; /* random seed */
1283 * These structs store information about index quals that don't have simple
1284 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1289 ScanKey scan_key; /* scankey to put value into */
1290 ExprState *key_expr; /* expr to evaluate to get value */
1291 bool key_toastable; /* is expr's result a toastable datatype? */
1292 } IndexRuntimeKeyInfo;
1296 ScanKey scan_key; /* scankey to put value into */
1297 ExprState *array_expr; /* expr to evaluate to get array value */
1298 int next_elem; /* next array element to use */
1299 int num_elems; /* number of elems in current array value */
1300 Datum *elem_values; /* array of num_elems Datums */
1301 bool *elem_nulls; /* array of num_elems is-null flags */
1302 } IndexArrayKeyInfo;
1305 * IndexScanState information
1307 * indexqualorig execution state for indexqualorig expressions
1308 * indexorderbyorig execution state for indexorderbyorig expressions
1309 * ScanKeys Skey structures for index quals
1310 * NumScanKeys number of ScanKeys
1311 * OrderByKeys Skey structures for index ordering operators
1312 * NumOrderByKeys number of OrderByKeys
1313 * RuntimeKeys info about Skeys that must be evaluated at runtime
1314 * NumRuntimeKeys number of RuntimeKeys
1315 * RuntimeKeysReady true if runtime Skeys have been computed
1316 * RuntimeContext expr context for evaling runtime Skeys
1317 * RelationDesc index relation descriptor
1318 * ScanDesc index scan descriptor
1320 * ReorderQueue tuples that need reordering due to re-check
1321 * ReachedEnd have we fetched all tuples from index already?
1322 * OrderByValues values of ORDER BY exprs of last fetched tuple
1323 * OrderByNulls null flags for OrderByValues
1324 * SortSupport for reordering ORDER BY exprs
1325 * OrderByTypByVals is the datatype of order by expression pass-by-value?
1326 * OrderByTypLens typlens of the datatypes of order by expressions
1329 typedef struct IndexScanState
1331 ScanState ss; /* its first field is NodeTag */
1332 List *indexqualorig;
1333 List *indexorderbyorig;
1334 ScanKey iss_ScanKeys;
1335 int iss_NumScanKeys;
1336 ScanKey iss_OrderByKeys;
1337 int iss_NumOrderByKeys;
1338 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1339 int iss_NumRuntimeKeys;
1340 bool iss_RuntimeKeysReady;
1341 ExprContext *iss_RuntimeContext;
1342 Relation iss_RelationDesc;
1343 IndexScanDesc iss_ScanDesc;
1345 /* These are needed for re-checking ORDER BY expr ordering */
1346 pairingheap *iss_ReorderQueue;
1347 bool iss_ReachedEnd;
1348 Datum *iss_OrderByValues;
1349 bool *iss_OrderByNulls;
1350 SortSupport iss_SortSupport;
1351 bool *iss_OrderByTypByVals;
1352 int16 *iss_OrderByTypLens;
1356 * IndexOnlyScanState information
1358 * indexqual execution state for indexqual expressions
1359 * ScanKeys Skey structures for index quals
1360 * NumScanKeys number of ScanKeys
1361 * OrderByKeys Skey structures for index ordering operators
1362 * NumOrderByKeys number of OrderByKeys
1363 * RuntimeKeys info about Skeys that must be evaluated at runtime
1364 * NumRuntimeKeys number of RuntimeKeys
1365 * RuntimeKeysReady true if runtime Skeys have been computed
1366 * RuntimeContext expr context for evaling runtime Skeys
1367 * RelationDesc index relation descriptor
1368 * ScanDesc index scan descriptor
1369 * VMBuffer buffer in use for visibility map testing, if any
1370 * HeapFetches number of tuples we were forced to fetch from heap
1373 typedef struct IndexOnlyScanState
1375 ScanState ss; /* its first field is NodeTag */
1377 ScanKey ioss_ScanKeys;
1378 int ioss_NumScanKeys;
1379 ScanKey ioss_OrderByKeys;
1380 int ioss_NumOrderByKeys;
1381 IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1382 int ioss_NumRuntimeKeys;
1383 bool ioss_RuntimeKeysReady;
1384 ExprContext *ioss_RuntimeContext;
1385 Relation ioss_RelationDesc;
1386 IndexScanDesc ioss_ScanDesc;
1387 Buffer ioss_VMBuffer;
1388 long ioss_HeapFetches;
1389 } IndexOnlyScanState;
1392 * BitmapIndexScanState information
1394 * result bitmap to return output into, or NULL
1395 * ScanKeys Skey structures for index quals
1396 * NumScanKeys number of ScanKeys
1397 * RuntimeKeys info about Skeys that must be evaluated at runtime
1398 * NumRuntimeKeys number of RuntimeKeys
1399 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1400 * NumArrayKeys number of ArrayKeys
1401 * RuntimeKeysReady true if runtime Skeys have been computed
1402 * RuntimeContext expr context for evaling runtime Skeys
1403 * RelationDesc index relation descriptor
1404 * ScanDesc index scan descriptor
1407 typedef struct BitmapIndexScanState
1409 ScanState ss; /* its first field is NodeTag */
1410 TIDBitmap *biss_result;
1411 ScanKey biss_ScanKeys;
1412 int biss_NumScanKeys;
1413 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1414 int biss_NumRuntimeKeys;
1415 IndexArrayKeyInfo *biss_ArrayKeys;
1416 int biss_NumArrayKeys;
1417 bool biss_RuntimeKeysReady;
1418 ExprContext *biss_RuntimeContext;
1419 Relation biss_RelationDesc;
1420 IndexScanDesc biss_ScanDesc;
1421 } BitmapIndexScanState;
1424 * BitmapHeapScanState information
1426 * bitmapqualorig execution state for bitmapqualorig expressions
1427 * tbm bitmap obtained from child index scan(s)
1428 * tbmiterator iterator for scanning current pages
1429 * tbmres current-page data
1430 * exact_pages total number of exact pages retrieved
1431 * lossy_pages total number of lossy pages retrieved
1432 * prefetch_iterator iterator for prefetching ahead of current page
1433 * prefetch_pages # pages prefetch iterator is ahead of current
1434 * prefetch_target current target prefetch distance
1435 * prefetch_maximum maximum value for prefetch_target
1438 typedef struct BitmapHeapScanState
1440 ScanState ss; /* its first field is NodeTag */
1441 List *bitmapqualorig;
1443 TBMIterator *tbmiterator;
1444 TBMIterateResult *tbmres;
1447 TBMIterator *prefetch_iterator;
1449 int prefetch_target;
1450 int prefetch_maximum;
1451 } BitmapHeapScanState;
1454 * TidScanState information
1456 * isCurrentOf scan has a CurrentOfExpr qual
1457 * NumTids number of tids in this scan
1458 * TidPtr index of currently fetched tid
1459 * TidList evaluated item pointers (array of size NumTids)
1462 typedef struct TidScanState
1464 ScanState ss; /* its first field is NodeTag */
1465 List *tss_tidquals; /* list of ExprState nodes */
1466 bool tss_isCurrentOf;
1469 ItemPointerData *tss_TidList;
1470 HeapTupleData tss_htup;
1474 * SubqueryScanState information
1476 * SubqueryScanState is used for scanning a sub-query in the range table.
1477 * ScanTupleSlot references the current output tuple of the sub-query.
1480 typedef struct SubqueryScanState
1482 ScanState ss; /* its first field is NodeTag */
1484 } SubqueryScanState;
1487 * FunctionScanState information
1489 * Function nodes are used to scan the results of a
1490 * function appearing in FROM (typically a function returning set).
1492 * eflags node's capability flags
1493 * ordinality is this scan WITH ORDINALITY?
1494 * simple true if we have 1 function and no ordinality
1495 * ordinal current ordinal column value
1496 * nfuncs number of functions being executed
1497 * funcstates per-function execution states (private in
1498 * nodeFunctionscan.c)
1499 * argcontext memory context to evaluate function arguments in
1502 struct FunctionScanPerFuncState;
1504 typedef struct FunctionScanState
1506 ScanState ss; /* its first field is NodeTag */
1512 struct FunctionScanPerFuncState *funcstates; /* array of length
1514 MemoryContext argcontext;
1515 } FunctionScanState;
1518 * ValuesScanState information
1520 * ValuesScan nodes are used to scan the results of a VALUES list
1522 * rowcontext per-expression-list context
1523 * exprlists array of expression lists being evaluated
1524 * array_len size of array
1525 * curr_idx current array index (0-based)
1527 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1528 * expressions attached to the node. We create a second ExprContext,
1529 * rowcontext, in which to build the executor expression state for each
1530 * Values sublist. Resetting this context lets us get rid of expression
1531 * state for each row, avoiding major memory leakage over a long values list.
1534 typedef struct ValuesScanState
1536 ScanState ss; /* its first field is NodeTag */
1537 ExprContext *rowcontext;
1544 * CteScanState information
1546 * CteScan nodes are used to scan a CommonTableExpr query.
1548 * Multiple CteScan nodes can read out from the same CTE query. We use
1549 * a tuplestore to hold rows that have been read from the CTE query but
1550 * not yet consumed by all readers.
1553 typedef struct CteScanState
1555 ScanState ss; /* its first field is NodeTag */
1556 int eflags; /* capability flags to pass to tuplestore */
1557 int readptr; /* index of my tuplestore read pointer */
1558 PlanState *cteplanstate; /* PlanState for the CTE query itself */
1559 /* Link to the "leader" CteScanState (possibly this same node) */
1560 struct CteScanState *leader;
1561 /* The remaining fields are only valid in the "leader" CteScanState */
1562 Tuplestorestate *cte_table; /* rows already read from the CTE query */
1563 bool eof_cte; /* reached end of CTE query? */
1567 * WorkTableScanState information
1569 * WorkTableScan nodes are used to scan the work table created by
1570 * a RecursiveUnion node. We locate the RecursiveUnion node
1571 * during executor startup.
1574 typedef struct WorkTableScanState
1576 ScanState ss; /* its first field is NodeTag */
1577 RecursiveUnionState *rustate;
1578 } WorkTableScanState;
1581 * ForeignScanState information
1583 * ForeignScan nodes are used to scan foreign-data tables.
1586 typedef struct ForeignScanState
1588 ScanState ss; /* its first field is NodeTag */
1589 List *fdw_recheck_quals; /* original quals not in ss.ps.qual */
1590 Size pscan_len; /* size of parallel coordination information */
1591 /* use struct pointer to avoid including fdwapi.h here */
1592 struct FdwRoutine *fdwroutine;
1593 void *fdw_state; /* foreign-data wrapper can keep state here */
1597 * CustomScanState information
1599 * CustomScan nodes are used to execute custom code within executor.
1601 * Core code must avoid assuming that the CustomScanState is only as large as
1602 * the structure declared here; providers are allowed to make it the first
1603 * element in a larger structure, and typically would need to do so. The
1604 * struct is actually allocated by the CreateCustomScanState method associated
1605 * with the plan node. Any additional fields can be initialized there, or in
1606 * the BeginCustomScan method.
1609 struct CustomExecMethods;
1611 typedef struct CustomScanState
1614 uint32 flags; /* mask of CUSTOMPATH_* flags, see relation.h */
1615 List *custom_ps; /* list of child PlanState nodes, if any */
1616 Size pscan_len; /* size of parallel coordination information */
1617 const struct CustomExecMethods *methods;
1620 /* ----------------------------------------------------------------
1621 * Join State Information
1622 * ----------------------------------------------------------------
1626 * JoinState information
1628 * Superclass for state nodes of join plans.
1631 typedef struct JoinState
1635 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1639 * NestLoopState information
1641 * NeedNewOuter true if need new outer tuple on next call
1642 * MatchedOuter true if found a join match for current outer tuple
1643 * NullInnerTupleSlot prepared null tuple for left outer joins
1646 typedef struct NestLoopState
1648 JoinState js; /* its first field is NodeTag */
1649 bool nl_NeedNewOuter;
1650 bool nl_MatchedOuter;
1651 TupleTableSlot *nl_NullInnerTupleSlot;
1655 * MergeJoinState information
1657 * NumClauses number of mergejoinable join clauses
1658 * Clauses info for each mergejoinable clause
1659 * JoinState current state of ExecMergeJoin state machine
1660 * ExtraMarks true to issue extra Mark operations on inner scan
1661 * ConstFalseJoin true if we have a constant-false joinqual
1662 * FillOuter true if should emit unjoined outer tuples anyway
1663 * FillInner true if should emit unjoined inner tuples anyway
1664 * MatchedOuter true if found a join match for current outer tuple
1665 * MatchedInner true if found a join match for current inner tuple
1666 * OuterTupleSlot slot in tuple table for cur outer tuple
1667 * InnerTupleSlot slot in tuple table for cur inner tuple
1668 * MarkedTupleSlot slot in tuple table for marked tuple
1669 * NullOuterTupleSlot prepared null tuple for right outer joins
1670 * NullInnerTupleSlot prepared null tuple for left outer joins
1671 * OuterEContext workspace for computing outer tuple's join values
1672 * InnerEContext workspace for computing inner tuple's join values
1675 /* private in nodeMergejoin.c: */
1676 typedef struct MergeJoinClauseData *MergeJoinClause;
1678 typedef struct MergeJoinState
1680 JoinState js; /* its first field is NodeTag */
1682 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1685 bool mj_ConstFalseJoin;
1688 bool mj_MatchedOuter;
1689 bool mj_MatchedInner;
1690 TupleTableSlot *mj_OuterTupleSlot;
1691 TupleTableSlot *mj_InnerTupleSlot;
1692 TupleTableSlot *mj_MarkedTupleSlot;
1693 TupleTableSlot *mj_NullOuterTupleSlot;
1694 TupleTableSlot *mj_NullInnerTupleSlot;
1695 ExprContext *mj_OuterEContext;
1696 ExprContext *mj_InnerEContext;
1700 * HashJoinState information
1702 * hashclauses original form of the hashjoin condition
1703 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1704 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1705 * hj_HashOperators the join operators in the hashjoin condition
1706 * hj_HashTable hash table for the hashjoin
1707 * (NULL if table not built yet)
1708 * hj_CurHashValue hash value for current outer tuple
1709 * hj_CurBucketNo regular bucket# for current outer tuple
1710 * hj_CurSkewBucketNo skew bucket# for current outer tuple
1711 * hj_CurTuple last inner tuple matched to current outer
1712 * tuple, or NULL if starting search
1713 * (hj_CurXXX variables are undefined if
1714 * OuterTupleSlot is empty!)
1715 * hj_OuterTupleSlot tuple slot for outer tuples
1716 * hj_HashTupleSlot tuple slot for inner (hashed) tuples
1717 * hj_NullOuterTupleSlot prepared null tuple for right/full outer joins
1718 * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
1719 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1720 * hj_JoinState current state of ExecHashJoin state machine
1721 * hj_MatchedOuter true if found a join match for current outer
1722 * hj_OuterNotEmpty true if outer relation known not empty
1726 /* these structs are defined in executor/hashjoin.h: */
1727 typedef struct HashJoinTupleData *HashJoinTuple;
1728 typedef struct HashJoinTableData *HashJoinTable;
1730 typedef struct HashJoinState
1732 JoinState js; /* its first field is NodeTag */
1733 List *hashclauses; /* list of ExprState nodes */
1734 List *hj_OuterHashKeys; /* list of ExprState nodes */
1735 List *hj_InnerHashKeys; /* list of ExprState nodes */
1736 List *hj_HashOperators; /* list of operator OIDs */
1737 HashJoinTable hj_HashTable;
1738 uint32 hj_CurHashValue;
1740 int hj_CurSkewBucketNo;
1741 HashJoinTuple hj_CurTuple;
1742 TupleTableSlot *hj_OuterTupleSlot;
1743 TupleTableSlot *hj_HashTupleSlot;
1744 TupleTableSlot *hj_NullOuterTupleSlot;
1745 TupleTableSlot *hj_NullInnerTupleSlot;
1746 TupleTableSlot *hj_FirstOuterTupleSlot;
1748 bool hj_MatchedOuter;
1749 bool hj_OuterNotEmpty;
1753 /* ----------------------------------------------------------------
1754 * Materialization State Information
1755 * ----------------------------------------------------------------
1759 * MaterialState information
1761 * materialize nodes are used to materialize the results
1762 * of a subplan into a temporary file.
1764 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1767 typedef struct MaterialState
1769 ScanState ss; /* its first field is NodeTag */
1770 int eflags; /* capability flags to pass to tuplestore */
1771 bool eof_underlying; /* reached end of underlying plan? */
1772 Tuplestorestate *tuplestorestate;
1776 * SortState information
1779 typedef struct SortState
1781 ScanState ss; /* its first field is NodeTag */
1782 bool randomAccess; /* need random access to sort output? */
1783 bool bounded; /* is the result set bounded? */
1784 int64 bound; /* if bounded, how many tuples are needed */
1785 bool sort_Done; /* sort completed yet? */
1786 bool bounded_Done; /* value of bounded we did the sort with */
1787 int64 bound_Done; /* value of bound we did the sort with */
1788 void *tuplesortstate; /* private state of tuplesort.c */
1791 /* ---------------------
1792 * GroupState information
1793 * -------------------------
1795 typedef struct GroupState
1797 ScanState ss; /* its first field is NodeTag */
1798 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1799 bool grp_done; /* indicates completion of Group scan */
1802 /* ---------------------
1803 * AggState information
1805 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1807 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1808 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1809 * input group during evaluation of an Agg node's output tuple(s). We
1810 * create a second ExprContext, tmpcontext, in which to evaluate input
1811 * expressions and run the aggregate transition functions.
1812 * -------------------------
1814 /* these structs are private in nodeAgg.c: */
1815 typedef struct AggStatePerAggData *AggStatePerAgg;
1816 typedef struct AggStatePerTransData *AggStatePerTrans;
1817 typedef struct AggStatePerGroupData *AggStatePerGroup;
1818 typedef struct AggStatePerPhaseData *AggStatePerPhase;
1820 typedef struct AggState
1822 ScanState ss; /* its first field is NodeTag */
1823 List *aggs; /* all Aggref nodes in targetlist & quals */
1824 int numaggs; /* length of list (could be zero!) */
1825 int numtrans; /* number of pertrans items */
1826 AggStatePerPhase phase; /* pointer to current phase data */
1827 int numphases; /* number of phases */
1828 int current_phase; /* current phase number */
1829 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1830 AggStatePerAgg peragg; /* per-Aggref information */
1831 AggStatePerTrans pertrans; /* per-Trans state information */
1832 ExprContext **aggcontexts; /* econtexts for long-lived data (per GS) */
1833 ExprContext *tmpcontext; /* econtext for input expressions */
1834 AggStatePerTrans curpertrans; /* currently active trans state */
1835 bool input_done; /* indicates end of input */
1836 bool agg_done; /* indicates completion of Agg scan */
1837 bool combineStates; /* input tuples contain transition states */
1838 bool finalizeAggs; /* should we call the finalfn on agg states? */
1839 bool serialStates; /* should agg states be (de)serialized? */
1840 int projected_set; /* The last projected grouping set */
1841 int current_set; /* The current grouping set being evaluated */
1842 Bitmapset *grouped_cols; /* grouped cols in current projection */
1843 List *all_grouped_cols; /* list of all grouped cols in DESC
1845 /* These fields are for grouping set phase data */
1846 int maxsets; /* The max number of sets in any phase */
1847 AggStatePerPhase phases; /* array of all phases */
1848 Tuplesortstate *sort_in; /* sorted input to phases > 0 */
1849 Tuplesortstate *sort_out; /* input is copied here for next phase */
1850 TupleTableSlot *sort_slot; /* slot for sort results */
1851 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1852 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1853 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1854 /* these fields are used in AGG_HASHED mode: */
1855 TupleHashTable hashtable; /* hash table with one entry per group */
1856 TupleTableSlot *hashslot; /* slot for loading hash table */
1857 List *hash_needed; /* list of columns needed in hash table */
1858 bool table_filled; /* hash table filled yet? */
1859 TupleHashIterator hashiter; /* for iterating through hash table */
1863 * WindowAggState information
1866 /* these structs are private in nodeWindowAgg.c: */
1867 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1868 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1870 typedef struct WindowAggState
1872 ScanState ss; /* its first field is NodeTag */
1874 /* these fields are filled in by ExecInitExpr: */
1875 List *funcs; /* all WindowFunc nodes in targetlist */
1876 int numfuncs; /* total number of window functions */
1877 int numaggs; /* number that are plain aggregates */
1879 WindowStatePerFunc perfunc; /* per-window-function information */
1880 WindowStatePerAgg peragg; /* per-plain-aggregate information */
1881 FmgrInfo *partEqfunctions; /* equality funcs for partition columns */
1882 FmgrInfo *ordEqfunctions; /* equality funcs for ordering columns */
1883 Tuplestorestate *buffer; /* stores rows of current partition */
1884 int current_ptr; /* read pointer # for current */
1885 int64 spooled_rows; /* total # of rows in buffer */
1886 int64 currentpos; /* position of current row in partition */
1887 int64 frameheadpos; /* current frame head position */
1888 int64 frametailpos; /* current frame tail position */
1889 /* use struct pointer to avoid including windowapi.h here */
1890 struct WindowObjectData *agg_winobj; /* winobj for aggregate
1892 int64 aggregatedbase; /* start row for current aggregates */
1893 int64 aggregatedupto; /* rows before this one are aggregated */
1895 int frameOptions; /* frame_clause options, see WindowDef */
1896 ExprState *startOffset; /* expression for starting bound offset */
1897 ExprState *endOffset; /* expression for ending bound offset */
1898 Datum startOffsetValue; /* result of startOffset evaluation */
1899 Datum endOffsetValue; /* result of endOffset evaluation */
1901 MemoryContext partcontext; /* context for partition-lifespan data */
1902 MemoryContext aggcontext; /* shared context for aggregate working data */
1903 MemoryContext curaggcontext; /* current aggregate's working data */
1904 ExprContext *tmpcontext; /* short-term evaluation context */
1906 bool all_first; /* true if the scan is starting */
1907 bool all_done; /* true if the scan is finished */
1908 bool partition_spooled; /* true if all tuples in current
1909 * partition have been spooled into
1911 bool more_partitions;/* true if there's more partitions after this
1913 bool framehead_valid;/* true if frameheadpos is known up to date
1914 * for current row */
1915 bool frametail_valid;/* true if frametailpos is known up to date
1916 * for current row */
1918 TupleTableSlot *first_part_slot; /* first tuple of current or next
1921 /* temporary slots for tuples fetched back from tuplestore */
1922 TupleTableSlot *agg_row_slot;
1923 TupleTableSlot *temp_slot_1;
1924 TupleTableSlot *temp_slot_2;
1928 * UniqueState information
1930 * Unique nodes are used "on top of" sort nodes to discard
1931 * duplicate tuples returned from the sort phase. Basically
1932 * all it does is compare the current tuple from the subplan
1933 * with the previously fetched tuple (stored in its result slot).
1934 * If the two are identical in all interesting fields, then
1935 * we just fetch another tuple from the sort and try again.
1938 typedef struct UniqueState
1940 PlanState ps; /* its first field is NodeTag */
1941 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1942 MemoryContext tempContext; /* short-term context for comparisons */
1946 * GatherState information
1948 * Gather nodes launch 1 or more parallel workers, run a subplan
1949 * in those workers, and collect the results.
1952 typedef struct GatherState
1954 PlanState ps; /* its first field is NodeTag */
1956 struct ParallelExecutorInfo *pei;
1959 struct TupleQueueReader **reader;
1960 TupleTableSlot *funnel_slot;
1961 bool need_to_scan_locally;
1965 * HashState information
1968 typedef struct HashState
1970 PlanState ps; /* its first field is NodeTag */
1971 HashJoinTable hashtable; /* hash table for the hashjoin */
1972 List *hashkeys; /* list of ExprState nodes */
1973 /* hashkeys is same as parent's hj_InnerHashKeys */
1977 * SetOpState information
1979 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1980 * Unique, since we have to count how many duplicates to return. But
1981 * we also support hashing, so this is really more like a cut-down
1985 /* this struct is private in nodeSetOp.c: */
1986 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1988 typedef struct SetOpState
1990 PlanState ps; /* its first field is NodeTag */
1991 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1992 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1993 bool setop_done; /* indicates completion of output scan */
1994 long numOutput; /* number of dups left to output */
1995 MemoryContext tempContext; /* short-term context for comparisons */
1996 /* these fields are used in SETOP_SORTED mode: */
1997 SetOpStatePerGroup pergroup; /* per-group working state */
1998 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1999 /* these fields are used in SETOP_HASHED mode: */
2000 TupleHashTable hashtable; /* hash table with one entry per group */
2001 MemoryContext tableContext; /* memory context containing hash table */
2002 bool table_filled; /* hash table filled yet? */
2003 TupleHashIterator hashiter; /* for iterating through hash table */
2007 * LockRowsState information
2009 * LockRows nodes are used to enforce FOR [KEY] UPDATE/SHARE locking.
2012 typedef struct LockRowsState
2014 PlanState ps; /* its first field is NodeTag */
2015 List *lr_arowMarks; /* List of ExecAuxRowMarks */
2016 EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
2017 HeapTuple *lr_curtuples; /* locked tuples (one entry per RT entry) */
2018 int lr_ntables; /* length of lr_curtuples[] array */
2022 * LimitState information
2024 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
2025 * They just select the desired subrange of their subplan's output.
2027 * offset is the number of initial tuples to skip (0 does nothing).
2028 * count is the number of tuples to return after skipping the offset tuples.
2029 * If no limit count was specified, count is undefined and noCount is true.
2030 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
2035 LIMIT_INITIAL, /* initial state for LIMIT node */
2036 LIMIT_RESCAN, /* rescan after recomputing parameters */
2037 LIMIT_EMPTY, /* there are no returnable rows */
2038 LIMIT_INWINDOW, /* have returned a row in the window */
2039 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
2040 LIMIT_WINDOWEND, /* stepped off end of window */
2041 LIMIT_WINDOWSTART /* stepped off beginning of window */
2044 typedef struct LimitState
2046 PlanState ps; /* its first field is NodeTag */
2047 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
2048 ExprState *limitCount; /* COUNT parameter, or NULL if none */
2049 int64 offset; /* current OFFSET value */
2050 int64 count; /* current COUNT, if any */
2051 bool noCount; /* if true, ignore count */
2052 LimitStateCond lstate; /* state machine status, as above */
2053 int64 position; /* 1-based index of last tuple returned */
2054 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
2057 #endif /* EXECNODES_H */