1 /*-------------------------------------------------------------------------
4 * definitions for executor state nodes
7 * Portions Copyright (c) 1996-2011, 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/skey.h"
20 #include "nodes/params.h"
21 #include "nodes/plannodes.h"
22 #include "nodes/tidbitmap.h"
23 #include "utils/hsearch.h"
24 #include "utils/rel.h"
25 #include "utils/snapshot.h"
26 #include "utils/tuplestore.h"
30 * IndexInfo information
32 * this struct holds the information needed to construct new index
33 * entries for a particular index. Used for both index_build and
34 * retail creation of index entries.
36 * NumIndexAttrs number of columns in this index
37 * KeyAttrNumbers underlying-rel attribute numbers used as keys
38 * (zeroes indicate expressions)
39 * Expressions expr trees for expression entries, or NIL if none
40 * ExpressionsState exec state for expressions, or NIL if none
41 * Predicate partial-index predicate, or NIL if none
42 * PredicateState exec state for predicate, or NIL if none
43 * ExclusionOps Per-column exclusion operators, or NULL if none
44 * ExclusionProcs Underlying function OIDs for ExclusionOps
45 * ExclusionStrats Opclass strategy numbers for ExclusionOps
46 * Unique is it a unique index?
47 * ReadyForInserts is it valid for inserts?
48 * Concurrent are we doing a concurrent index build?
49 * BrokenHotChain did we detect any broken HOT chains?
51 * ii_Concurrent and ii_BrokenHotChain are used only during index build;
52 * they're conventionally set to false otherwise.
55 typedef struct IndexInfo
59 AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS];
60 List *ii_Expressions; /* list of Expr */
61 List *ii_ExpressionsState; /* list of ExprState */
62 List *ii_Predicate; /* list of Expr */
63 List *ii_PredicateState; /* list of ExprState */
64 Oid *ii_ExclusionOps; /* array with one entry per column */
65 Oid *ii_ExclusionProcs; /* array with one entry per column */
66 uint16 *ii_ExclusionStrats; /* array with one entry per column */
68 bool ii_ReadyForInserts;
70 bool ii_BrokenHotChain;
76 * List of callbacks to be called at ExprContext shutdown.
79 typedef void (*ExprContextCallbackFunction) (Datum arg);
81 typedef struct ExprContext_CB
83 struct ExprContext_CB *next;
84 ExprContextCallbackFunction function;
91 * This class holds the "current context" information
92 * needed to evaluate expressions for doing tuple qualifications
93 * and tuple projections. For example, if an expression refers
94 * to an attribute in the current inner tuple then we need to know
95 * what the current inner tuple is and so we look at the expression
98 * There are two memory contexts associated with an ExprContext:
99 * * ecxt_per_query_memory is a query-lifespan context, typically the same
100 * context the ExprContext node itself is allocated in. This context
101 * can be used for purposes such as storing function call cache info.
102 * * ecxt_per_tuple_memory is a short-term context for expression results.
103 * As the name suggests, it will typically be reset once per tuple,
104 * before we begin to evaluate expressions for that tuple. Each
105 * ExprContext normally has its very own per-tuple memory context.
107 * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
108 * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
111 typedef struct ExprContext
115 /* Tuples that Var nodes in expression may refer to */
116 TupleTableSlot *ecxt_scantuple;
117 TupleTableSlot *ecxt_innertuple;
118 TupleTableSlot *ecxt_outertuple;
120 /* Memory contexts for expression evaluation --- see notes above */
121 MemoryContext ecxt_per_query_memory;
122 MemoryContext ecxt_per_tuple_memory;
124 /* Values to substitute for Param nodes in expression */
125 ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
126 ParamListInfo ecxt_param_list_info; /* for other param types */
129 * Values to substitute for Aggref nodes in the expressions of an Agg
130 * node, or for WindowFunc nodes within a WindowAgg node.
132 Datum *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
133 bool *ecxt_aggnulls; /* null flags for aggs/windowfuncs */
135 /* Value to substitute for CaseTestExpr nodes in expression */
136 Datum caseValue_datum;
137 bool caseValue_isNull;
139 /* Value to substitute for CoerceToDomainValue nodes in expression */
140 Datum domainValue_datum;
141 bool domainValue_isNull;
143 /* Link to containing EState (NULL if a standalone ExprContext) */
144 struct EState *ecxt_estate;
146 /* Functions to call back when ExprContext is shut down */
147 ExprContext_CB *ecxt_callbacks;
151 * Set-result status returned by ExecEvalExpr()
155 ExprSingleResult, /* expression does not return a set */
156 ExprMultipleResult, /* this result is an element of a set */
157 ExprEndResult /* there are no more elements in the set */
161 * Return modes for functions returning sets. Note values must be chosen
162 * as separate bits so that a bitmask can be formed to indicate supported
163 * modes. SFRM_Materialize_Random and SFRM_Materialize_Preferred are
164 * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
168 SFRM_ValuePerCall = 0x01, /* one value returned per call */
169 SFRM_Materialize = 0x02, /* result set instantiated in Tuplestore */
170 SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */
171 SFRM_Materialize_Preferred = 0x08 /* caller prefers Tuplestore */
172 } SetFunctionReturnMode;
175 * When calling a function that might return a set (multiple rows),
176 * a node of this type is passed as fcinfo->resultinfo to allow
177 * return status to be passed back. A function returning set should
178 * raise an error if no such resultinfo is provided.
180 typedef struct ReturnSetInfo
183 /* values set by caller: */
184 ExprContext *econtext; /* context function is being called in */
185 TupleDesc expectedDesc; /* tuple descriptor expected by caller */
186 int allowedModes; /* bitmask: return modes caller can handle */
187 /* result status from function (but pre-initialized by caller): */
188 SetFunctionReturnMode returnMode; /* actual return mode */
189 ExprDoneCond isDone; /* status for ValuePerCall mode */
190 /* fields filled by function in Materialize return mode: */
191 Tuplestorestate *setResult; /* holds the complete returned tuple set */
192 TupleDesc setDesc; /* actual descriptor for returned tuples */
196 * ProjectionInfo node information
198 * This is all the information needed to perform projections ---
199 * that is, form new tuples by evaluation of targetlist expressions.
200 * Nodes which need to do projections create one of these.
202 * ExecProject() evaluates the tlist, forms a tuple, and stores it
203 * in the given slot. Note that the result will be a "virtual" tuple
204 * unless ExecMaterializeSlot() is then called to force it to be
205 * converted to a physical tuple. The slot must have a tupledesc
206 * that matches the output of the tlist!
208 * The planner very often produces tlists that consist entirely of
209 * simple Var references (lower levels of a plan tree almost always
210 * look like that). And top-level tlists are often mostly Vars too.
211 * We therefore optimize execution of simple-Var tlist entries.
212 * The pi_targetlist list actually contains only the tlist entries that
213 * aren't simple Vars, while those that are Vars are processed using the
214 * varSlotOffsets/varNumbers/varOutputCols arrays.
216 * The lastXXXVar fields are used to optimize fetching of fields from
217 * input tuples: they let us do a slot_getsomeattrs() call to ensure
218 * that all needed attributes are extracted in one pass.
220 * targetlist target list for projection (non-Var expressions only)
221 * exprContext expression context in which to evaluate targetlist
222 * slot slot to place projection result in
223 * itemIsDone workspace array for ExecProject
224 * directMap true if varOutputCols[] is an identity map
225 * numSimpleVars number of simple Vars found in original tlist
226 * varSlotOffsets array indicating which slot each simple Var is from
227 * varNumbers array containing input attr numbers of simple Vars
228 * varOutputCols array containing output attr numbers of simple Vars
229 * lastInnerVar highest attnum from inner tuple slot (0 if none)
230 * lastOuterVar highest attnum from outer tuple slot (0 if none)
231 * lastScanVar highest attnum from scan tuple slot (0 if none)
234 typedef struct ProjectionInfo
238 ExprContext *pi_exprContext;
239 TupleTableSlot *pi_slot;
240 ExprDoneCond *pi_itemIsDone;
242 int pi_numSimpleVars;
243 int *pi_varSlotOffsets;
245 int *pi_varOutputCols;
254 * This class is used to store information regarding junk attributes.
255 * A junk attribute is an attribute in a tuple that is needed only for
256 * storing intermediate information in the executor, and does not belong
257 * in emitted tuples. For example, when we do an UPDATE query,
258 * the planner adds a "junk" entry to the targetlist so that the tuples
259 * returned to ExecutePlan() contain an extra attribute: the ctid of
260 * the tuple to be updated. This is needed to do the update, but we
261 * don't want the ctid to be part of the stored new tuple! So, we
262 * apply a "junk filter" to remove the junk attributes and form the
263 * real output tuple. The junkfilter code also provides routines to
264 * extract the values of the junk attribute(s) from the input tuple.
266 * targetList: the original target list (including junk attributes).
267 * cleanTupType: the tuple descriptor for the "clean" tuple (with
268 * junk attributes removed).
269 * cleanMap: A map with the correspondence between the non-junk
270 * attribute numbers of the "original" tuple and the
271 * attribute numbers of the "clean" tuple.
272 * resultSlot: tuple slot used to hold cleaned tuple.
273 * junkAttNo: not used by junkfilter code. Can be used by caller
274 * to remember the attno of a specific junk attribute
275 * (execMain.c stores the "ctid" attno here).
278 typedef struct JunkFilter
282 TupleDesc jf_cleanTupType;
283 AttrNumber *jf_cleanMap;
284 TupleTableSlot *jf_resultSlot;
285 AttrNumber jf_junkAttNo;
289 * ResultRelInfo information
291 * Whenever we update an existing relation, we have to
292 * update indices on the relation, and perhaps also fire triggers.
293 * The ResultRelInfo class is used to hold all the information needed
294 * about a result relation, including indices.. -cim 10/15/89
296 * RangeTableIndex result relation's range table index
297 * RelationDesc relation descriptor for result relation
298 * NumIndices # of indices existing on result relation
299 * IndexRelationDescs array of relation descriptors for indices
300 * IndexRelationInfo array of key/attr info for indices
301 * TrigDesc triggers to be fired, if any
302 * TrigFunctions cached lookup info for trigger functions
303 * TrigWhenExprs array of trigger WHEN expr states
304 * TrigInstrument optional runtime measurements for triggers
305 * ConstraintExprs array of constraint-checking expr states
306 * junkFilter for removing junk attributes from tuples
307 * projectReturning for computing a RETURNING list
310 typedef struct ResultRelInfo
313 Index ri_RangeTableIndex;
314 Relation ri_RelationDesc;
316 RelationPtr ri_IndexRelationDescs;
317 IndexInfo **ri_IndexRelationInfo;
318 TriggerDesc *ri_TrigDesc;
319 FmgrInfo *ri_TrigFunctions;
320 List **ri_TrigWhenExprs;
321 struct Instrumentation *ri_TrigInstrument;
322 List **ri_ConstraintExprs;
323 JunkFilter *ri_junkFilter;
324 ProjectionInfo *ri_projectReturning;
330 * Master working state for an Executor invocation
333 typedef struct EState
337 /* Basic state for all query types: */
338 ScanDirection es_direction; /* current scan direction */
339 Snapshot es_snapshot; /* time qual to use */
340 Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
341 List *es_range_table; /* List of RangeTblEntry */
342 PlannedStmt *es_plannedstmt; /* link to top of plan tree */
344 JunkFilter *es_junkFilter; /* top-level junk filter, if any */
346 /* If query can insert/delete tuples, the command ID to mark them with */
347 CommandId es_output_cid;
349 /* Info about target table(s) for insert/update/delete queries: */
350 ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
351 int es_num_result_relations; /* length of array */
352 ResultRelInfo *es_result_relation_info; /* currently active array elt */
354 /* Stuff used for firing triggers: */
355 List *es_trig_target_relations; /* trigger-only ResultRelInfos */
356 TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
357 TupleTableSlot *es_trig_oldtup_slot; /* for trigger old tuples */
359 /* Parameter info: */
360 ParamListInfo es_param_list_info; /* values of external params */
361 ParamExecData *es_param_exec_vals; /* values of internal params */
363 /* Other working state: */
364 MemoryContext es_query_cxt; /* per-query context in which EState lives */
366 List *es_tupleTable; /* List of TupleTableSlots */
368 List *es_rowMarks; /* List of ExecRowMarks */
370 uint32 es_processed; /* # of tuples processed */
371 Oid es_lastoid; /* last oid processed (by INSERT) */
373 int es_top_eflags; /* eflags passed to ExecutorStart */
374 int es_instrument; /* OR of InstrumentOption flags */
375 bool es_select_into; /* true if doing SELECT INTO */
376 bool es_into_oids; /* true to generate OIDs in SELECT INTO */
377 bool es_finished; /* true when ExecutorFinish is done */
379 List *es_exprcontexts; /* List of ExprContexts within EState */
381 List *es_subplanstates; /* List of PlanState for SubPlans */
383 List *es_auxmodifytables; /* List of secondary ModifyTableStates */
386 * this ExprContext is for per-output-tuple operations, such as constraint
387 * checks and index-value computations. It will be reset for each output
388 * tuple. Note that it will be created only if needed.
390 ExprContext *es_per_tuple_exprcontext;
393 * These fields are for re-evaluating plan quals when an updated tuple is
394 * substituted in READ COMMITTED mode. es_epqTuple[] contains tuples that
395 * scan plan nodes should return instead of whatever they'd normally
396 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
397 * particular array entry is valid; and es_epqScanDone[] is state to
398 * remember if the tuple has been returned already. Arrays are of size
399 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
401 HeapTuple *es_epqTuple; /* array of EPQ substitute tuples */
402 bool *es_epqTupleSet; /* true if EPQ tuple is provided */
403 bool *es_epqScanDone; /* true if EPQ tuple has been fetched */
409 * runtime representation of FOR UPDATE/SHARE clauses
411 * When doing UPDATE, DELETE, or SELECT FOR UPDATE/SHARE, we should have an
412 * ExecRowMark for each non-target relation in the query (except inheritance
413 * parent RTEs, which can be ignored at runtime). See PlanRowMark for details
414 * about most of the fields. In addition to fields directly derived from
415 * PlanRowMark, we store curCtid, which is used by the WHERE CURRENT OF code.
417 * EState->es_rowMarks is a list of these structs.
419 typedef struct ExecRowMark
421 Relation relation; /* opened and suitably locked relation */
422 Index rti; /* its range table index */
423 Index prti; /* parent range table index, if child */
424 Index rowmarkId; /* unique identifier for resjunk columns */
425 RowMarkType markType; /* see enum in nodes/plannodes.h */
426 bool noWait; /* NOWAIT option */
427 ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
432 * additional runtime representation of FOR UPDATE/SHARE clauses
434 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
435 * deal with. In addition to a pointer to the related entry in es_rowMarks,
436 * this struct carries the column number(s) of the resjunk columns associated
437 * with the rowmark (see comments for PlanRowMark for more detail). In the
438 * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
439 * each child plan, because the resjunk columns could be at different physical
440 * column positions in different subplans.
442 typedef struct ExecAuxRowMark
444 ExecRowMark *rowmark; /* related entry in es_rowMarks */
445 AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
446 AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
447 AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
451 /* ----------------------------------------------------------------
454 * All-in-memory tuple hash tables are used for a number of purposes.
456 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
457 * and tab_eq_funcs are non-cross-type equality operators for those types.
458 * Normally these are the only functions used, but FindTupleHashEntry()
459 * supports searching a hashtable using cross-data-type hashing. For that,
460 * the caller must supply hash functions for the LHS datatype as well as
461 * the cross-type equality operators to use. in_hash_funcs and cur_eq_funcs
462 * are set to point to the caller's function arrays while doing such a search.
463 * During LookupTupleHashEntry(), they point to tab_hash_funcs and
464 * tab_eq_funcs respectively.
465 * ----------------------------------------------------------------
467 typedef struct TupleHashEntryData *TupleHashEntry;
468 typedef struct TupleHashTableData *TupleHashTable;
470 typedef struct TupleHashEntryData
472 /* firstTuple must be the first field in this struct! */
473 MinimalTuple firstTuple; /* copy of first tuple in this group */
474 /* there may be additional data beyond the end of this struct */
475 } TupleHashEntryData; /* VARIABLE LENGTH STRUCT */
477 typedef struct TupleHashTableData
479 HTAB *hashtab; /* underlying dynahash table */
480 int numCols; /* number of columns in lookup key */
481 AttrNumber *keyColIdx; /* attr numbers of key columns */
482 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
483 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
484 MemoryContext tablecxt; /* memory context containing table */
485 MemoryContext tempcxt; /* context for function evaluations */
486 Size entrysize; /* actual size to make each hash entry */
487 TupleTableSlot *tableslot; /* slot for referencing table entries */
488 /* The following fields are set transiently for each table search: */
489 TupleTableSlot *inputslot; /* current input tuple's slot */
490 FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
491 FmgrInfo *cur_eq_funcs; /* equality functions for input vs. table */
492 } TupleHashTableData;
494 typedef HASH_SEQ_STATUS TupleHashIterator;
497 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
498 * Use ResetTupleHashIterator if the table can be frozen (in this case no
499 * explicit scan termination is needed).
501 #define InitTupleHashIterator(htable, iter) \
502 hash_seq_init(iter, (htable)->hashtab)
503 #define TermTupleHashIterator(iter) \
505 #define ResetTupleHashIterator(htable, iter) \
507 hash_freeze((htable)->hashtab); \
508 hash_seq_init(iter, (htable)->hashtab); \
510 #define ScanTupleHashTable(iter) \
511 ((TupleHashEntry) hash_seq_search(iter))
514 /* ----------------------------------------------------------------
515 * Expression State Trees
517 * Each executable expression tree has a parallel ExprState tree.
519 * Unlike PlanState, there is not an exact one-for-one correspondence between
520 * ExprState node types and Expr node types. Many Expr node types have no
521 * need for node-type-specific run-time state, and so they can use plain
522 * ExprState or GenericExprState as their associated ExprState node type.
523 * ----------------------------------------------------------------
529 * ExprState is the common superclass for all ExprState-type nodes.
531 * It can also be instantiated directly for leaf Expr nodes that need no
532 * local run-time state (such as Var, Const, or Param).
534 * To save on dispatch overhead, each ExprState node contains a function
535 * pointer to the routine to execute to evaluate the node.
539 typedef struct ExprState ExprState;
541 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
542 ExprContext *econtext,
544 ExprDoneCond *isDone);
549 Expr *expr; /* associated Expr node */
550 ExprStateEvalFunc evalfunc; /* routine to run to execute node */
554 * GenericExprState node
556 * This is used for Expr node types that need no local run-time state,
557 * but have one child Expr node.
560 typedef struct GenericExprState
563 ExprState *arg; /* state of my child node */
567 * AggrefExprState node
570 typedef struct AggrefExprState
573 List *args; /* states of argument expressions */
574 int aggno; /* ID number for agg within its plan node */
578 * WindowFuncExprState node
581 typedef struct WindowFuncExprState
584 List *args; /* states of argument expressions */
585 int wfuncno; /* ID number for wfunc within its plan node */
586 } WindowFuncExprState;
589 * ArrayRefExprState node
591 * Note: array types can be fixed-length (typlen > 0), but only when the
592 * element type is itself fixed-length. Otherwise they are varlena structures
593 * and have typlen = -1. In any case, an array type is never pass-by-value.
596 typedef struct ArrayRefExprState
599 List *refupperindexpr; /* states for child nodes */
600 List *reflowerindexpr;
602 ExprState *refassgnexpr;
603 int16 refattrlength; /* typlen of array type */
604 int16 refelemlength; /* typlen of the array element type */
605 bool refelembyval; /* is the element type pass-by-value? */
606 char refelemalign; /* typalign of the element type */
612 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
613 * and NullIf nodes; be careful to check what xprstate.expr is actually
617 typedef struct FuncExprState
620 List *args; /* states of argument expressions */
623 * Function manager's lookup info for the target function. If func.fn_oid
624 * is InvalidOid, we haven't initialized it yet (nor any of the following
630 * For a set-returning function (SRF) that returns a tuplestore, we keep
631 * the tuplestore here and dole out the result rows one at a time. The
632 * slot holds the row currently being returned.
634 Tuplestorestate *funcResultStore;
635 TupleTableSlot *funcResultSlot;
638 * In some cases we need to compute a tuple descriptor for the function's
639 * output. If so, it's stored here.
641 TupleDesc funcResultDesc;
642 bool funcReturnsTuple; /* valid when funcResultDesc isn't
646 * setArgsValid is true when we are evaluating a set-returning function
647 * that uses value-per-call mode and we are in the middle of a call
648 * series; we want to pass the same argument values to the function again
649 * (and again, until it returns ExprEndResult). This indicates that
650 * fcinfo_data already contains valid argument data.
655 * Flag to remember whether we found a set-valued argument to the
656 * function. This causes the function result to be a set as well. Valid
657 * only when setArgsValid is true or funcResultStore isn't NULL.
659 bool setHasSetArg; /* some argument returns a set */
662 * Flag to remember whether we have registered a shutdown callback for
663 * this FuncExprState. We do so only if funcResultStore or setArgsValid
664 * has been set at least once (since all the callback is for is to release
665 * the tuplestore or clear setArgsValid).
667 bool shutdown_reg; /* a shutdown callback is registered */
670 * Call parameter structure for the function. This has been initialized
671 * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
672 * argument values between calls, when setArgsValid is true.
674 FunctionCallInfoData fcinfo_data;
678 * ScalarArrayOpExprState node
680 * This is a FuncExprState plus some additional data.
683 typedef struct ScalarArrayOpExprState
685 FuncExprState fxprstate;
686 /* Cached info about array element type */
691 } ScalarArrayOpExprState;
697 typedef struct BoolExprState
700 List *args; /* states of argument expression(s) */
707 typedef struct SubPlanState
710 struct PlanState *planstate; /* subselect plan's state tree */
711 ExprState *testexpr; /* state of combining expression */
712 List *args; /* states of argument expression(s) */
713 HeapTuple curTuple; /* copy of most recent tuple from subplan */
714 /* these are used when hashing the subselect's output: */
715 ProjectionInfo *projLeft; /* for projecting lefthand exprs */
716 ProjectionInfo *projRight; /* for projecting subselect output */
717 TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
718 TupleHashTable hashnulls; /* hash table for rows with null(s) */
719 bool havehashrows; /* TRUE if hashtable is not empty */
720 bool havenullrows; /* TRUE if hashnulls is not empty */
721 MemoryContext hashtablecxt; /* memory context containing hash tables */
722 MemoryContext hashtempcxt; /* temp memory context for hash tables */
723 ExprContext *innerecontext; /* econtext for computing inner tuples */
724 AttrNumber *keyColIdx; /* control data for hash tables */
725 FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
726 FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
727 FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
728 FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
732 * AlternativeSubPlanState node
735 typedef struct AlternativeSubPlanState
738 List *subplans; /* states of alternative subplans */
739 int active; /* list index of the one we're using */
740 } AlternativeSubPlanState;
743 * FieldSelectState node
746 typedef struct FieldSelectState
749 ExprState *arg; /* input expression */
750 TupleDesc argdesc; /* tupdesc for most recent input */
754 * FieldStoreState node
757 typedef struct FieldStoreState
760 ExprState *arg; /* input tuple value */
761 List *newvals; /* new value(s) for field(s) */
762 TupleDesc argdesc; /* tupdesc for most recent input */
766 * CoerceViaIOState node
769 typedef struct CoerceViaIOState
772 ExprState *arg; /* input expression */
773 FmgrInfo outfunc; /* lookup info for source output function */
774 FmgrInfo infunc; /* lookup info for result input function */
775 Oid intypioparam; /* argument needed for input function */
779 * ArrayCoerceExprState node
782 typedef struct ArrayCoerceExprState
785 ExprState *arg; /* input array value */
786 Oid resultelemtype; /* element type of result array */
787 FmgrInfo elemfunc; /* lookup info for element coercion function */
788 /* use struct pointer to avoid including array.h here */
789 struct ArrayMapState *amstate; /* workspace for array_map */
790 } ArrayCoerceExprState;
793 * ConvertRowtypeExprState node
796 typedef struct ConvertRowtypeExprState
799 ExprState *arg; /* input tuple value */
800 TupleDesc indesc; /* tupdesc for source rowtype */
801 TupleDesc outdesc; /* tupdesc for result rowtype */
802 /* use "struct" so we needn't include tupconvert.h here */
803 struct TupleConversionMap *map;
805 } ConvertRowtypeExprState;
811 typedef struct CaseExprState
814 ExprState *arg; /* implicit equality comparison argument */
815 List *args; /* the arguments (list of WHEN clauses) */
816 ExprState *defresult; /* the default result (ELSE clause) */
823 typedef struct CaseWhenState
826 ExprState *expr; /* condition expression */
827 ExprState *result; /* substitution result */
831 * ArrayExprState node
833 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
837 typedef struct ArrayExprState
840 List *elements; /* states for child nodes */
841 int16 elemlength; /* typlen of the array element type */
842 bool elembyval; /* is the element type pass-by-value? */
843 char elemalign; /* typalign of the element type */
850 typedef struct RowExprState
853 List *args; /* the arguments */
854 TupleDesc tupdesc; /* descriptor for result tuples */
858 * RowCompareExprState node
861 typedef struct RowCompareExprState
864 List *largs; /* the left-hand input arguments */
865 List *rargs; /* the right-hand input arguments */
866 FmgrInfo *funcs; /* array of comparison function info */
867 Oid *collations; /* array of collations to use */
868 } RowCompareExprState;
871 * CoalesceExprState node
874 typedef struct CoalesceExprState
877 List *args; /* the arguments */
881 * MinMaxExprState node
884 typedef struct MinMaxExprState
887 List *args; /* the arguments */
888 FmgrInfo cfunc; /* lookup info for comparison func */
895 typedef struct XmlExprState
898 List *named_args; /* ExprStates for named arguments */
899 List *args; /* ExprStates for other arguments */
906 typedef struct NullTestState
909 ExprState *arg; /* input expression */
910 /* used only if input is of composite type: */
911 TupleDesc argdesc; /* tupdesc for most recent input */
915 * CoerceToDomainState node
918 typedef struct CoerceToDomainState
921 ExprState *arg; /* input expression */
922 /* Cached list of constraints that need to be checked */
923 List *constraints; /* list of DomainConstraintState nodes */
924 } CoerceToDomainState;
927 * DomainConstraintState - one item to check during CoerceToDomain
929 * Note: this is just a Node, and not an ExprState, because it has no
930 * corresponding Expr to link to. Nonetheless it is part of an ExprState
931 * tree, so we give it a name following the xxxState convention.
933 typedef enum DomainConstraintType
935 DOM_CONSTRAINT_NOTNULL,
937 } DomainConstraintType;
939 typedef struct DomainConstraintState
942 DomainConstraintType constrainttype; /* constraint type */
943 char *name; /* name of constraint (for error msgs) */
944 ExprState *check_expr; /* for CHECK, a boolean expression */
945 } DomainConstraintState;
948 /* ----------------------------------------------------------------
949 * Executor State Trees
951 * An executing query has a PlanState tree paralleling the Plan tree
952 * that describes the plan.
953 * ----------------------------------------------------------------
959 * We never actually instantiate any PlanState nodes; this is just the common
960 * abstract superclass for all PlanState-type nodes.
963 typedef struct PlanState
967 Plan *plan; /* associated Plan node */
969 EState *state; /* at execution time, states of individual
970 * nodes point to one EState for the whole
973 struct Instrumentation *instrument; /* Optional runtime stats for this
977 * Common structural data for all Plan types. These links to subsidiary
978 * state trees parallel links in the associated plan tree (except for the
979 * subPlan list, which does not exist in the plan tree).
981 List *targetlist; /* target list to be computed at this node */
982 List *qual; /* implicitly-ANDed qual conditions */
983 struct PlanState *lefttree; /* input plan tree(s) */
984 struct PlanState *righttree;
985 List *initPlan; /* Init SubPlanState nodes (un-correlated expr
987 List *subPlan; /* SubPlanState nodes in my expressions */
990 * State for management of parameter-change-driven rescanning
992 Bitmapset *chgParam; /* set of IDs of changed Params */
995 * Other run-time state needed by most if not all node types.
997 TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
998 ExprContext *ps_ExprContext; /* node's expression-evaluation context */
999 ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
1000 bool ps_TupFromTlist;/* state flag for processing set-valued
1001 * functions in targetlist */
1005 * these are defined to avoid confusion problems with "left"
1006 * and "right" and "inner" and "outer". The convention is that
1007 * the "left" plan is the "outer" plan and the "right" plan is
1008 * the inner plan, but these make the code more readable.
1011 #define innerPlanState(node) (((PlanState *)(node))->righttree)
1012 #define outerPlanState(node) (((PlanState *)(node))->lefttree)
1015 * EPQState is state for executing an EvalPlanQual recheck on a candidate
1016 * tuple in ModifyTable or LockRows. The estate and planstate fields are
1019 typedef struct EPQState
1021 EState *estate; /* subsidiary EState */
1022 PlanState *planstate; /* plan state tree ready to be executed */
1023 TupleTableSlot *origslot; /* original output tuple to be rechecked */
1024 Plan *plan; /* plan tree to be executed */
1025 List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
1026 int epqParam; /* ID of Param to force scan node re-eval */
1031 * ResultState information
1034 typedef struct ResultState
1036 PlanState ps; /* its first field is NodeTag */
1037 ExprState *resconstantqual;
1038 bool rs_done; /* are we done? */
1039 bool rs_checkqual; /* do we need to check the qual? */
1043 * ModifyTableState information
1046 typedef struct ModifyTableState
1048 PlanState ps; /* its first field is NodeTag */
1049 CmdType operation; /* INSERT, UPDATE, or DELETE */
1050 bool canSetTag; /* do we set the command tag/es_processed? */
1051 bool mt_done; /* are we done? */
1052 PlanState **mt_plans; /* subplans (one per target rel) */
1053 int mt_nplans; /* number of plans in the array */
1054 int mt_whichplan; /* which one is being executed (0..n-1) */
1055 ResultRelInfo *resultRelInfo; /* per-subplan target relations */
1056 List **mt_arowmarks; /* per-subplan ExecAuxRowMark lists */
1057 EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
1058 bool fireBSTriggers; /* do we need to fire stmt triggers? */
1062 * AppendState information
1064 * nplans how many plans are in the array
1065 * whichplan which plan is being executed (0 .. n-1)
1068 typedef struct AppendState
1070 PlanState ps; /* its first field is NodeTag */
1071 PlanState **appendplans; /* array of PlanStates for my inputs */
1077 * MergeAppendState information
1079 * nplans how many plans are in the array
1080 * nkeys number of sort key columns
1081 * scankeys sort keys in ScanKey representation
1082 * slots current output tuple of each subplan
1083 * heap heap of active tuples (represented as array indexes)
1084 * heap_size number of active heap entries
1085 * initialized true if we have fetched first tuple from each subplan
1086 * last_slot last subplan fetched from (which must be re-called)
1089 typedef struct MergeAppendState
1091 PlanState ps; /* its first field is NodeTag */
1092 PlanState **mergeplans; /* array of PlanStates for my inputs */
1095 ScanKey ms_scankeys; /* array of length ms_nkeys */
1096 TupleTableSlot **ms_slots; /* array of length ms_nplans */
1097 int *ms_heap; /* array of length ms_nplans */
1098 int ms_heap_size; /* current active length of ms_heap[] */
1099 bool ms_initialized; /* are subplans started? */
1100 int ms_last_slot; /* last subplan slot we returned from */
1104 * RecursiveUnionState information
1106 * RecursiveUnionState is used for performing a recursive union.
1108 * recursing T when we're done scanning the non-recursive term
1109 * intermediate_empty T if intermediate_table is currently empty
1110 * working_table working table (to be scanned by recursive term)
1111 * intermediate_table current recursive output (next generation of WT)
1114 typedef struct RecursiveUnionState
1116 PlanState ps; /* its first field is NodeTag */
1118 bool intermediate_empty;
1119 Tuplestorestate *working_table;
1120 Tuplestorestate *intermediate_table;
1121 /* Remaining fields are unused in UNION ALL case */
1122 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1123 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1124 MemoryContext tempContext; /* short-term context for comparisons */
1125 TupleHashTable hashtable; /* hash table for tuples already seen */
1126 MemoryContext tableContext; /* memory context containing hash table */
1127 } RecursiveUnionState;
1130 * BitmapAndState information
1133 typedef struct BitmapAndState
1135 PlanState ps; /* its first field is NodeTag */
1136 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1137 int nplans; /* number of input plans */
1141 * BitmapOrState information
1144 typedef struct BitmapOrState
1146 PlanState ps; /* its first field is NodeTag */
1147 PlanState **bitmapplans; /* array of PlanStates for my inputs */
1148 int nplans; /* number of input plans */
1151 /* ----------------------------------------------------------------
1152 * Scan State Information
1153 * ----------------------------------------------------------------
1157 * ScanState information
1159 * ScanState extends PlanState for node types that represent
1160 * scans of an underlying relation. It can also be used for nodes
1161 * that scan the output of an underlying plan node --- in that case,
1162 * only ScanTupleSlot is actually useful, and it refers to the tuple
1163 * retrieved from the subplan.
1165 * currentRelation relation being scanned (NULL if none)
1166 * currentScanDesc current scan descriptor for scan (NULL if none)
1167 * ScanTupleSlot pointer to slot in tuple table holding scan tuple
1170 typedef struct ScanState
1172 PlanState ps; /* its first field is NodeTag */
1173 Relation ss_currentRelation;
1174 HeapScanDesc ss_currentScanDesc;
1175 TupleTableSlot *ss_ScanTupleSlot;
1179 * SeqScan uses a bare ScanState as its state node, since it needs
1180 * no additional fields.
1182 typedef ScanState SeqScanState;
1185 * These structs store information about index quals that don't have simple
1186 * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
1191 ScanKey scan_key; /* scankey to put value into */
1192 ExprState *key_expr; /* expr to evaluate to get value */
1193 bool key_toastable; /* is expr's result a toastable datatype? */
1194 } IndexRuntimeKeyInfo;
1198 ScanKey scan_key; /* scankey to put value into */
1199 ExprState *array_expr; /* expr to evaluate to get array value */
1200 int next_elem; /* next array element to use */
1201 int num_elems; /* number of elems in current array value */
1202 Datum *elem_values; /* array of num_elems Datums */
1203 bool *elem_nulls; /* array of num_elems is-null flags */
1204 } IndexArrayKeyInfo;
1207 * IndexScanState information
1209 * indexqualorig execution state for indexqualorig expressions
1210 * ScanKeys Skey structures for index quals
1211 * NumScanKeys number of ScanKeys
1212 * OrderByKeys Skey structures for index ordering operators
1213 * NumOrderByKeys number of OrderByKeys
1214 * RuntimeKeys info about Skeys that must be evaluated at runtime
1215 * NumRuntimeKeys number of RuntimeKeys
1216 * RuntimeKeysReady true if runtime Skeys have been computed
1217 * RuntimeContext expr context for evaling runtime Skeys
1218 * RelationDesc index relation descriptor
1219 * ScanDesc index scan descriptor
1222 typedef struct IndexScanState
1224 ScanState ss; /* its first field is NodeTag */
1225 List *indexqualorig;
1226 ScanKey iss_ScanKeys;
1227 int iss_NumScanKeys;
1228 ScanKey iss_OrderByKeys;
1229 int iss_NumOrderByKeys;
1230 IndexRuntimeKeyInfo *iss_RuntimeKeys;
1231 int iss_NumRuntimeKeys;
1232 bool iss_RuntimeKeysReady;
1233 ExprContext *iss_RuntimeContext;
1234 Relation iss_RelationDesc;
1235 IndexScanDesc iss_ScanDesc;
1239 * BitmapIndexScanState information
1241 * result bitmap to return output into, or NULL
1242 * ScanKeys Skey structures for index quals
1243 * NumScanKeys number of ScanKeys
1244 * RuntimeKeys info about Skeys that must be evaluated at runtime
1245 * NumRuntimeKeys number of RuntimeKeys
1246 * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
1247 * NumArrayKeys number of ArrayKeys
1248 * RuntimeKeysReady true if runtime Skeys have been computed
1249 * RuntimeContext expr context for evaling runtime Skeys
1250 * RelationDesc index relation descriptor
1251 * ScanDesc index scan descriptor
1254 typedef struct BitmapIndexScanState
1256 ScanState ss; /* its first field is NodeTag */
1257 TIDBitmap *biss_result;
1258 ScanKey biss_ScanKeys;
1259 int biss_NumScanKeys;
1260 IndexRuntimeKeyInfo *biss_RuntimeKeys;
1261 int biss_NumRuntimeKeys;
1262 IndexArrayKeyInfo *biss_ArrayKeys;
1263 int biss_NumArrayKeys;
1264 bool biss_RuntimeKeysReady;
1265 ExprContext *biss_RuntimeContext;
1266 Relation biss_RelationDesc;
1267 IndexScanDesc biss_ScanDesc;
1268 } BitmapIndexScanState;
1271 * BitmapHeapScanState information
1273 * bitmapqualorig execution state for bitmapqualorig expressions
1274 * tbm bitmap obtained from child index scan(s)
1275 * tbmiterator iterator for scanning current pages
1276 * tbmres current-page data
1277 * prefetch_iterator iterator for prefetching ahead of current page
1278 * prefetch_pages # pages prefetch iterator is ahead of current
1279 * prefetch_target target prefetch distance
1282 typedef struct BitmapHeapScanState
1284 ScanState ss; /* its first field is NodeTag */
1285 List *bitmapqualorig;
1287 TBMIterator *tbmiterator;
1288 TBMIterateResult *tbmres;
1289 TBMIterator *prefetch_iterator;
1291 int prefetch_target;
1292 } BitmapHeapScanState;
1295 * TidScanState information
1297 * isCurrentOf scan has a CurrentOfExpr qual
1298 * NumTids number of tids in this scan
1299 * TidPtr index of currently fetched tid
1300 * TidList evaluated item pointers (array of size NumTids)
1303 typedef struct TidScanState
1305 ScanState ss; /* its first field is NodeTag */
1306 List *tss_tidquals; /* list of ExprState nodes */
1307 bool tss_isCurrentOf;
1311 ItemPointerData *tss_TidList;
1312 HeapTupleData tss_htup;
1316 * SubqueryScanState information
1318 * SubqueryScanState is used for scanning a sub-query in the range table.
1319 * ScanTupleSlot references the current output tuple of the sub-query.
1322 typedef struct SubqueryScanState
1324 ScanState ss; /* its first field is NodeTag */
1326 } SubqueryScanState;
1329 * FunctionScanState information
1331 * Function nodes are used to scan the results of a
1332 * function appearing in FROM (typically a function returning set).
1334 * eflags node's capability flags
1335 * tupdesc expected return tuple description
1336 * tuplestorestate private state of tuplestore.c
1337 * funcexpr state for function expression being evaluated
1340 typedef struct FunctionScanState
1342 ScanState ss; /* its first field is NodeTag */
1345 Tuplestorestate *tuplestorestate;
1346 ExprState *funcexpr;
1347 } FunctionScanState;
1350 * ValuesScanState information
1352 * ValuesScan nodes are used to scan the results of a VALUES list
1354 * rowcontext per-expression-list context
1355 * exprlists array of expression lists being evaluated
1356 * array_len size of array
1357 * curr_idx current array index (0-based)
1358 * marked_idx marked position (for mark/restore)
1360 * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1361 * expressions attached to the node. We create a second ExprContext,
1362 * rowcontext, in which to build the executor expression state for each
1363 * Values sublist. Resetting this context lets us get rid of expression
1364 * state for each row, avoiding major memory leakage over a long values list.
1367 typedef struct ValuesScanState
1369 ScanState ss; /* its first field is NodeTag */
1370 ExprContext *rowcontext;
1378 * CteScanState information
1380 * CteScan nodes are used to scan a CommonTableExpr query.
1382 * Multiple CteScan nodes can read out from the same CTE query. We use
1383 * a tuplestore to hold rows that have been read from the CTE query but
1384 * not yet consumed by all readers.
1387 typedef struct CteScanState
1389 ScanState ss; /* its first field is NodeTag */
1390 int eflags; /* capability flags to pass to tuplestore */
1391 int readptr; /* index of my tuplestore read pointer */
1392 PlanState *cteplanstate; /* PlanState for the CTE query itself */
1393 /* Link to the "leader" CteScanState (possibly this same node) */
1394 struct CteScanState *leader;
1395 /* The remaining fields are only valid in the "leader" CteScanState */
1396 Tuplestorestate *cte_table; /* rows already read from the CTE query */
1397 bool eof_cte; /* reached end of CTE query? */
1401 * WorkTableScanState information
1403 * WorkTableScan nodes are used to scan the work table created by
1404 * a RecursiveUnion node. We locate the RecursiveUnion node
1405 * during executor startup.
1408 typedef struct WorkTableScanState
1410 ScanState ss; /* its first field is NodeTag */
1411 RecursiveUnionState *rustate;
1412 } WorkTableScanState;
1415 * ForeignScanState information
1417 * ForeignScan nodes are used to scan foreign-data tables.
1420 typedef struct ForeignScanState
1422 ScanState ss; /* its first field is NodeTag */
1423 /* use struct pointer to avoid including fdwapi.h here */
1424 struct FdwRoutine *fdwroutine;
1425 void *fdw_state; /* foreign-data wrapper can keep state here */
1428 /* ----------------------------------------------------------------
1429 * Join State Information
1430 * ----------------------------------------------------------------
1434 * JoinState information
1436 * Superclass for state nodes of join plans.
1439 typedef struct JoinState
1443 List *joinqual; /* JOIN quals (in addition to ps.qual) */
1447 * NestLoopState information
1449 * NeedNewOuter true if need new outer tuple on next call
1450 * MatchedOuter true if found a join match for current outer tuple
1451 * NullInnerTupleSlot prepared null tuple for left outer joins
1454 typedef struct NestLoopState
1456 JoinState js; /* its first field is NodeTag */
1457 bool nl_NeedNewOuter;
1458 bool nl_MatchedOuter;
1459 TupleTableSlot *nl_NullInnerTupleSlot;
1463 * MergeJoinState information
1465 * NumClauses number of mergejoinable join clauses
1466 * Clauses info for each mergejoinable clause
1467 * JoinState current state of ExecMergeJoin state machine
1468 * ExtraMarks true to issue extra Mark operations on inner scan
1469 * ConstFalseJoin true if we have a constant-false joinqual
1470 * FillOuter true if should emit unjoined outer tuples anyway
1471 * FillInner true if should emit unjoined inner tuples anyway
1472 * MatchedOuter true if found a join match for current outer tuple
1473 * MatchedInner true if found a join match for current inner tuple
1474 * OuterTupleSlot slot in tuple table for cur outer tuple
1475 * InnerTupleSlot slot in tuple table for cur inner tuple
1476 * MarkedTupleSlot slot in tuple table for marked tuple
1477 * NullOuterTupleSlot prepared null tuple for right outer joins
1478 * NullInnerTupleSlot prepared null tuple for left outer joins
1479 * OuterEContext workspace for computing outer tuple's join values
1480 * InnerEContext workspace for computing inner tuple's join values
1483 /* private in nodeMergejoin.c: */
1484 typedef struct MergeJoinClauseData *MergeJoinClause;
1486 typedef struct MergeJoinState
1488 JoinState js; /* its first field is NodeTag */
1490 MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1493 bool mj_ConstFalseJoin;
1496 bool mj_MatchedOuter;
1497 bool mj_MatchedInner;
1498 TupleTableSlot *mj_OuterTupleSlot;
1499 TupleTableSlot *mj_InnerTupleSlot;
1500 TupleTableSlot *mj_MarkedTupleSlot;
1501 TupleTableSlot *mj_NullOuterTupleSlot;
1502 TupleTableSlot *mj_NullInnerTupleSlot;
1503 ExprContext *mj_OuterEContext;
1504 ExprContext *mj_InnerEContext;
1508 * HashJoinState information
1510 * hashclauses original form of the hashjoin condition
1511 * hj_OuterHashKeys the outer hash keys in the hashjoin condition
1512 * hj_InnerHashKeys the inner hash keys in the hashjoin condition
1513 * hj_HashOperators the join operators in the hashjoin condition
1514 * hj_HashTable hash table for the hashjoin
1515 * (NULL if table not built yet)
1516 * hj_CurHashValue hash value for current outer tuple
1517 * hj_CurBucketNo regular bucket# for current outer tuple
1518 * hj_CurSkewBucketNo skew bucket# for current outer tuple
1519 * hj_CurTuple last inner tuple matched to current outer
1520 * tuple, or NULL if starting search
1521 * (hj_CurXXX variables are undefined if
1522 * OuterTupleSlot is empty!)
1523 * hj_OuterTupleSlot tuple slot for outer tuples
1524 * hj_HashTupleSlot tuple slot for inner (hashed) tuples
1525 * hj_NullOuterTupleSlot prepared null tuple for right/full outer joins
1526 * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
1527 * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
1528 * hj_JoinState current state of ExecHashJoin state machine
1529 * hj_MatchedOuter true if found a join match for current outer
1530 * hj_OuterNotEmpty true if outer relation known not empty
1534 /* these structs are defined in executor/hashjoin.h: */
1535 typedef struct HashJoinTupleData *HashJoinTuple;
1536 typedef struct HashJoinTableData *HashJoinTable;
1538 typedef struct HashJoinState
1540 JoinState js; /* its first field is NodeTag */
1541 List *hashclauses; /* list of ExprState nodes */
1542 List *hj_OuterHashKeys; /* list of ExprState nodes */
1543 List *hj_InnerHashKeys; /* list of ExprState nodes */
1544 List *hj_HashOperators; /* list of operator OIDs */
1545 HashJoinTable hj_HashTable;
1546 uint32 hj_CurHashValue;
1548 int hj_CurSkewBucketNo;
1549 HashJoinTuple hj_CurTuple;
1550 TupleTableSlot *hj_OuterTupleSlot;
1551 TupleTableSlot *hj_HashTupleSlot;
1552 TupleTableSlot *hj_NullOuterTupleSlot;
1553 TupleTableSlot *hj_NullInnerTupleSlot;
1554 TupleTableSlot *hj_FirstOuterTupleSlot;
1556 bool hj_MatchedOuter;
1557 bool hj_OuterNotEmpty;
1561 /* ----------------------------------------------------------------
1562 * Materialization State Information
1563 * ----------------------------------------------------------------
1567 * MaterialState information
1569 * materialize nodes are used to materialize the results
1570 * of a subplan into a temporary file.
1572 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1575 typedef struct MaterialState
1577 ScanState ss; /* its first field is NodeTag */
1578 int eflags; /* capability flags to pass to tuplestore */
1579 bool eof_underlying; /* reached end of underlying plan? */
1580 Tuplestorestate *tuplestorestate;
1584 * SortState information
1587 typedef struct SortState
1589 ScanState ss; /* its first field is NodeTag */
1590 bool randomAccess; /* need random access to sort output? */
1591 bool bounded; /* is the result set bounded? */
1592 int64 bound; /* if bounded, how many tuples are needed */
1593 bool sort_Done; /* sort completed yet? */
1594 bool bounded_Done; /* value of bounded we did the sort with */
1595 int64 bound_Done; /* value of bound we did the sort with */
1596 void *tuplesortstate; /* private state of tuplesort.c */
1599 /* ---------------------
1600 * GroupState information
1601 * -------------------------
1603 typedef struct GroupState
1605 ScanState ss; /* its first field is NodeTag */
1606 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1607 bool grp_done; /* indicates completion of Group scan */
1610 /* ---------------------
1611 * AggState information
1613 * ss.ss_ScanTupleSlot refers to output of underlying plan.
1615 * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1616 * ecxt_aggnulls arrays, which hold the computed agg values for the current
1617 * input group during evaluation of an Agg node's output tuple(s). We
1618 * create a second ExprContext, tmpcontext, in which to evaluate input
1619 * expressions and run the aggregate transition functions.
1620 * -------------------------
1622 /* these structs are private in nodeAgg.c: */
1623 typedef struct AggStatePerAggData *AggStatePerAgg;
1624 typedef struct AggStatePerGroupData *AggStatePerGroup;
1626 typedef struct AggState
1628 ScanState ss; /* its first field is NodeTag */
1629 List *aggs; /* all Aggref nodes in targetlist & quals */
1630 int numaggs; /* length of list (could be zero!) */
1631 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1632 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1633 AggStatePerAgg peragg; /* per-Aggref information */
1634 MemoryContext aggcontext; /* memory context for long-lived data */
1635 ExprContext *tmpcontext; /* econtext for input expressions */
1636 bool agg_done; /* indicates completion of Agg scan */
1637 /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1638 AggStatePerGroup pergroup; /* per-Aggref-per-group working state */
1639 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1640 /* these fields are used in AGG_HASHED mode: */
1641 TupleHashTable hashtable; /* hash table with one entry per group */
1642 TupleTableSlot *hashslot; /* slot for loading hash table */
1643 List *hash_needed; /* list of columns needed in hash table */
1644 bool table_filled; /* hash table filled yet? */
1645 TupleHashIterator hashiter; /* for iterating through hash table */
1649 * WindowAggState information
1652 /* these structs are private in nodeWindowAgg.c: */
1653 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1654 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1656 typedef struct WindowAggState
1658 ScanState ss; /* its first field is NodeTag */
1660 /* these fields are filled in by ExecInitExpr: */
1661 List *funcs; /* all WindowFunc nodes in targetlist */
1662 int numfuncs; /* total number of window functions */
1663 int numaggs; /* number that are plain aggregates */
1665 WindowStatePerFunc perfunc; /* per-window-function information */
1666 WindowStatePerAgg peragg; /* per-plain-aggregate information */
1667 FmgrInfo *partEqfunctions; /* equality funcs for partition columns */
1668 FmgrInfo *ordEqfunctions; /* equality funcs for ordering columns */
1669 Tuplestorestate *buffer; /* stores rows of current partition */
1670 int current_ptr; /* read pointer # for current */
1671 int64 spooled_rows; /* total # of rows in buffer */
1672 int64 currentpos; /* position of current row in partition */
1673 int64 frameheadpos; /* current frame head position */
1674 int64 frametailpos; /* current frame tail position */
1675 /* use struct pointer to avoid including windowapi.h here */
1676 struct WindowObjectData *agg_winobj; /* winobj for aggregate
1678 int64 aggregatedbase; /* start row for current aggregates */
1679 int64 aggregatedupto; /* rows before this one are aggregated */
1681 int frameOptions; /* frame_clause options, see WindowDef */
1682 ExprState *startOffset; /* expression for starting bound offset */
1683 ExprState *endOffset; /* expression for ending bound offset */
1684 Datum startOffsetValue; /* result of startOffset evaluation */
1685 Datum endOffsetValue; /* result of endOffset evaluation */
1687 MemoryContext partcontext; /* context for partition-lifespan data */
1688 MemoryContext aggcontext; /* context for each aggregate data */
1689 ExprContext *tmpcontext; /* short-term evaluation context */
1691 bool all_first; /* true if the scan is starting */
1692 bool all_done; /* true if the scan is finished */
1693 bool partition_spooled; /* true if all tuples in current
1694 * partition have been spooled into
1696 bool more_partitions;/* true if there's more partitions after this
1698 bool framehead_valid;/* true if frameheadpos is known up to date
1699 * for current row */
1700 bool frametail_valid;/* true if frametailpos is known up to date
1701 * for current row */
1703 TupleTableSlot *first_part_slot; /* first tuple of current or next
1706 /* temporary slots for tuples fetched back from tuplestore */
1707 TupleTableSlot *agg_row_slot;
1708 TupleTableSlot *temp_slot_1;
1709 TupleTableSlot *temp_slot_2;
1713 * UniqueState information
1715 * Unique nodes are used "on top of" sort nodes to discard
1716 * duplicate tuples returned from the sort phase. Basically
1717 * all it does is compare the current tuple from the subplan
1718 * with the previously fetched tuple (stored in its result slot).
1719 * If the two are identical in all interesting fields, then
1720 * we just fetch another tuple from the sort and try again.
1723 typedef struct UniqueState
1725 PlanState ps; /* its first field is NodeTag */
1726 FmgrInfo *eqfunctions; /* per-field lookup data for equality fns */
1727 MemoryContext tempContext; /* short-term context for comparisons */
1731 * HashState information
1734 typedef struct HashState
1736 PlanState ps; /* its first field is NodeTag */
1737 HashJoinTable hashtable; /* hash table for the hashjoin */
1738 List *hashkeys; /* list of ExprState nodes */
1739 /* hashkeys is same as parent's hj_InnerHashKeys */
1743 * SetOpState information
1745 * Even in "sorted" mode, SetOp nodes are more complex than a simple
1746 * Unique, since we have to count how many duplicates to return. But
1747 * we also support hashing, so this is really more like a cut-down
1751 /* this struct is private in nodeSetOp.c: */
1752 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
1754 typedef struct SetOpState
1756 PlanState ps; /* its first field is NodeTag */
1757 FmgrInfo *eqfunctions; /* per-grouping-field equality fns */
1758 FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
1759 bool setop_done; /* indicates completion of output scan */
1760 long numOutput; /* number of dups left to output */
1761 MemoryContext tempContext; /* short-term context for comparisons */
1762 /* these fields are used in SETOP_SORTED mode: */
1763 SetOpStatePerGroup pergroup; /* per-group working state */
1764 HeapTuple grp_firstTuple; /* copy of first tuple of current group */
1765 /* these fields are used in SETOP_HASHED mode: */
1766 TupleHashTable hashtable; /* hash table with one entry per group */
1767 MemoryContext tableContext; /* memory context containing hash table */
1768 bool table_filled; /* hash table filled yet? */
1769 TupleHashIterator hashiter; /* for iterating through hash table */
1773 * LockRowsState information
1775 * LockRows nodes are used to enforce FOR UPDATE/FOR SHARE locking.
1778 typedef struct LockRowsState
1780 PlanState ps; /* its first field is NodeTag */
1781 List *lr_arowMarks; /* List of ExecAuxRowMarks */
1782 EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
1786 * LimitState information
1788 * Limit nodes are used to enforce LIMIT/OFFSET clauses.
1789 * They just select the desired subrange of their subplan's output.
1791 * offset is the number of initial tuples to skip (0 does nothing).
1792 * count is the number of tuples to return after skipping the offset tuples.
1793 * If no limit count was specified, count is undefined and noCount is true.
1794 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1799 LIMIT_INITIAL, /* initial state for LIMIT node */
1800 LIMIT_RESCAN, /* rescan after recomputing parameters */
1801 LIMIT_EMPTY, /* there are no returnable rows */
1802 LIMIT_INWINDOW, /* have returned a row in the window */
1803 LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
1804 LIMIT_WINDOWEND, /* stepped off end of window */
1805 LIMIT_WINDOWSTART /* stepped off beginning of window */
1808 typedef struct LimitState
1810 PlanState ps; /* its first field is NodeTag */
1811 ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
1812 ExprState *limitCount; /* COUNT parameter, or NULL if none */
1813 int64 offset; /* current OFFSET value */
1814 int64 count; /* current COUNT, if any */
1815 bool noCount; /* if true, ignore count */
1816 LimitStateCond lstate; /* state machine status, as above */
1817 int64 position; /* 1-based index of last tuple returned */
1818 TupleTableSlot *subSlot; /* tuple last obtained from subplan */
1821 #endif /* EXECNODES_H */