1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2017, 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 "access/tupconvert.h"
20 #include "executor/instrument.h"
21 #include "lib/pairingheap.h"
22 #include "nodes/params.h"
23 #include "nodes/plannodes.h"
24 #include "utils/hsearch.h"
25 #include "utils/reltrigger.h"
26 #include "utils/sortsupport.h"
27 #include "utils/tuplestore.h"
28 #include "utils/tuplesort.h"
29 #include "nodes/tidbitmap.h"
30 #include "storage/condition_variable.h"
36 * ExprState is the top-level node for expression evaluation.
37 * It contains instructions (in ->steps) to evaluate the expression.
40 struct ExprState; /* forward references in this file */
42 struct ExprEvalStep; /* avoid including execExpr.h everywhere */
44 typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression,
45 struct ExprContext *econtext,
48 /* Bits in ExprState->flags (see also execExpr.h for private flag bits): */
49 /* expression is for use with ExecQual() */
50 #define EEO_FLAG_IS_QUAL (1 << 0)
52 typedef struct ExprState
56 uint8 flags; /* bitmask of EEO_FLAG_* bits, see above */
59 * Storage for result value of a scalar expression, or for individual
60 * column results within expressions built by ExecBuildProjectionInfo().
66 * If projecting a tuple result, this slot holds the result; else NULL.
68 TupleTableSlot *resultslot;
71 * Instructions to compute expression's return value.
73 struct ExprEvalStep *steps;
76 * Function that actually evaluates the expression. This can be set to
77 * different values depending on the complexity of the expression.
79 ExprStateEvalFunc evalfunc;
81 /* original expression tree, for debugging only */
85 * XXX: following only needed during "compilation", could be thrown away.
88 int steps_len; /* number of steps currently */
89 int steps_alloc; /* allocated length of steps array */
91 Datum *innermost_caseval;
92 bool *innermost_casenull;
94 Datum *innermost_domainval;
95 bool *innermost_domainnull;
100 * IndexInfo information
102 * this struct holds the information needed to construct new index
103 * entries for a particular index. Used for both index_build and
104 * retail creation of index entries.
106 * NumIndexAttrs number of columns in this index
107 * KeyAttrNumbers underlying-rel attribute numbers used as keys
108 * (zeroes indicate expressions)
109 * Expressions expr trees for expression entries, or NIL if none
110 * ExpressionsState exec state for expressions, or NIL if none
111 * Predicate partial-index predicate, or NIL if none
112 * PredicateState exec state for predicate, or NIL if none
113 * ExclusionOps Per-column exclusion operators, or NULL if none
114 * ExclusionProcs Underlying function OIDs for ExclusionOps
115 * ExclusionStrats Opclass strategy numbers for ExclusionOps
116 * UniqueOps Theses are like Exclusion*, but for unique indexes
119 * Unique is it a unique index?
120 * ReadyForInserts is it valid for inserts?
121 * Concurrent are we doing a concurrent index build?
122 * BrokenHotChain did we detect any broken HOT chains?
123 * AmCache private cache area for index AM
124 * Context memory context holding this IndexInfo
126 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
127 * they're conventionally set to false otherwise.
130 typedef struct IndexInfo
133 int ii_NumIndexAttrs;
134 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
135 List *ii_Expressions; /* list of Expr */
136 List *ii_ExpressionsState; /* list of ExprState */
137 List *ii_Predicate; /* list of Expr */
138 ExprState *ii_PredicateState;
139 Oid *ii_ExclusionOps; /* array with one entry per column */
140 Oid *ii_ExclusionProcs; /* array with one entry per column */
141 uint16 *ii_ExclusionStrats; /* array with one entry per column */
142 Oid *ii_UniqueOps; /* array with one entry per column */
143 Oid *ii_UniqueProcs; /* array with one entry per column */
144 uint16 *ii_UniqueStrats; /* array with one entry per column */
146 bool ii_ReadyForInserts;
148 bool ii_BrokenHotChain;
150 MemoryContext ii_Context;
156 * List of callbacks to be called at ExprContext shutdown.
159 typedef void (*ExprContextCallbackFunction) (Datum arg);
161 typedef struct ExprContext_CB
163 struct ExprContext_CB *next;
164 ExprContextCallbackFunction function;
171 * This class holds the "current context" information
172 * needed to evaluate expressions for doing tuple qualifications
173 * and tuple projections. For example, if an expression refers
174 * to an attribute in the current inner tuple then we need to know
175 * what the current inner tuple is and so we look at the expression
178 * There are two memory contexts associated with an ExprContext:
179 * * ecxt_per_query_memory is a query-lifespan context, typically the same
180 * context the ExprContext node itself is allocated in. This context
181 * can be used for purposes such as storing function call cache info.
182 * * ecxt_per_tuple_memory is a short-term context for expression results.
183 * As the name suggests, it will typically be reset once per tuple,
184 * before we begin to evaluate expressions for that tuple. Each
185 * ExprContext normally has its very own per-tuple memory context.
187 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
188 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
191 typedef struct ExprContext
195 /* Tuples that Var nodes in expression may refer to */
196 TupleTableSlot *ecxt_scantuple;
197 TupleTableSlot *ecxt_innertuple;
198 TupleTableSlot *ecxt_outertuple;
200 /* Memory contexts for expression evaluation --- see notes above */
201 MemoryContext ecxt_per_query_memory;
202 MemoryContext ecxt_per_tuple_memory;
204 /* Values to substitute for Param nodes in expression */
205 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
206 ParamListInfo ecxt_param_list_info; /* for other param types */
209 * Values to substitute for Aggref nodes in the expressions of an Agg
210 * node, or for WindowFunc nodes within a WindowAgg node.
212 Datum *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
213 bool *ecxt_aggnulls; /* null flags for aggs/windowfuncs */
215 /* Value to substitute for CaseTestExpr nodes in expression */
216 Datum caseValue_datum;
217 bool caseValue_isNull;
219 /* Value to substitute for CoerceToDomainValue nodes in expression */
220 Datum domainValue_datum;
221 bool domainValue_isNull;
223 /* Link to containing EState (NULL if a standalone ExprContext) */
224 struct EState *ecxt_estate;
226 /* Functions to call back when ExprContext is shut down or rescanned */
227 ExprContext_CB *ecxt_callbacks;
231 * Set-result status used when evaluating functions potentially returning a
236 ExprSingleResult, /* expression does not return a set */
237 ExprMultipleResult, /* this result is an element of a set */
238 ExprEndResult /* there are no more elements in the set */
242 * Return modes for functions returning sets. Note values must be chosen
243 * as separate bits so that a bitmask can be formed to indicate supported
244 * modes. SFRM_Materialize_Random and SFRM_Materialize_Preferred are
245 * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
249 SFRM_ValuePerCall = 0x01, /* one value returned per call */
250 SFRM_Materialize = 0x02, /* result set instantiated in Tuplestore */
251 SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */
252 SFRM_Materialize_Preferred = 0x08 /* caller prefers Tuplestore */
253 } SetFunctionReturnMode;
256 * When calling a function that might return a set (multiple rows),
257 * a node of this type is passed as fcinfo->resultinfo to allow
258 * return status to be passed back. A function returning set should
259 * raise an error if no such resultinfo is provided.
261 typedef struct ReturnSetInfo
264 /* values set by caller: */
265 ExprContext *econtext; /* context function is being called in */
266 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
267 int allowedModes; /* bitmask: return modes caller can handle */
268 /* result status from function (but pre-initialized by caller): */
269 SetFunctionReturnMode returnMode; /* actual return mode */
270 ExprDoneCond isDone; /* status for ValuePerCall mode */
271 /* fields filled by function in Materialize return mode: */
272 Tuplestorestate *setResult; /* holds the complete returned tuple set */
273 TupleDesc setDesc; /* actual descriptor for returned tuples */
277 * ProjectionInfo node information
279 * This is all the information needed to perform projections ---
280 * that is, form new tuples by evaluation of targetlist expressions.
281 * Nodes which need to do projections create one of these.
283 * The target tuple slot is kept in ProjectionInfo->pi_state.resultslot.
284 * ExecProject() evaluates the tlist, forms a tuple, and stores it
285 * in the given slot. Note that the result will be a "virtual" tuple
286 * unless ExecMaterializeSlot() is then called to force it to be
287 * converted to a physical tuple. The slot must have a tupledesc
288 * that matches the output of the tlist!
291 typedef struct ProjectionInfo
294 /* instructions to evaluate projection */
296 /* expression context in which to evaluate expression */
297 ExprContext *pi_exprContext;
303 * This class is used to store information regarding junk attributes.
304 * A junk attribute is an attribute in a tuple that is needed only for
305 * storing intermediate information in the executor, and does not belong
306 * in emitted tuples. For example, when we do an UPDATE query,
307 * the planner adds a "junk" entry to the targetlist so that the tuples
308 * returned to ExecutePlan() contain an extra attribute: the ctid of
309 * the tuple to be updated. This is needed to do the update, but we
310 * don't want the ctid to be part of the stored new tuple! So, we
311 * apply a "junk filter" to remove the junk attributes and form the
312 * real output tuple. The junkfilter code also provides routines to
313 * extract the values of the junk attribute(s) from the input tuple.
315 * targetList: the original target list (including junk attributes).
316 * cleanTupType: the tuple descriptor for the "clean" tuple (with
317 * junk attributes removed).
318 * cleanMap: A map with the correspondence between the non-junk
319 * attribute numbers of the "original" tuple and the
320 * attribute numbers of the "clean" tuple.
321 * resultSlot: tuple slot used to hold cleaned tuple.
322 * junkAttNo: not used by junkfilter code. Can be used by caller
323 * to remember the attno of a specific junk attribute
324 * (nodeModifyTable.c keeps the "ctid" or "wholerow"
328 typedef struct JunkFilter
332 TupleDesc jf_cleanTupType;
333 AttrNumber *jf_cleanMap;
334 TupleTableSlot *jf_resultSlot;
335 AttrNumber jf_junkAttNo;
339 * ResultRelInfo information
341 * Whenever we update an existing relation, we have to
342 * update indices on the relation, and perhaps also fire triggers.
343 * The ResultRelInfo class is used to hold all the information needed
344 * about a result relation, including indices.. -cim 10/15/89
346 * RangeTableIndex result relation's range table index
347 * RelationDesc relation descriptor for result relation
348 * NumIndices # of indices existing on result relation
349 * IndexRelationDescs array of relation descriptors for indices
350 * IndexRelationInfo array of key/attr info for indices
351 * TrigDesc triggers to be fired, if any
352 * TrigFunctions cached lookup info for trigger functions
353 * TrigWhenExprs array of trigger WHEN expr states
354 * TrigInstrument optional runtime measurements for triggers
355 * FdwRoutine FDW callback functions, if foreign table
356 * FdwState available to save private state of FDW
357 * usesFdwDirectModify true when modifying foreign table directly
358 * WithCheckOptions list of WithCheckOption's to be checked
359 * WithCheckOptionExprs list of WithCheckOption expr states
360 * ConstraintExprs array of constraint-checking expr states
361 * junkFilter for removing junk attributes from tuples
362 * projectReturning for computing a RETURNING list
363 * onConflictSetProj for computing ON CONFLICT DO UPDATE SET
364 * onConflictSetWhere list of ON CONFLICT DO UPDATE exprs (qual)
365 * PartitionCheck partition check expression
366 * PartitionCheckExpr partition check expression state
369 typedef struct ResultRelInfo
372 Index ri_RangeTableIndex;
373 Relation ri_RelationDesc;
375 RelationPtr ri_IndexRelationDescs;
376 IndexInfo **ri_IndexRelationInfo;
377 TriggerDesc *ri_TrigDesc;
378 FmgrInfo *ri_TrigFunctions;
379 ExprState **ri_TrigWhenExprs;
380 Instrumentation *ri_TrigInstrument;
381 struct FdwRoutine *ri_FdwRoutine;
383 bool ri_usesFdwDirectModify;
384 List *ri_WithCheckOptions;
385 List *ri_WithCheckOptionExprs;
386 ExprState **ri_ConstraintExprs;
387 JunkFilter *ri_junkFilter;
388 ProjectionInfo *ri_projectReturning;
389 ProjectionInfo *ri_onConflictSetProj;
390 ExprState *ri_onConflictSetWhere;
391 List *ri_PartitionCheck;
392 ExprState *ri_PartitionCheckExpr;
393 Relation ri_PartitionRoot;
399 * Master working state for an Executor invocation
402 typedef struct EState
406 /* Basic state for all query types: */
407 ScanDirection es_direction; /* current scan direction */
408 Snapshot es_snapshot; /* time qual to use */
409 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
410 List *es_range_table; /* List of RangeTblEntry */
411 PlannedStmt *es_plannedstmt; /* link to top of plan tree */
412 const char *es_sourceText; /* Source text from QueryDesc */
414 JunkFilter *es_junkFilter; /* top-level junk filter, if any */
416 /* If query can insert/delete tuples, the command ID to mark them with */
417 CommandId es_output_cid;
419 /* Info about target table(s) for insert/update/delete queries: */
420 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
421 int es_num_result_relations; /* length of array */
422 ResultRelInfo *es_result_relation_info; /* currently active array elt */
424 /* Stuff used for firing triggers: */
425 List *es_trig_target_relations; /* trigger-only ResultRelInfos */
426 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
427 TupleTableSlot *es_trig_oldtup_slot; /* for TriggerEnabled */
428 TupleTableSlot *es_trig_newtup_slot; /* for TriggerEnabled */
430 /* Parameter info: */
431 ParamListInfo es_param_list_info; /* values of external params */
432 ParamExecData *es_param_exec_vals; /* values of internal params */
434 /* Other working state: */
435 MemoryContext es_query_cxt; /* per-query context in which EState lives */
437 List *es_tupleTable; /* List of TupleTableSlots */
439 List *es_rowMarks; /* List of ExecRowMarks */
441 uint64 es_processed; /* # of tuples processed */
442 Oid es_lastoid; /* last oid processed (by INSERT) */
444 int es_top_eflags; /* eflags passed to ExecutorStart */
445 int es_instrument; /* OR of InstrumentOption flags */
446 bool es_finished; /* true when ExecutorFinish is done */
448 List *es_exprcontexts; /* List of ExprContexts within EState */
450 List *es_subplanstates; /* List of PlanState for SubPlans */
452 List *es_auxmodifytables; /* List of secondary ModifyTableStates */
455 * this ExprContext is for per-output-tuple operations, such as constraint
456 * checks and index-value computations. It will be reset for each output
457 * tuple. Note that it will be created only if needed.
459 ExprContext *es_per_tuple_exprcontext;
462 * These fields are for re-evaluating plan quals when an updated tuple is
463 * substituted in READ COMMITTED mode. es_epqTuple[] contains tuples that
464 * scan plan nodes should return instead of whatever they'd normally
465 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
466 * particular array entry is valid; and es_epqScanDone[] is state to
467 * remember if the tuple has been returned already. Arrays are of size
468 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
470 HeapTuple *es_epqTuple; /* array of EPQ substitute tuples */
471 bool *es_epqTupleSet; /* true if EPQ tuple is provided */
472 bool *es_epqScanDone; /* true if EPQ tuple has been fetched */
474 /* The per-query shared memory area to use for parallel execution. */
475 struct dsa_area *es_query_dsa;
481 * runtime representation of FOR [KEY] UPDATE/SHARE clauses
483 * When doing UPDATE, DELETE, or SELECT FOR [KEY] UPDATE/SHARE, we will have an
484 * ExecRowMark for each non-target relation in the query (except inheritance
485 * parent RTEs, which can be ignored at runtime). Virtual relations such as
486 * subqueries-in-FROM will have an ExecRowMark with relation == NULL. See
487 * PlanRowMark for details about most of the fields. In addition to fields
488 * directly derived from PlanRowMark, we store an activity flag (to denote
489 * inactive children of inheritance trees), curCtid, which is used by the
490 * WHERE CURRENT OF code, and ermExtra, which is available for use by the plan
491 * node that sources the relation (e.g., for a foreign table the FDW can use
492 * ermExtra to hold information).
494 * EState->es_rowMarks is a list of these structs.
496 typedef struct ExecRowMark
498 Relation relation; /* opened and suitably locked relation */
499 Oid relid; /* its OID (or InvalidOid, if subquery) */
500 Index rti; /* its range table index */
501 Index prti; /* parent range table index, if child */
502 Index rowmarkId; /* unique identifier for resjunk columns */
503 RowMarkType markType; /* see enum in nodes/plannodes.h */
504 LockClauseStrength strength; /* LockingClause's strength, or LCS_NONE */
505 LockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
506 bool ermActive; /* is this mark relevant for current tuple? */
507 ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
508 void *ermExtra; /* available for use by relation source node */
513 * additional runtime representation of FOR [KEY] UPDATE/SHARE clauses
515 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
516 * deal with. In addition to a pointer to the related entry in es_rowMarks,
517 * this struct carries the column number(s) of the resjunk columns associated
518 * with the rowmark (see comments for PlanRowMark for more detail). In the
519 * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
520 * each child plan, because the resjunk columns could be at different physical
521 * column positions in different subplans.
523 typedef struct ExecAuxRowMark
525 ExecRowMark *rowmark; /* related entry in es_rowMarks */
526 AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
527 AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
528 AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
532 /* ----------------------------------------------------------------
535 * All-in-memory tuple hash tables are used for a number of purposes.
537 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
538 * and tab_eq_funcs are non-cross-type equality operators for those types.
539 * Normally these are the only functions used, but FindTupleHashEntry()
540 * supports searching a hashtable using cross-data-type hashing. For that,
541 * the caller must supply hash functions for the LHS datatype as well as
542 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
543 * are set to point to the caller's function arrays while doing such a search.
544 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
545 * tab_eq_funcs respectively.
546 * ----------------------------------------------------------------
548 typedef struct TupleHashEntryData *TupleHashEntry;
549 typedef struct TupleHashTableData *TupleHashTable;
551 typedef struct TupleHashEntryData
553 MinimalTuple firstTuple; /* copy of first tuple in this group */
554 void *additional; /* user data */
555 uint32 status; /* hash status */
556 uint32 hash; /* hash value (cached) */
557 } TupleHashEntryData;
559 /* define paramters necessary to generate the tuple hash table interface */
560 #define SH_PREFIX tuplehash
561 #define SH_ELEMENT_TYPE TupleHashEntryData
562 #define SH_KEY_TYPE MinimalTuple
563 #define SH_SCOPE extern
565 #include "lib/simplehash.h"
567 typedef struct TupleHashTableData
569 tuplehash_hash *hashtab; /* underlying hash table */
570 int numCols; /* number of columns in lookup key */
571 AttrNumber *keyColIdx; /* attr numbers of key columns */
572 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
573 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
574 MemoryContext tablecxt; /* memory context containing table */
575 MemoryContext tempcxt; /* context for function evaluations */
576 Size entrysize; /* actual size to make each hash entry */
577 TupleTableSlot *tableslot; /* slot for referencing table entries */
578 /* The following fields are set transiently for each table search: */
579 TupleTableSlot *inputslot; /* current input tuple's slot */
580 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
581 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
582 uint32 hash_iv; /* hash-function IV */
583 } TupleHashTableData;
585 typedef tuplehash_iterator TupleHashIterator;
588 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
589 * Use ResetTupleHashIterator if the table can be frozen (in this case no
590 * explicit scan termination is needed).
592 #define InitTupleHashIterator(htable, iter) \
593 tuplehash_start_iterate(htable->hashtab, iter)
594 #define TermTupleHashIterator(iter) \
596 #define ResetTupleHashIterator(htable, iter) \
597 InitTupleHashIterator(htable, iter)
598 #define ScanTupleHashTable(htable, iter) \
599 tuplehash_iterate(htable->hashtab, iter)
602 /* ----------------------------------------------------------------
603 * Expression State Nodes
605 * Formerly, there was a separate executor expression state node corresponding
606 * to each node in a planned expression tree. That's no longer the case; for
607 * common expression node types, all the execution info is embedded into
608 * step(s) in a single ExprState node. But we still have a few executor state
609 * node types for selected expression node types, mostly those in which info
610 * has to be shared with other parts of the execution state tree.
611 * ----------------------------------------------------------------
615 * AggrefExprState node
618 typedef struct AggrefExprState
621 Aggref *aggref; /* expression plan node */
622 int aggno; /* ID number for agg within its plan node */
626 * WindowFuncExprState node
629 typedef struct WindowFuncExprState
632 WindowFunc *wfunc; /* expression plan node */
633 List *args; /* ExprStates for argument expressions */
634 ExprState *aggfilter; /* FILTER expression */
635 int wfuncno; /* ID number for wfunc within its plan node */
636 } WindowFuncExprState;
642 * State for evaluating a potentially set-returning expression (like FuncExpr
643 * or OpExpr). In some cases, like some of the expressions in ROWS FROM(...)
644 * the expression might not be a SRF, but nonetheless it uses the same
645 * machinery as SRFs; it will be treated as a SRF returning a single row.
648 typedef struct SetExprState
651 Expr *expr; /* expression plan node */
652 List *args; /* ExprStates for argument expressions */
655 * In ROWS FROM, functions can be inlined, removing the FuncExpr normally
656 * inside. In such a case this is the compiled expression (which cannot
657 * return a set), which'll be evaluated using regular ExecEvalExpr().
659 ExprState *elidedFuncState;
662 * Function manager's lookup info for the target function. If func.fn_oid
663 * is InvalidOid, we haven't initialized it yet (nor any of the following
664 * fields, except funcReturnsSet).
669 * For a set-returning function (SRF) that returns a tuplestore, we keep
670 * the tuplestore here and dole out the result rows one at a time. The
671 * slot holds the row currently being returned.
673 Tuplestorestate *funcResultStore;
674 TupleTableSlot *funcResultSlot;
677 * In some cases we need to compute a tuple descriptor for the function's
678 * output. If so, it's stored here.
680 TupleDesc funcResultDesc;
681 bool funcReturnsTuple; /* valid when funcResultDesc isn't
685 * Remember whether the function is declared to return a set. This is set
686 * by ExecInitExpr, and is valid even before the FmgrInfo is set up.
691 * setArgsValid is true when we are evaluating a set-returning function
692 * that uses value-per-call mode and we are in the middle of a call
693 * series; we want to pass the same argument values to the function again
694 * (and again, until it returns ExprEndResult). This indicates that
695 * fcinfo_data already contains valid argument data.
700 * Flag to remember whether we have registered a shutdown callback for
701 * this SetExprState. We do so only if funcResultStore or setArgsValid
702 * has been set at least once (since all the callback is for is to release
703 * the tuplestore or clear setArgsValid).
705 bool shutdown_reg; /* a shutdown callback is registered */
708 * Call parameter structure for the function. This has been initialized
709 * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
710 * argument values between calls, when setArgsValid is true.
712 FunctionCallInfoData fcinfo_data;
719 typedef struct SubPlanState
722 SubPlan *subplan; /* expression plan node */
723 struct PlanState *planstate; /* subselect plan's state tree */
724 struct PlanState *parent; /* parent plan node's state tree */
725 ExprState *testexpr; /* state of combining expression */
726 List *args; /* states of argument expression(s) */
727 HeapTuple curTuple; /* copy of most recent tuple from subplan */
728 Datum curArray; /* most recent array from ARRAY() subplan */
729 /* these are used when hashing the subselect's output: */
730 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
731 ProjectionInfo *projRight; /* for projecting subselect output */
732 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
733 TupleHashTable hashnulls; /* hash table for rows with null(s) */
734 bool havehashrows; /* TRUE if hashtable is not empty */
735 bool havenullrows; /* TRUE if hashnulls is not empty */
736 MemoryContext hashtablecxt; /* memory context containing hash tables */
737 MemoryContext hashtempcxt; /* temp memory context for hash tables */
738 ExprContext *innerecontext; /* econtext for computing inner tuples */
739 AttrNumber *keyColIdx; /* control data for hash tables */
740 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
741 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
742 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
743 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
747 * AlternativeSubPlanState node
750 typedef struct AlternativeSubPlanState
753 AlternativeSubPlan *subplan; /* expression plan node */
754 List *subplans; /* SubPlanStates of alternative subplans */
755 int active; /* list index of the one we're using */
756 } AlternativeSubPlanState;
759 * DomainConstraintState - one item to check during CoerceToDomain
761 * Note: we consider this to be part of an ExprState tree, so we give it
762 * a name following the xxxState convention. But there's no directly
763 * associated plan-tree node.
765 typedef enum DomainConstraintType
767 DOM_CONSTRAINT_NOTNULL,
769 } DomainConstraintType;
771 typedef struct DomainConstraintState
774 DomainConstraintType constrainttype; /* constraint type */
775 char *name; /* name of constraint (for error msgs) */
776 Expr *check_expr; /* for CHECK, a boolean expression */
777 ExprState *check_exprstate; /* check_expr's eval state, or NULL */
778 } DomainConstraintState;
781 /* ----------------------------------------------------------------
782 * Executor State Trees
784 * An executing query has a PlanState tree paralleling the Plan tree
785 * that describes the plan.
786 * ----------------------------------------------------------------
792 * We never actually instantiate any PlanState nodes; this is just the common
793 * abstract superclass for all PlanState-type nodes.
796 typedef struct PlanState
800 Plan *plan; /* associated Plan node */
802 EState *state; /* at execution time, states of individual
803 * nodes point to one EState for the whole
806 Instrumentation *instrument; /* Optional runtime stats for this node */
807 WorkerInstrumentation *worker_instrument; /* per-worker instrumentation */
810 * Common structural data for all Plan types. These links to subsidiary
811 * state trees parallel links in the associated plan tree (except for the
812 * subPlan list, which does not exist in the plan tree).
814 ExprState *qual; /* boolean qual condition */
815 struct PlanState *lefttree; /* input plan tree(s) */
816 struct PlanState *righttree;
817 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
819 List *subPlan; /* SubPlanState nodes in my expressions */
822 * State for management of parameter-change-driven rescanning
824 Bitmapset *chgParam; /* set of IDs of changed Params */
827 * Other run-time state needed by most if not all node types.
829 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
830 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
831 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
835 * these are defined to avoid confusion problems with "left"
836 * and "right" and "inner" and "outer". The convention is that
837 * the "left" plan is the "outer" plan and the "right" plan is
838 * the inner plan, but these make the code more readable.
841 #define innerPlanState(node) (((PlanState *)(node))->righttree)
842 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
844 /* Macros for inline access to certain instrumentation counters */
845 #define InstrCountFiltered1(node, delta) \
847 if (((PlanState *)(node))->instrument) \
848 ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
850 #define InstrCountFiltered2(node, delta) \
852 if (((PlanState *)(node))->instrument) \
853 ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
857 * EPQState is state for executing an EvalPlanQual recheck on a candidate
858 * tuple in ModifyTable or LockRows. The estate and planstate fields are
861 typedef struct EPQState
863 EState *estate; /* subsidiary EState */
864 PlanState *planstate; /* plan state tree ready to be executed */
865 TupleTableSlot *origslot; /* original output tuple to be rechecked */
866 Plan *plan; /* plan tree to be executed */
867 List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
868 int epqParam; /* ID of Param to force scan node re-eval */
873 * ResultState information
876 typedef struct ResultState
878 PlanState ps; /* its first field is NodeTag */
879 ExprState *resconstantqual;
880 bool rs_done; /* are we done? */
881 bool rs_checkqual; /* do we need to check the qual? */
885 * ProjectSetState information
887 * Note: at least one of the "elems" will be a SetExprState; the rest are
888 * regular ExprStates.
891 typedef struct ProjectSetState
893 PlanState ps; /* its first field is NodeTag */
894 Node **elems; /* array of expression states */
895 ExprDoneCond *elemdone; /* array of per-SRF is-done states */
896 int nelems; /* length of elemdone[] array */
897 bool pending_srf_tuples; /* still evaluating srfs in tlist? */
901 * ModifyTableState information
904 typedef struct ModifyTableState
906 PlanState ps; /* its first field is NodeTag */
907 CmdType operation; /* INSERT, UPDATE, or DELETE */
908 bool canSetTag; /* do we set the command tag/es_processed? */
909 bool mt_done; /* are we done? */
910 PlanState **mt_plans; /* subplans (one per target rel) */
911 int mt_nplans; /* number of plans in the array */
912 int mt_whichplan; /* which one is being executed (0..n-1) */
913 ResultRelInfo *resultRelInfo; /* per-subplan target relations */
914 List **mt_arowmarks; /* per-subplan ExecAuxRowMark lists */
915 EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
916 bool fireBSTriggers; /* do we need to fire stmt triggers? */
917 OnConflictAction mt_onconflict; /* ON CONFLICT type */
918 List *mt_arbiterindexes; /* unique index OIDs to arbitrate
920 TupleTableSlot *mt_existing; /* slot to store existing target tuple in */
921 List *mt_excludedtlist; /* the excluded pseudo relation's
923 TupleTableSlot *mt_conflproj; /* CONFLICT ... SET ... projection
925 struct PartitionDispatchData **mt_partition_dispatch_info;
926 /* Tuple-routing support info */
927 int mt_num_dispatch; /* Number of entries in the above
929 int mt_num_partitions; /* Number of members in the
930 * following arrays */
931 ResultRelInfo *mt_partitions; /* Per partition result relation */
932 TupleConversionMap **mt_partition_tupconv_maps;
933 /* Per partition tuple conversion map */
934 TupleTableSlot *mt_partition_tuple_slot;
938 * AppendState information
940 * nplans how many plans are in the array
941 * whichplan which plan is being executed (0 .. n-1)
944 typedef struct AppendState
946 PlanState ps; /* its first field is NodeTag */
947 PlanState **appendplans; /* array of PlanStates for my inputs */
953 * MergeAppendState information
955 * nplans how many plans are in the array
956 * nkeys number of sort key columns
957 * sortkeys sort keys in SortSupport representation
958 * slots current output tuple of each subplan
959 * heap heap of active tuples
960 * initialized true if we have fetched first tuple from each subplan
963 typedef struct MergeAppendState
965 PlanState ps; /* its first field is NodeTag */
966 PlanState **mergeplans; /* array of PlanStates for my inputs */
969 SortSupport ms_sortkeys; /* array of length ms_nkeys */
970 TupleTableSlot **ms_slots; /* array of length ms_nplans */
971 struct binaryheap *ms_heap; /* binary heap of slot indices */
972 bool ms_initialized; /* are subplans started? */
976 * RecursiveUnionState information
978 * RecursiveUnionState is used for performing a recursive union.
980 * recursing T when we're done scanning the non-recursive term
981 * intermediate_empty T if intermediate_table is currently empty
982 * working_table working table (to be scanned by recursive term)
983 * intermediate_table current recursive output (next generation of WT)
986 typedef struct RecursiveUnionState
988 PlanState ps; /* its first field is NodeTag */
990 bool intermediate_empty;
991 Tuplestorestate *working_table;
992 Tuplestorestate *intermediate_table;
993 /* Remaining fields are unused in UNION ALL case */
994 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
995 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
996 MemoryContext tempContext; /* short-term context for comparisons */
997 TupleHashTable hashtable; /* hash table for tuples already seen */
998 MemoryContext tableContext; /* memory context containing hash table */
999 } RecursiveUnionState;
1002 * BitmapAndState information
1005 typedef struct BitmapAndState
1007 PlanState ps; /* its first field is NodeTag */
1008 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1009 int nplans; /* number of input plans */
1013 * BitmapOrState information
1016 typedef struct BitmapOrState
1018 PlanState ps; /* its first field is NodeTag */
1019 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1020 int nplans; /* number of input plans */
1023 /* ----------------------------------------------------------------
1024 * Scan State Information
1025 * ----------------------------------------------------------------
1029 * ScanState information
1031 * ScanState extends PlanState for node types that represent
1032 * scans of an underlying relation. It can also be used for nodes
1033 * that scan the output of an underlying plan node --- in that case,
1034 * only ScanTupleSlot is actually useful, and it refers to the tuple
1035 * retrieved from the subplan.
1037 * currentRelation relation being scanned (NULL if none)
1038 * currentScanDesc current scan descriptor for scan (NULL if none)
1039 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
1042 typedef struct ScanState
1044 PlanState ps; /* its first field is NodeTag */
1045 Relation ss_currentRelation;
1046 HeapScanDesc ss_currentScanDesc;
1047 TupleTableSlot *ss_ScanTupleSlot;
1051 * SeqScanState information
1054 typedef struct SeqScanState
1056 ScanState ss; /* its first field is NodeTag */
1057 Size pscan_len; /* size of parallel heap scan descriptor */
1061 * SampleScanState information
1064 typedef struct SampleScanState
1067 List *args; /* expr states for TABLESAMPLE params */
1068 ExprState *repeatable; /* expr state for REPEATABLE expr */
1069 /* use struct pointer to avoid including tsmapi.h here */
1070 struct TsmRoutine *tsmroutine; /* descriptor for tablesample method */
1071 void *tsm_state; /* tablesample method can keep state here */
1072 bool use_bulkread; /* use bulkread buffer access strategy? */
1073 bool use_pagemode; /* use page-at-a-time visibility checking? */
1074 bool begun; /* false means need to call BeginSampleScan */
1075 uint32 seed; /* random seed */
1079 * These structs store information about index quals that don't have simple
1080 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1085 ScanKey scan_key; /* scankey to put value into */
1086 ExprState *key_expr; /* expr to evaluate to get value */
1087 bool key_toastable; /* is expr's result a toastable datatype? */
1088 } IndexRuntimeKeyInfo;
1092 ScanKey scan_key; /* scankey to put value into */
1093 ExprState *array_expr; /* expr to evaluate to get array value */
1094 int next_elem; /* next array element to use */
1095 int num_elems; /* number of elems in current array value */
1096 Datum *elem_values; /* array of num_elems Datums */
1097 bool *elem_nulls; /* array of num_elems is-null flags */
1098 } IndexArrayKeyInfo;
1101 * IndexScanState information
1103 * indexqualorig execution state for indexqualorig expressions
1104 * indexorderbyorig execution state for indexorderbyorig expressions
1105 * ScanKeys Skey structures for index quals
1106 * NumScanKeys number of ScanKeys
1107 * OrderByKeys Skey structures for index ordering operators
1108 * NumOrderByKeys number of OrderByKeys
1109 * RuntimeKeys info about Skeys that must be evaluated at runtime
1110 * NumRuntimeKeys number of RuntimeKeys
1111 * RuntimeKeysReady true if runtime Skeys have been computed
1112 * RuntimeContext expr context for evaling runtime Skeys
1113 * RelationDesc index relation descriptor
1114 * ScanDesc index scan descriptor
1116 * ReorderQueue tuples that need reordering due to re-check
1117 * ReachedEnd have we fetched all tuples from index already?
1118 * OrderByValues values of ORDER BY exprs of last fetched tuple
1119 * OrderByNulls null flags for OrderByValues
1120 * SortSupport for reordering ORDER BY exprs
1121 * OrderByTypByVals is the datatype of order by expression pass-by-value?
1122 * OrderByTypLens typlens of the datatypes of order by expressions
1123 * pscan_len size of parallel index scan descriptor
1126 typedef struct IndexScanState
1128 ScanState ss; /* its first field is NodeTag */
1129 ExprState *indexqualorig;
1130 List *indexorderbyorig;
1131 ScanKey iss_ScanKeys;
1132 int iss_NumScanKeys;
1133 ScanKey iss_OrderByKeys;
1134 int iss_NumOrderByKeys;
1135 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1136 int iss_NumRuntimeKeys;
1137 bool iss_RuntimeKeysReady;
1138 ExprContext *iss_RuntimeContext;
1139 Relation iss_RelationDesc;
1140 IndexScanDesc iss_ScanDesc;
1142 /* These are needed for re-checking ORDER BY expr ordering */
1143 pairingheap *iss_ReorderQueue;
1144 bool iss_ReachedEnd;
1145 Datum *iss_OrderByValues;
1146 bool *iss_OrderByNulls;
1147 SortSupport iss_SortSupport;
1148 bool *iss_OrderByTypByVals;
1149 int16 *iss_OrderByTypLens;
1154 * IndexOnlyScanState information
1156 * indexqual execution state for indexqual expressions
1157 * ScanKeys Skey structures for index quals
1158 * NumScanKeys number of ScanKeys
1159 * OrderByKeys Skey structures for index ordering operators
1160 * NumOrderByKeys number of OrderByKeys
1161 * RuntimeKeys info about Skeys that must be evaluated at runtime
1162 * NumRuntimeKeys number of RuntimeKeys
1163 * RuntimeKeysReady true if runtime Skeys have been computed
1164 * RuntimeContext expr context for evaling runtime Skeys
1165 * RelationDesc index relation descriptor
1166 * ScanDesc index scan descriptor
1167 * VMBuffer buffer in use for visibility map testing, if any
1168 * HeapFetches number of tuples we were forced to fetch from heap
1169 * ioss_PscanLen Size of parallel index-only scan descriptor
1172 typedef struct IndexOnlyScanState
1174 ScanState ss; /* its first field is NodeTag */
1175 ExprState *indexqual;
1176 ScanKey ioss_ScanKeys;
1177 int ioss_NumScanKeys;
1178 ScanKey ioss_OrderByKeys;
1179 int ioss_NumOrderByKeys;
1180 IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1181 int ioss_NumRuntimeKeys;
1182 bool ioss_RuntimeKeysReady;
1183 ExprContext *ioss_RuntimeContext;
1184 Relation ioss_RelationDesc;
1185 IndexScanDesc ioss_ScanDesc;
1186 Buffer ioss_VMBuffer;
1187 long ioss_HeapFetches;
1189 } IndexOnlyScanState;
1192 * BitmapIndexScanState information
1194 * result bitmap to return output into, or NULL
1195 * ScanKeys Skey structures for index quals
1196 * NumScanKeys number of ScanKeys
1197 * RuntimeKeys info about Skeys that must be evaluated at runtime
1198 * NumRuntimeKeys number of RuntimeKeys
1199 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1200 * NumArrayKeys number of ArrayKeys
1201 * RuntimeKeysReady true if runtime Skeys have been computed
1202 * RuntimeContext expr context for evaling runtime Skeys
1203 * RelationDesc index relation descriptor
1204 * ScanDesc index scan descriptor
1207 typedef struct BitmapIndexScanState
1209 ScanState ss; /* its first field is NodeTag */
1210 TIDBitmap *biss_result;
1211 ScanKey biss_ScanKeys;
1212 int biss_NumScanKeys;
1213 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1214 int biss_NumRuntimeKeys;
1215 IndexArrayKeyInfo *biss_ArrayKeys;
1216 int biss_NumArrayKeys;
1217 bool biss_RuntimeKeysReady;
1218 ExprContext *biss_RuntimeContext;
1219 Relation biss_RelationDesc;
1220 IndexScanDesc biss_ScanDesc;
1221 } BitmapIndexScanState;
1224 * SharedBitmapState information
1226 * BM_INITIAL TIDBitmap creation is not yet started, so first worker
1227 * to see this state will set the state to BM_INPROGRESS
1228 * and that process will be responsible for creating
1230 * BM_INPROGRESS TIDBitmap creation is in progress; workers need to
1231 * sleep until it's finished.
1232 * BM_FINISHED TIDBitmap creation is done, so now all workers can
1233 * proceed to iterate over TIDBitmap.
1241 } SharedBitmapState;
1244 * ParallelBitmapHeapState information
1245 * tbmiterator iterator for scanning current pages
1246 * prefetch_iterator iterator for prefetching ahead of current page
1247 * mutex mutual exclusion for the prefetching variable
1249 * prefetch_pages # pages prefetch iterator is ahead of current
1250 * prefetch_target current target prefetch distance
1251 * state current state of the TIDBitmap
1252 * cv conditional wait variable
1253 * phs_snapshot_data snapshot data shared to workers
1256 typedef struct ParallelBitmapHeapState
1258 dsa_pointer tbmiterator;
1259 dsa_pointer prefetch_iterator;
1262 int prefetch_target;
1263 SharedBitmapState state;
1264 ConditionVariable cv;
1265 char phs_snapshot_data[FLEXIBLE_ARRAY_MEMBER];
1266 } ParallelBitmapHeapState;
1269 * BitmapHeapScanState information
1271 * bitmapqualorig execution state for bitmapqualorig expressions
1272 * tbm bitmap obtained from child index scan(s)
1273 * tbmiterator iterator for scanning current pages
1274 * tbmres current-page data
1275 * exact_pages total number of exact pages retrieved
1276 * lossy_pages total number of lossy pages retrieved
1277 * prefetch_iterator iterator for prefetching ahead of current page
1278 * prefetch_pages # pages prefetch iterator is ahead of current
1279 * prefetch_target current target prefetch distance
1280 * prefetch_maximum maximum value for prefetch_target
1281 * pscan_len size of the shared memory for parallel bitmap
1282 * initialized is node is ready to iterate
1283 * shared_tbmiterator shared iterator
1284 * shared_prefetch_iterator shared iterator for prefetching
1285 * pstate shared state for parallel bitmap scan
1288 typedef struct BitmapHeapScanState
1290 ScanState ss; /* its first field is NodeTag */
1291 ExprState *bitmapqualorig;
1293 TBMIterator *tbmiterator;
1294 TBMIterateResult *tbmres;
1297 TBMIterator *prefetch_iterator;
1299 int prefetch_target;
1300 int prefetch_maximum;
1303 TBMSharedIterator *shared_tbmiterator;
1304 TBMSharedIterator *shared_prefetch_iterator;
1305 ParallelBitmapHeapState *pstate;
1306 } BitmapHeapScanState;
1309 * TidScanState information
1311 * tidexprs list of TidExpr structs (see nodeTidscan.c)
1312 * isCurrentOf scan has a CurrentOfExpr qual
1313 * NumTids number of tids in this scan
1314 * TidPtr index of currently fetched tid
1315 * TidList evaluated item pointers (array of size NumTids)
1316 * htup currently-fetched tuple, if any
1319 typedef struct TidScanState
1321 ScanState ss; /* its first field is NodeTag */
1323 bool tss_isCurrentOf;
1326 ItemPointerData *tss_TidList;
1327 HeapTupleData tss_htup;
1331 * SubqueryScanState information
1333 * SubqueryScanState is used for scanning a sub-query in the range table.
1334 * ScanTupleSlot references the current output tuple of the sub-query.
1337 typedef struct SubqueryScanState
1339 ScanState ss; /* its first field is NodeTag */
1341 } SubqueryScanState;
1344 * FunctionScanState information
1346 * Function nodes are used to scan the results of a
1347 * function appearing in FROM (typically a function returning set).
1349 * eflags node's capability flags
1350 * ordinality is this scan WITH ORDINALITY?
1351 * simple true if we have 1 function and no ordinality
1352 * ordinal current ordinal column value
1353 * nfuncs number of functions being executed
1354 * funcstates per-function execution states (private in
1355 * nodeFunctionscan.c)
1356 * argcontext memory context to evaluate function arguments in
1359 struct FunctionScanPerFuncState;
1361 typedef struct FunctionScanState
1363 ScanState ss; /* its first field is NodeTag */
1369 struct FunctionScanPerFuncState *funcstates; /* array of length
1371 MemoryContext argcontext;
1372 } FunctionScanState;
1375 * ValuesScanState information
1377 * ValuesScan nodes are used to scan the results of a VALUES list
1379 * rowcontext per-expression-list context
1380 * exprlists array of expression lists being evaluated
1381 * array_len size of array
1382 * curr_idx current array index (0-based)
1384 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1385 * expressions attached to the node. We create a second ExprContext,
1386 * rowcontext, in which to build the executor expression state for each
1387 * Values sublist. Resetting this context lets us get rid of expression
1388 * state for each row, avoiding major memory leakage over a long values list.
1391 typedef struct ValuesScanState
1393 ScanState ss; /* its first field is NodeTag */
1394 ExprContext *rowcontext;
1401 * TableFuncScanState node
1403 * Used in table-expression functions like XMLTABLE.
1406 typedef struct TableFuncScanState
1408 ScanState ss; /* its first field is NodeTag */
1409 ExprState *docexpr; /* state for document expression */
1410 ExprState *rowexpr; /* state for row-generating expression */
1411 List *colexprs; /* state for column-generating expression */
1412 List *coldefexprs; /* state for column default expressions */
1413 List *ns_names; /* list of str nodes with namespace names */
1414 List *ns_uris; /* list of states of namespace uri exprs */
1415 Bitmapset *notnulls; /* nullability flag for each output column */
1416 void *opaque; /* table builder private space */
1417 const struct TableFuncRoutine *routine; /* table builder methods */
1418 FmgrInfo *in_functions; /* input function for each column */
1419 Oid *typioparams; /* typioparam for each column */
1420 int64 ordinal; /* row number to be output next */
1421 MemoryContext perValueCxt; /* short life context for value evaluation */
1422 Tuplestorestate *tupstore; /* output tuple store */
1423 } TableFuncScanState;
1426 * CteScanState information
1428 * CteScan nodes are used to scan a CommonTableExpr query.
1430 * Multiple CteScan nodes can read out from the same CTE query. We use
1431 * a tuplestore to hold rows that have been read from the CTE query but
1432 * not yet consumed by all readers.
1435 typedef struct CteScanState
1437 ScanState ss; /* its first field is NodeTag */
1438 int eflags; /* capability flags to pass to tuplestore */
1439 int readptr; /* index of my tuplestore read pointer */
1440 PlanState *cteplanstate; /* PlanState for the CTE query itself */
1441 /* Link to the "leader" CteScanState (possibly this same node) */
1442 struct CteScanState *leader;
1443 /* The remaining fields are only valid in the "leader" CteScanState */
1444 Tuplestorestate *cte_table; /* rows already read from the CTE query */
1445 bool eof_cte; /* reached end of CTE query? */
1449 * WorkTableScanState information
1451 * WorkTableScan nodes are used to scan the work table created by
1452 * a RecursiveUnion node. We locate the RecursiveUnion node
1453 * during executor startup.
1456 typedef struct WorkTableScanState
1458 ScanState ss; /* its first field is NodeTag */
1459 RecursiveUnionState *rustate;
1460 } WorkTableScanState;
1463 * ForeignScanState information
1465 * ForeignScan nodes are used to scan foreign-data tables.
1468 typedef struct ForeignScanState
1470 ScanState ss; /* its first field is NodeTag */
1471 ExprState *fdw_recheck_quals; /* original quals not in ss.ps.qual */
1472 Size pscan_len; /* size of parallel coordination information */
1473 /* use struct pointer to avoid including fdwapi.h here */
1474 struct FdwRoutine *fdwroutine;
1475 void *fdw_state; /* foreign-data wrapper can keep state here */
1479 * CustomScanState information
1481 * CustomScan nodes are used to execute custom code within executor.
1483 * Core code must avoid assuming that the CustomScanState is only as large as
1484 * the structure declared here; providers are allowed to make it the first
1485 * element in a larger structure, and typically would need to do so. The
1486 * struct is actually allocated by the CreateCustomScanState method associated
1487 * with the plan node. Any additional fields can be initialized there, or in
1488 * the BeginCustomScan method.
1491 struct CustomExecMethods;
1493 typedef struct CustomScanState
1496 uint32 flags; /* mask of CUSTOMPATH_* flags, see
1497 * nodes/extensible.h */
1498 List *custom_ps; /* list of child PlanState nodes, if any */
1499 Size pscan_len; /* size of parallel coordination information */
1500 const struct CustomExecMethods *methods;
1503 /* ----------------------------------------------------------------
1504 * Join State Information
1505 * ----------------------------------------------------------------
1509 * JoinState information
1511 * Superclass for state nodes of join plans.
1514 typedef struct JoinState
1518 ExprState *joinqual; /* JOIN quals (in addition to ps.qual) */
1522 * NestLoopState information
1524 * NeedNewOuter true if need new outer tuple on next call
1525 * MatchedOuter true if found a join match for current outer tuple
1526 * NullInnerTupleSlot prepared null tuple for left outer joins
1529 typedef struct NestLoopState
1531 JoinState js; /* its first field is NodeTag */
1532 bool nl_NeedNewOuter;
1533 bool nl_MatchedOuter;
1534 TupleTableSlot *nl_NullInnerTupleSlot;
1538 * MergeJoinState information
1540 * NumClauses number of mergejoinable join clauses
1541 * Clauses info for each mergejoinable clause
1542 * JoinState current state of ExecMergeJoin state machine
1543 * ExtraMarks true to issue extra Mark operations on inner scan
1544 * ConstFalseJoin true if we have a constant-false joinqual
1545 * FillOuter true if should emit unjoined outer tuples anyway
1546 * FillInner true if should emit unjoined inner tuples anyway
1547 * MatchedOuter true if found a join match for current outer tuple
1548 * MatchedInner true if found a join match for current inner tuple
1549 * OuterTupleSlot slot in tuple table for cur outer tuple
1550 * InnerTupleSlot slot in tuple table for cur inner tuple
1551 * MarkedTupleSlot slot in tuple table for marked tuple
1552 * NullOuterTupleSlot prepared null tuple for right outer joins
1553 * NullInnerTupleSlot prepared null tuple for left outer joins
1554 * OuterEContext workspace for computing outer tuple's join values
1555 * InnerEContext workspace for computing inner tuple's join values
1558 /* private in nodeMergejoin.c: */
1559 typedef struct MergeJoinClauseData *MergeJoinClause;
1561 typedef struct MergeJoinState
1563 JoinState js; /* its first field is NodeTag */
1565 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1568 bool mj_ConstFalseJoin;
1571 bool mj_MatchedOuter;
1572 bool mj_MatchedInner;
1573 TupleTableSlot *mj_OuterTupleSlot;
1574 TupleTableSlot *mj_InnerTupleSlot;
1575 TupleTableSlot *mj_MarkedTupleSlot;
1576 TupleTableSlot *mj_NullOuterTupleSlot;
1577 TupleTableSlot *mj_NullInnerTupleSlot;
1578 ExprContext *mj_OuterEContext;
1579 ExprContext *mj_InnerEContext;
1583 * HashJoinState information
1585 * hashclauses original form of the hashjoin condition
1586 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1587 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1588 * hj_HashOperators the join operators in the hashjoin condition
1589 * hj_HashTable hash table for the hashjoin
1590 * (NULL if table not built yet)
1591 * hj_CurHashValue hash value for current outer tuple
1592 * hj_CurBucketNo regular bucket# for current outer tuple
1593 * hj_CurSkewBucketNo skew bucket# for current outer tuple
1594 * hj_CurTuple last inner tuple matched to current outer
1595 * tuple, or NULL if starting search
1596 * (hj_CurXXX variables are undefined if
1597 * OuterTupleSlot is empty!)
1598 * hj_OuterTupleSlot tuple slot for outer tuples
1599 * hj_HashTupleSlot tuple slot for inner (hashed) tuples
1600 * hj_NullOuterTupleSlot prepared null tuple for right/full outer joins
1601 * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
1602 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1603 * hj_JoinState current state of ExecHashJoin state machine
1604 * hj_MatchedOuter true if found a join match for current outer
1605 * hj_OuterNotEmpty true if outer relation known not empty
1609 /* these structs are defined in executor/hashjoin.h: */
1610 typedef struct HashJoinTupleData *HashJoinTuple;
1611 typedef struct HashJoinTableData *HashJoinTable;
1613 typedef struct HashJoinState
1615 JoinState js; /* its first field is NodeTag */
1616 ExprState *hashclauses;
1617 List *hj_OuterHashKeys; /* list of ExprState nodes */
1618 List *hj_InnerHashKeys; /* list of ExprState nodes */
1619 List *hj_HashOperators; /* list of operator OIDs */
1620 HashJoinTable hj_HashTable;
1621 uint32 hj_CurHashValue;
1623 int hj_CurSkewBucketNo;
1624 HashJoinTuple hj_CurTuple;
1625 TupleTableSlot *hj_OuterTupleSlot;
1626 TupleTableSlot *hj_HashTupleSlot;
1627 TupleTableSlot *hj_NullOuterTupleSlot;
1628 TupleTableSlot *hj_NullInnerTupleSlot;
1629 TupleTableSlot *hj_FirstOuterTupleSlot;
1631 bool hj_MatchedOuter;
1632 bool hj_OuterNotEmpty;
1636 /* ----------------------------------------------------------------
1637 * Materialization State Information
1638 * ----------------------------------------------------------------
1642 * MaterialState information
1644 * materialize nodes are used to materialize the results
1645 * of a subplan into a temporary file.
1647 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1650 typedef struct MaterialState
1652 ScanState ss; /* its first field is NodeTag */
1653 int eflags; /* capability flags to pass to tuplestore */
1654 bool eof_underlying; /* reached end of underlying plan? */
1655 Tuplestorestate *tuplestorestate;
1659 * SortState information
1662 typedef struct SortState
1664 ScanState ss; /* its first field is NodeTag */
1665 bool randomAccess; /* need random access to sort output? */
1666 bool bounded; /* is the result set bounded? */
1667 int64 bound; /* if bounded, how many tuples are needed */
1668 bool sort_Done; /* sort completed yet? */
1669 bool bounded_Done; /* value of bounded we did the sort with */
1670 int64 bound_Done; /* value of bound we did the sort with */
1671 void *tuplesortstate; /* private state of tuplesort.c */
1674 /* ---------------------
1675 * GroupState information
1676 * ---------------------
1678 typedef struct GroupState
1680 ScanState ss; /* its first field is NodeTag */
1681 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1682 bool grp_done; /* indicates completion of Group scan */
1685 /* ---------------------
1686 * AggState information
1688 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1690 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1691 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1692 * input group during evaluation of an Agg node's output tuple(s). We
1693 * create a second ExprContext, tmpcontext, in which to evaluate input
1694 * expressions and run the aggregate transition functions.
1695 * ---------------------
1697 /* these structs are private in nodeAgg.c: */
1698 typedef struct AggStatePerAggData *AggStatePerAgg;
1699 typedef struct AggStatePerTransData *AggStatePerTrans;
1700 typedef struct AggStatePerGroupData *AggStatePerGroup;
1701 typedef struct AggStatePerPhaseData *AggStatePerPhase;
1703 typedef struct AggState
1705 ScanState ss; /* its first field is NodeTag */
1706 List *aggs; /* all Aggref nodes in targetlist & quals */
1707 int numaggs; /* length of list (could be zero!) */
1708 int numtrans; /* number of pertrans items */
1709 AggSplit aggsplit; /* agg-splitting mode, see nodes.h */
1710 AggStatePerPhase phase; /* pointer to current phase data */
1711 int numphases; /* number of phases */
1712 int current_phase; /* current phase number */
1713 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1714 AggStatePerAgg peragg; /* per-Aggref information */
1715 AggStatePerTrans pertrans; /* per-Trans state information */
1716 ExprContext **aggcontexts; /* econtexts for long-lived data (per GS) */
1717 ExprContext *tmpcontext; /* econtext for input expressions */
1718 AggStatePerTrans curpertrans; /* currently active trans state */
1719 bool input_done; /* indicates end of input */
1720 bool agg_done; /* indicates completion of Agg scan */
1721 int projected_set; /* The last projected grouping set */
1722 int current_set; /* The current grouping set being evaluated */
1723 Bitmapset *grouped_cols; /* grouped cols in current projection */
1724 List *all_grouped_cols; /* list of all grouped cols in DESC
1726 /* These fields are for grouping set phase data */
1727 int maxsets; /* The max number of sets in any phase */
1728 AggStatePerPhase phases; /* array of all phases */
1729 Tuplesortstate *sort_in; /* sorted input to phases > 0 */
1730 Tuplesortstate *sort_out; /* input is copied here for next phase */
1731 TupleTableSlot *sort_slot; /* slot for sort results */
1732 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1733 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1734 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1735 /* these fields are used in AGG_HASHED mode: */
1736 TupleHashTable hashtable; /* hash table with one entry per group */
1737 TupleTableSlot *hashslot; /* slot for loading hash table */
1738 int numhashGrpCols; /* number of columns in hash table */
1739 int largestGrpColIdx; /* largest column required for hashing */
1740 AttrNumber *hashGrpColIdxInput; /* and their indices in input slot */
1741 AttrNumber *hashGrpColIdxHash; /* indices for execGrouping in hashtbl */
1742 bool table_filled; /* hash table filled yet? */
1743 TupleHashIterator hashiter; /* for iterating through hash table */
1744 /* support for evaluation of agg inputs */
1745 TupleTableSlot *evalslot; /* slot for agg inputs */
1746 ProjectionInfo *evalproj; /* projection machinery */
1747 TupleDesc evaldesc; /* descriptor of input tuples */
1751 * WindowAggState information
1754 /* these structs are private in nodeWindowAgg.c: */
1755 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1756 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1758 typedef struct WindowAggState
1760 ScanState ss; /* its first field is NodeTag */
1762 /* these fields are filled in by ExecInitExpr: */
1763 List *funcs; /* all WindowFunc nodes in targetlist */
1764 int numfuncs; /* total number of window functions */
1765 int numaggs; /* number that are plain aggregates */
1767 WindowStatePerFunc perfunc; /* per-window-function information */
1768 WindowStatePerAgg peragg; /* per-plain-aggregate information */
1769 FmgrInfo *partEqfunctions; /* equality funcs for partition columns */
1770 FmgrInfo *ordEqfunctions; /* equality funcs for ordering columns */
1771 Tuplestorestate *buffer; /* stores rows of current partition */
1772 int current_ptr; /* read pointer # for current */
1773 int64 spooled_rows; /* total # of rows in buffer */
1774 int64 currentpos; /* position of current row in partition */
1775 int64 frameheadpos; /* current frame head position */
1776 int64 frametailpos; /* current frame tail position */
1777 /* use struct pointer to avoid including windowapi.h here */
1778 struct WindowObjectData *agg_winobj; /* winobj for aggregate
1780 int64 aggregatedbase; /* start row for current aggregates */
1781 int64 aggregatedupto; /* rows before this one are aggregated */
1783 int frameOptions; /* frame_clause options, see WindowDef */
1784 ExprState *startOffset; /* expression for starting bound offset */
1785 ExprState *endOffset; /* expression for ending bound offset */
1786 Datum startOffsetValue; /* result of startOffset evaluation */
1787 Datum endOffsetValue; /* result of endOffset evaluation */
1789 MemoryContext partcontext; /* context for partition-lifespan data */
1790 MemoryContext aggcontext; /* shared context for aggregate working data */
1791 MemoryContext curaggcontext; /* current aggregate's working data */
1792 ExprContext *tmpcontext; /* short-term evaluation context */
1794 bool all_first; /* true if the scan is starting */
1795 bool all_done; /* true if the scan is finished */
1796 bool partition_spooled; /* true if all tuples in current
1797 * partition have been spooled into
1799 bool more_partitions;/* true if there's more partitions after this
1801 bool framehead_valid;/* true if frameheadpos is known up to date
1802 * for current row */
1803 bool frametail_valid;/* true if frametailpos is known up to date
1804 * for current row */
1806 TupleTableSlot *first_part_slot; /* first tuple of current or next
1809 /* temporary slots for tuples fetched back from tuplestore */
1810 TupleTableSlot *agg_row_slot;
1811 TupleTableSlot *temp_slot_1;
1812 TupleTableSlot *temp_slot_2;
1816 * UniqueState information
1818 * Unique nodes are used "on top of" sort nodes to discard
1819 * duplicate tuples returned from the sort phase. Basically
1820 * all it does is compare the current tuple from the subplan
1821 * with the previously fetched tuple (stored in its result slot).
1822 * If the two are identical in all interesting fields, then
1823 * we just fetch another tuple from the sort and try again.
1826 typedef struct UniqueState
1828 PlanState ps; /* its first field is NodeTag */
1829 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1830 MemoryContext tempContext; /* short-term context for comparisons */
1834 * GatherState information
1836 * Gather nodes launch 1 or more parallel workers, run a subplan
1837 * in those workers, and collect the results.
1840 typedef struct GatherState
1842 PlanState ps; /* its first field is NodeTag */
1844 struct ParallelExecutorInfo *pei;
1847 int nworkers_launched;
1848 struct TupleQueueReader **reader;
1849 TupleTableSlot *funnel_slot;
1850 bool need_to_scan_locally;
1854 * GatherMergeState information
1856 * Gather merge nodes launch 1 or more parallel workers, run a
1857 * subplan which produces sorted output in each worker, and then
1858 * merge the results into a single sorted stream.
1861 struct GMReaderTuple;
1863 typedef struct GatherMergeState
1865 PlanState ps; /* its first field is NodeTag */
1867 struct ParallelExecutorInfo *pei;
1869 int nworkers_launched;
1870 struct TupleQueueReader **reader;
1872 TupleTableSlot **gm_slots;
1873 struct binaryheap *gm_heap; /* binary heap of slot indices */
1874 bool gm_initialized; /* gather merge initilized ? */
1875 bool need_to_scan_locally;
1877 SortSupport gm_sortkeys; /* array of length ms_nkeys */
1878 struct GMReaderTupleBuffer *gm_tuple_buffers; /* tuple buffer per
1883 * HashState information
1886 typedef struct HashState
1888 PlanState ps; /* its first field is NodeTag */
1889 HashJoinTable hashtable; /* hash table for the hashjoin */
1890 List *hashkeys; /* list of ExprState nodes */
1891 /* hashkeys is same as parent's hj_InnerHashKeys */
1895 * SetOpState information
1897 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1898 * Unique, since we have to count how many duplicates to return. But
1899 * we also support hashing, so this is really more like a cut-down
1903 /* this struct is private in nodeSetOp.c: */
1904 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1906 typedef struct SetOpState
1908 PlanState ps; /* its first field is NodeTag */
1909 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1910 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1911 bool setop_done; /* indicates completion of output scan */
1912 long numOutput; /* number of dups left to output */
1913 MemoryContext tempContext; /* short-term context for comparisons */
1914 /* these fields are used in SETOP_SORTED mode: */
1915 SetOpStatePerGroup pergroup; /* per-group working state */
1916 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1917 /* these fields are used in SETOP_HASHED mode: */
1918 TupleHashTable hashtable; /* hash table with one entry per group */
1919 MemoryContext tableContext; /* memory context containing hash table */
1920 bool table_filled; /* hash table filled yet? */
1921 TupleHashIterator hashiter; /* for iterating through hash table */
1925 * LockRowsState information
1927 * LockRows nodes are used to enforce FOR [KEY] UPDATE/SHARE locking.
1930 typedef struct LockRowsState
1932 PlanState ps; /* its first field is NodeTag */
1933 List *lr_arowMarks; /* List of ExecAuxRowMarks */
1934 EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
1935 HeapTuple *lr_curtuples; /* locked tuples (one entry per RT entry) */
1936 int lr_ntables; /* length of lr_curtuples[] array */
1940 * LimitState information
1942 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1943 * They just select the desired subrange of their subplan's output.
1945 * offset is the number of initial tuples to skip (0 does nothing).
1946 * count is the number of tuples to return after skipping the offset tuples.
1947 * If no limit count was specified, count is undefined and noCount is true.
1948 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1953 LIMIT_INITIAL, /* initial state for LIMIT node */
1954 LIMIT_RESCAN, /* rescan after recomputing parameters */
1955 LIMIT_EMPTY, /* there are no returnable rows */
1956 LIMIT_INWINDOW, /* have returned a row in the window */
1957 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1958 LIMIT_WINDOWEND, /* stepped off end of window */
1959 LIMIT_WINDOWSTART /* stepped off beginning of window */
1962 typedef struct LimitState
1964 PlanState ps; /* its first field is NodeTag */
1965 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1966 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1967 int64 offset; /* current OFFSET value */
1968 int64 count; /* current COUNT, if any */
1969 bool noCount; /* if true, ignore count */
1970 LimitStateCond lstate; /* state machine status, as above */
1971 int64 position; /* 1-based index of last tuple returned */
1972 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1975 #endif /* EXECNODES_H */