1 /*-------------------------------------------------------------------------
2  *
3  * execnodes.h
4  *	  definitions for executor state nodes
5  *
6  *
7  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/nodes/execnodes.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef EXECNODES_H
15 #define EXECNODES_H
16 
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "executor/instrument.h"
20 #include "lib/pairingheap.h"
21 #include "nodes/params.h"
22 #include "nodes/plannodes.h"
23 #include "utils/reltrigger.h"
24 #include "utils/sortsupport.h"
25 #include "utils/tuplestore.h"
26 #include "utils/tuplesort.h"
27 
28 
29 /* ----------------
30  *	  IndexInfo information
31  *
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.
35  *
36  *		NumIndexAttrs		number of columns in this index
37  *		KeyAttrNumbers		underlying-rel attribute numbers used as keys
38  *							(zeroes indicate expressions)
39  *		Expressions			expr trees for expression entries, or NIL if none
40  *		ExpressionsState	exec state for expressions, or NIL if none
41  *		Predicate			partial-index predicate, or NIL if none
42  *		PredicateState		exec state for predicate, or NIL if none
43  *		ExclusionOps		Per-column exclusion operators, or NULL if none
44  *		ExclusionProcs		Underlying function OIDs for ExclusionOps
45  *		ExclusionStrats		Opclass strategy numbers for ExclusionOps
46  *		UniqueOps			Theses are like Exclusion*, but for unique indexes
47  *		UniqueProcs
48  *		UniqueStrats
49  *		Unique				is it a unique index?
50  *		ReadyForInserts		is it valid for inserts?
51  *		Concurrent			are we doing a concurrent index build?
52  *		BrokenHotChain		did we detect any broken HOT chains?
53  *
54  * ii_Concurrent and ii_BrokenHotChain are used only during index build;
55  * they're conventionally set to false otherwise.
56  * ----------------
57  */
58 typedef struct IndexInfo
59 {
60 	NodeTag		type;
61 	int			ii_NumIndexAttrs;
62 	AttrNumber	ii_KeyAttrNumbers[INDEX_MAX_KEYS];
63 	List	   *ii_Expressions; /* list of Expr */
64 	List	   *ii_ExpressionsState;	/* list of ExprState */
65 	List	   *ii_Predicate;	/* list of Expr */
66 	List	   *ii_PredicateState;		/* list of ExprState */
67 	Oid		   *ii_ExclusionOps;	/* array with one entry per column */
68 	Oid		   *ii_ExclusionProcs;		/* array with one entry per column */
69 	uint16	   *ii_ExclusionStrats;		/* array with one entry per column */
70 	Oid		   *ii_UniqueOps;	/* array with one entry per column */
71 	Oid		   *ii_UniqueProcs; /* array with one entry per column */
72 	uint16	   *ii_UniqueStrats;	/* array with one entry per column */
73 	bool		ii_Unique;
74 	bool		ii_ReadyForInserts;
75 	bool		ii_Concurrent;
76 	bool		ii_BrokenHotChain;
77 } IndexInfo;
78 
79 /* ----------------
80  *	  ExprContext_CB
81  *
82  *		List of callbacks to be called at ExprContext shutdown.
83  * ----------------
84  */
85 typedef void (*ExprContextCallbackFunction) (Datum arg);
86 
87 typedef struct ExprContext_CB
88 {
89 	struct ExprContext_CB *next;
90 	ExprContextCallbackFunction function;
91 	Datum		arg;
92 } ExprContext_CB;
93 
94 /* ----------------
95  *	  ExprContext
96  *
97  *		This class holds the "current context" information
98  *		needed to evaluate expressions for doing tuple qualifications
99  *		and tuple projections.  For example, if an expression refers
100  *		to an attribute in the current inner tuple then we need to know
101  *		what the current inner tuple is and so we look at the expression
102  *		context.
103  *
104  *	There are two memory contexts associated with an ExprContext:
105  *	* ecxt_per_query_memory is a query-lifespan context, typically the same
106  *	  context the ExprContext node itself is allocated in.  This context
107  *	  can be used for purposes such as storing function call cache info.
108  *	* ecxt_per_tuple_memory is a short-term context for expression results.
109  *	  As the name suggests, it will typically be reset once per tuple,
110  *	  before we begin to evaluate expressions for that tuple.  Each
111  *	  ExprContext normally has its very own per-tuple memory context.
112  *
113  *	CurrentMemoryContext should be set to ecxt_per_tuple_memory before
114  *	calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
115  * ----------------
116  */
117 typedef struct ExprContext
118 {
119 	NodeTag		type;
120 
121 	/* Tuples that Var nodes in expression may refer to */
122 	TupleTableSlot *ecxt_scantuple;
123 	TupleTableSlot *ecxt_innertuple;
124 	TupleTableSlot *ecxt_outertuple;
125 
126 	/* Memory contexts for expression evaluation --- see notes above */
127 	MemoryContext ecxt_per_query_memory;
128 	MemoryContext ecxt_per_tuple_memory;
129 
130 	/* Values to substitute for Param nodes in expression */
131 	ParamExecData *ecxt_param_exec_vals;		/* for PARAM_EXEC params */
132 	ParamListInfo ecxt_param_list_info; /* for other param types */
133 
134 	/*
135 	 * Values to substitute for Aggref nodes in the expressions of an Agg
136 	 * node, or for WindowFunc nodes within a WindowAgg node.
137 	 */
138 	Datum	   *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
139 	bool	   *ecxt_aggnulls;	/* null flags for aggs/windowfuncs */
140 
141 	/* Value to substitute for CaseTestExpr nodes in expression */
142 	Datum		caseValue_datum;
143 	bool		caseValue_isNull;
144 
145 	/* Value to substitute for CoerceToDomainValue nodes in expression */
146 	Datum		domainValue_datum;
147 	bool		domainValue_isNull;
148 
149 	/* Link to containing EState (NULL if a standalone ExprContext) */
150 	struct EState *ecxt_estate;
151 
152 	/* Functions to call back when ExprContext is shut down or rescanned */
153 	ExprContext_CB *ecxt_callbacks;
154 } ExprContext;
155 
156 /*
157  * Set-result status returned by ExecEvalExpr()
158  */
159 typedef enum
160 {
161 	ExprSingleResult,			/* expression does not return a set */
162 	ExprMultipleResult,			/* this result is an element of a set */
163 	ExprEndResult				/* there are no more elements in the set */
164 } ExprDoneCond;
165 
166 /*
167  * Return modes for functions returning sets.  Note values must be chosen
168  * as separate bits so that a bitmask can be formed to indicate supported
169  * modes.  SFRM_Materialize_Random and SFRM_Materialize_Preferred are
170  * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
171  */
172 typedef enum
173 {
174 	SFRM_ValuePerCall = 0x01,	/* one value returned per call */
175 	SFRM_Materialize = 0x02,	/* result set instantiated in Tuplestore */
176 	SFRM_Materialize_Random = 0x04,		/* Tuplestore needs randomAccess */
177 	SFRM_Materialize_Preferred = 0x08	/* caller prefers Tuplestore */
178 } SetFunctionReturnMode;
179 
180 /*
181  * When calling a function that might return a set (multiple rows),
182  * a node of this type is passed as fcinfo->resultinfo to allow
183  * return status to be passed back.  A function returning set should
184  * raise an error if no such resultinfo is provided.
185  */
186 typedef struct ReturnSetInfo
187 {
188 	NodeTag		type;
189 	/* values set by caller: */
190 	ExprContext *econtext;		/* context function is being called in */
191 	TupleDesc	expectedDesc;	/* tuple descriptor expected by caller */
192 	int			allowedModes;	/* bitmask: return modes caller can handle */
193 	/* result status from function (but pre-initialized by caller): */
194 	SetFunctionReturnMode returnMode;	/* actual return mode */
195 	ExprDoneCond isDone;		/* status for ValuePerCall mode */
196 	/* fields filled by function in Materialize return mode: */
197 	Tuplestorestate *setResult; /* holds the complete returned tuple set */
198 	TupleDesc	setDesc;		/* actual descriptor for returned tuples */
199 } ReturnSetInfo;
200 
201 /* ----------------
202  *		ProjectionInfo node information
203  *
204  *		This is all the information needed to perform projections ---
205  *		that is, form new tuples by evaluation of targetlist expressions.
206  *		Nodes which need to do projections create one of these.
207  *
208  *		ExecProject() evaluates the tlist, forms a tuple, and stores it
209  *		in the given slot.  Note that the result will be a "virtual" tuple
210  *		unless ExecMaterializeSlot() is then called to force it to be
211  *		converted to a physical tuple.  The slot must have a tupledesc
212  *		that matches the output of the tlist!
213  *
214  *		The planner very often produces tlists that consist entirely of
215  *		simple Var references (lower levels of a plan tree almost always
216  *		look like that).  And top-level tlists are often mostly Vars too.
217  *		We therefore optimize execution of simple-Var tlist entries.
218  *		The pi_targetlist list actually contains only the tlist entries that
219  *		aren't simple Vars, while those that are Vars are processed using the
220  *		varSlotOffsets/varNumbers/varOutputCols arrays.
221  *
222  *		The lastXXXVar fields are used to optimize fetching of fields from
223  *		input tuples: they let us do a slot_getsomeattrs() call to ensure
224  *		that all needed attributes are extracted in one pass.
225  *
226  *		targetlist		target list for projection (non-Var expressions only)
227  *		exprContext		expression context in which to evaluate targetlist
228  *		slot			slot to place projection result in
229  *		itemIsDone		workspace array for ExecProject
230  *		directMap		true if varOutputCols[] is an identity map
231  *		numSimpleVars	number of simple Vars found in original tlist
232  *		varSlotOffsets	array indicating which slot each simple Var is from
233  *		varNumbers		array containing input attr numbers of simple Vars
234  *		varOutputCols	array containing output attr numbers of simple Vars
235  *		lastInnerVar	highest attnum from inner tuple slot (0 if none)
236  *		lastOuterVar	highest attnum from outer tuple slot (0 if none)
237  *		lastScanVar		highest attnum from scan tuple slot (0 if none)
238  * ----------------
239  */
240 typedef struct ProjectionInfo
241 {
242 	NodeTag		type;
243 	List	   *pi_targetlist;
244 	ExprContext *pi_exprContext;
245 	TupleTableSlot *pi_slot;
246 	ExprDoneCond *pi_itemIsDone;
247 	bool		pi_directMap;
248 	int			pi_numSimpleVars;
249 	int		   *pi_varSlotOffsets;
250 	int		   *pi_varNumbers;
251 	int		   *pi_varOutputCols;
252 	int			pi_lastInnerVar;
253 	int			pi_lastOuterVar;
254 	int			pi_lastScanVar;
255 } ProjectionInfo;
256 
257 /* ----------------
258  *	  JunkFilter
259  *
260  *	  This class is used to store information regarding junk attributes.
261  *	  A junk attribute is an attribute in a tuple that is needed only for
262  *	  storing intermediate information in the executor, and does not belong
263  *	  in emitted tuples.  For example, when we do an UPDATE query,
264  *	  the planner adds a "junk" entry to the targetlist so that the tuples
265  *	  returned to ExecutePlan() contain an extra attribute: the ctid of
266  *	  the tuple to be updated.  This is needed to do the update, but we
267  *	  don't want the ctid to be part of the stored new tuple!  So, we
268  *	  apply a "junk filter" to remove the junk attributes and form the
269  *	  real output tuple.  The junkfilter code also provides routines to
270  *	  extract the values of the junk attribute(s) from the input tuple.
271  *
272  *	  targetList:		the original target list (including junk attributes).
273  *	  cleanTupType:		the tuple descriptor for the "clean" tuple (with
274  *						junk attributes removed).
275  *	  cleanMap:			A map with the correspondence between the non-junk
276  *						attribute numbers of the "original" tuple and the
277  *						attribute numbers of the "clean" tuple.
278  *	  resultSlot:		tuple slot used to hold cleaned tuple.
279  *	  junkAttNo:		not used by junkfilter code.  Can be used by caller
280  *						to remember the attno of a specific junk attribute
281  *						(nodeModifyTable.c keeps the "ctid" or "wholerow"
282  *						attno here).
283  * ----------------
284  */
285 typedef struct JunkFilter
286 {
287 	NodeTag		type;
288 	List	   *jf_targetList;
289 	TupleDesc	jf_cleanTupType;
290 	AttrNumber *jf_cleanMap;
291 	TupleTableSlot *jf_resultSlot;
292 	AttrNumber	jf_junkAttNo;
293 } JunkFilter;
294 
295 /* ----------------
296  *	  ResultRelInfo information
297  *
298  *		Whenever we update an existing relation, we have to
299  *		update indices on the relation, and perhaps also fire triggers.
300  *		The ResultRelInfo class is used to hold all the information needed
301  *		about a result relation, including indices.. -cim 10/15/89
302  *
303  *		RangeTableIndex			result relation's range table index
304  *		RelationDesc			relation descriptor for result relation
305  *		NumIndices				# of indices existing on result relation
306  *		IndexRelationDescs		array of relation descriptors for indices
307  *		IndexRelationInfo		array of key/attr info for indices
308  *		TrigDesc				triggers to be fired, if any
309  *		TrigFunctions			cached lookup info for trigger functions
310  *		TrigWhenExprs			array of trigger WHEN expr states
311  *		TrigInstrument			optional runtime measurements for triggers
312  *		FdwRoutine				FDW callback functions, if foreign table
313  *		FdwState				available to save private state of FDW
314  *		usesFdwDirectModify		true when modifying foreign table directly
315  *		WithCheckOptions		list of WithCheckOption's to be checked
316  *		WithCheckOptionExprs	list of WithCheckOption expr states
317  *		ConstraintExprs			array of constraint-checking expr states
318  *		junkFilter				for removing junk attributes from tuples
319  *		projectReturning		for computing a RETURNING list
320  *		onConflictSetProj		for computing ON CONFLICT DO UPDATE SET
321  *		onConflictSetWhere		list of ON CONFLICT DO UPDATE exprs (qual)
322  * ----------------
323  */
324 typedef struct ResultRelInfo
325 {
326 	NodeTag		type;
327 	Index		ri_RangeTableIndex;
328 	Relation	ri_RelationDesc;
329 	int			ri_NumIndices;
330 	RelationPtr ri_IndexRelationDescs;
331 	IndexInfo **ri_IndexRelationInfo;
332 	TriggerDesc *ri_TrigDesc;
333 	FmgrInfo   *ri_TrigFunctions;
334 	List	  **ri_TrigWhenExprs;
335 	Instrumentation *ri_TrigInstrument;
336 	struct FdwRoutine *ri_FdwRoutine;
337 	void	   *ri_FdwState;
338 	bool		ri_usesFdwDirectModify;
339 	List	   *ri_WithCheckOptions;
340 	List	   *ri_WithCheckOptionExprs;
341 	List	  **ri_ConstraintExprs;
342 	JunkFilter *ri_junkFilter;
343 	ProjectionInfo *ri_projectReturning;
344 	ProjectionInfo *ri_onConflictSetProj;
345 	List	   *ri_onConflictSetWhere;
346 } ResultRelInfo;
347 
348 /* ----------------
349  *	  EState information
350  *
351  * Master working state for an Executor invocation
352  * ----------------
353  */
354 typedef struct EState
355 {
356 	NodeTag		type;
357 
358 	/* Basic state for all query types: */
359 	ScanDirection es_direction; /* current scan direction */
360 	Snapshot	es_snapshot;	/* time qual to use */
361 	Snapshot	es_crosscheck_snapshot; /* crosscheck time qual for RI */
362 	List	   *es_range_table; /* List of RangeTblEntry */
363 	PlannedStmt *es_plannedstmt;	/* link to top of plan tree */
364 
365 	JunkFilter *es_junkFilter;	/* top-level junk filter, if any */
366 
367 	/* If query can insert/delete tuples, the command ID to mark them with */
368 	CommandId	es_output_cid;
369 
370 	/* Info about target table(s) for insert/update/delete queries: */
371 	ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
372 	int			es_num_result_relations;		/* length of array */
373 	ResultRelInfo *es_result_relation_info;		/* currently active array elt */
374 
375 	/* Stuff used for firing triggers: */
376 	List	   *es_trig_target_relations;		/* trigger-only ResultRelInfos */
377 	TupleTableSlot *es_trig_tuple_slot; /* for trigger output tuples */
378 	TupleTableSlot *es_trig_oldtup_slot;		/* for TriggerEnabled */
379 	TupleTableSlot *es_trig_newtup_slot;		/* for TriggerEnabled */
380 
381 	/* Parameter info: */
382 	ParamListInfo es_param_list_info;	/* values of external params */
383 	ParamExecData *es_param_exec_vals;	/* values of internal params */
384 
385 	/* Other working state: */
386 	MemoryContext es_query_cxt; /* per-query context in which EState lives */
387 
388 	List	   *es_tupleTable;	/* List of TupleTableSlots */
389 
390 	List	   *es_rowMarks;	/* List of ExecRowMarks */
391 
392 	uint64		es_processed;	/* # of tuples processed */
393 	Oid			es_lastoid;		/* last oid processed (by INSERT) */
394 
395 	int			es_top_eflags;	/* eflags passed to ExecutorStart */
396 	int			es_instrument;	/* OR of InstrumentOption flags */
397 	bool		es_finished;	/* true when ExecutorFinish is done */
398 
399 	List	   *es_exprcontexts;	/* List of ExprContexts within EState */
400 
401 	List	   *es_subplanstates;		/* List of PlanState for SubPlans */
402 
403 	List	   *es_auxmodifytables;		/* List of secondary ModifyTableStates */
404 
405 	/*
406 	 * this ExprContext is for per-output-tuple operations, such as constraint
407 	 * checks and index-value computations.  It will be reset for each output
408 	 * tuple.  Note that it will be created only if needed.
409 	 */
410 	ExprContext *es_per_tuple_exprcontext;
411 
412 	/*
413 	 * These fields are for re-evaluating plan quals when an updated tuple is
414 	 * substituted in READ COMMITTED mode.  es_epqTuple[] contains tuples that
415 	 * scan plan nodes should return instead of whatever they'd normally
416 	 * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
417 	 * particular array entry is valid; and es_epqScanDone[] is state to
418 	 * remember if the tuple has been returned already.  Arrays are of size
419 	 * list_length(es_range_table) and are indexed by scan node scanrelid - 1.
420 	 */
421 	HeapTuple  *es_epqTuple;	/* array of EPQ substitute tuples */
422 	bool	   *es_epqTupleSet; /* true if EPQ tuple is provided */
423 	bool	   *es_epqScanDone; /* true if EPQ tuple has been fetched */
424 
425 	bool		es_use_parallel_mode; /* can we use parallel workers? */
426 } EState;
427 
428 
429 /*
430  * ExecRowMark -
431  *	   runtime representation of FOR [KEY] UPDATE/SHARE clauses
432  *
433  * When doing UPDATE, DELETE, or SELECT FOR [KEY] UPDATE/SHARE, we will have an
434  * ExecRowMark for each non-target relation in the query (except inheritance
435  * parent RTEs, which can be ignored at runtime).  Virtual relations such as
436  * subqueries-in-FROM will have an ExecRowMark with relation == NULL.  See
437  * PlanRowMark for details about most of the fields.  In addition to fields
438  * directly derived from PlanRowMark, we store an activity flag (to denote
439  * inactive children of inheritance trees), curCtid, which is used by the
440  * WHERE CURRENT OF code, and ermExtra, which is available for use by the plan
441  * node that sources the relation (e.g., for a foreign table the FDW can use
442  * ermExtra to hold information).
443  *
444  * EState->es_rowMarks is a list of these structs.
445  */
446 typedef struct ExecRowMark
447 {
448 	Relation	relation;		/* opened and suitably locked relation */
449 	Oid			relid;			/* its OID (or InvalidOid, if subquery) */
450 	Index		rti;			/* its range table index */
451 	Index		prti;			/* parent range table index, if child */
452 	Index		rowmarkId;		/* unique identifier for resjunk columns */
453 	RowMarkType markType;		/* see enum in nodes/plannodes.h */
454 	LockClauseStrength strength;	/* LockingClause's strength, or LCS_NONE */
455 	LockWaitPolicy waitPolicy;	/* NOWAIT and SKIP LOCKED */
456 	bool		ermActive;		/* is this mark relevant for current tuple? */
457 	ItemPointerData curCtid;	/* ctid of currently locked tuple, if any */
458 	void	   *ermExtra;		/* available for use by relation source node */
459 } ExecRowMark;
460 
461 /*
462  * ExecAuxRowMark -
463  *	   additional runtime representation of FOR [KEY] UPDATE/SHARE clauses
464  *
465  * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
466  * deal with.  In addition to a pointer to the related entry in es_rowMarks,
467  * this struct carries the column number(s) of the resjunk columns associated
468  * with the rowmark (see comments for PlanRowMark for more detail).  In the
469  * case of ModifyTable, there has to be a separate ExecAuxRowMark list for
470  * each child plan, because the resjunk columns could be at different physical
471  * column positions in different subplans.
472  */
473 typedef struct ExecAuxRowMark
474 {
475 	ExecRowMark *rowmark;		/* related entry in es_rowMarks */
476 	AttrNumber	ctidAttNo;		/* resno of ctid junk attribute, if any */
477 	AttrNumber	toidAttNo;		/* resno of tableoid junk attribute, if any */
478 	AttrNumber	wholeAttNo;		/* resno of whole-row junk attribute, if any */
479 } ExecAuxRowMark;
480 
481 
482 /* ----------------------------------------------------------------
483  *				 Tuple Hash Tables
484  *
485  * All-in-memory tuple hash tables are used for a number of purposes.
486  *
487  * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
488  * and tab_eq_funcs are non-cross-type equality operators for those types.
489  * Normally these are the only functions used, but FindTupleHashEntry()
490  * supports searching a hashtable using cross-data-type hashing.  For that,
491  * the caller must supply hash functions for the LHS datatype as well as
492  * the cross-type equality operators to use.  in_hash_funcs and cur_eq_funcs
493  * are set to point to the caller's function arrays while doing such a search.
494  * During LookupTupleHashEntry(), they point to tab_hash_funcs and
495  * tab_eq_funcs respectively.
496  * ----------------------------------------------------------------
497  */
498 typedef struct TupleHashEntryData *TupleHashEntry;
499 typedef struct TupleHashTableData *TupleHashTable;
500 
501 typedef struct TupleHashEntryData
502 {
503 	/* firstTuple must be the first field in this struct! */
504 	MinimalTuple firstTuple;	/* copy of first tuple in this group */
505 	/* there may be additional data beyond the end of this struct */
506 } TupleHashEntryData;			/* VARIABLE LENGTH STRUCT */
507 
508 typedef struct TupleHashTableData
509 {
510 	HTAB	   *hashtab;		/* underlying dynahash table */
511 	int			numCols;		/* number of columns in lookup key */
512 	AttrNumber *keyColIdx;		/* attr numbers of key columns */
513 	FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */
514 	FmgrInfo   *tab_eq_funcs;	/* equality functions for table datatype(s) */
515 	MemoryContext tablecxt;		/* memory context containing table */
516 	MemoryContext tempcxt;		/* context for function evaluations */
517 	Size		entrysize;		/* actual size to make each hash entry */
518 	TupleTableSlot *tableslot;	/* slot for referencing table entries */
519 	/* The following fields are set transiently for each table search: */
520 	TupleTableSlot *inputslot;	/* current input tuple's slot */
521 	FmgrInfo   *in_hash_funcs;	/* hash functions for input datatype(s) */
522 	FmgrInfo   *cur_eq_funcs;	/* equality functions for input vs. table */
523 }	TupleHashTableData;
524 
525 typedef HASH_SEQ_STATUS TupleHashIterator;
526 
527 /*
528  * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
529  * Use ResetTupleHashIterator if the table can be frozen (in this case no
530  * explicit scan termination is needed).
531  */
532 #define InitTupleHashIterator(htable, iter) \
533 	hash_seq_init(iter, (htable)->hashtab)
534 #define TermTupleHashIterator(iter) \
535 	hash_seq_term(iter)
536 #define ResetTupleHashIterator(htable, iter) \
537 	do { \
538 		hash_freeze((htable)->hashtab); \
539 		hash_seq_init(iter, (htable)->hashtab); \
540 	} while (0)
541 #define ScanTupleHashTable(iter) \
542 	((TupleHashEntry) hash_seq_search(iter))
543 
544 
545 /* ----------------------------------------------------------------
546  *				 Expression State Trees
547  *
548  * Each executable expression tree has a parallel ExprState tree.
549  *
550  * Unlike PlanState, there is not an exact one-for-one correspondence between
551  * ExprState node types and Expr node types.  Many Expr node types have no
552  * need for node-type-specific run-time state, and so they can use plain
553  * ExprState or GenericExprState as their associated ExprState node type.
554  * ----------------------------------------------------------------
555  */
556 
557 /* ----------------
558  *		ExprState node
559  *
560  * ExprState is the common superclass for all ExprState-type nodes.
561  *
562  * It can also be instantiated directly for leaf Expr nodes that need no
563  * local run-time state (such as Var, Const, or Param).
564  *
565  * To save on dispatch overhead, each ExprState node contains a function
566  * pointer to the routine to execute to evaluate the node.
567  * ----------------
568  */
569 
570 typedef struct ExprState ExprState;
571 
572 typedef Datum (*ExprStateEvalFunc) (ExprState *expression,
573 												ExprContext *econtext,
574 												bool *isNull,
575 												ExprDoneCond *isDone);
576 
577 struct ExprState
578 {
579 	NodeTag		type;
580 	Expr	   *expr;			/* associated Expr node */
581 	ExprStateEvalFunc evalfunc; /* routine to run to execute node */
582 };
583 
584 /* ----------------
585  *		GenericExprState node
586  *
587  * This is used for Expr node types that need no local run-time state,
588  * but have one child Expr node.
589  * ----------------
590  */
591 typedef struct GenericExprState
592 {
593 	ExprState	xprstate;
594 	ExprState  *arg;			/* state of my child node */
595 } GenericExprState;
596 
597 /* ----------------
598  *		WholeRowVarExprState node
599  * ----------------
600  */
601 typedef struct WholeRowVarExprState
602 {
603 	ExprState	xprstate;
604 	struct PlanState *parent;	/* parent PlanState, or NULL if none */
605 	TupleDesc	wrv_tupdesc;	/* descriptor for resulting tuples */
606 	JunkFilter *wrv_junkFilter; /* JunkFilter to remove resjunk cols */
607 } WholeRowVarExprState;
608 
609 /* ----------------
610  *		AggrefExprState node
611  * ----------------
612  */
613 typedef struct AggrefExprState
614 {
615 	ExprState	xprstate;
616 	int			aggno;			/* ID number for agg within its plan node */
617 } AggrefExprState;
618 
619 /* ----------------
620  *		GroupingFuncExprState node
621  *
622  * The list of column numbers refers to the input tuples of the Agg node to
623  * which the GroupingFunc belongs, and may contain 0 for references to columns
624  * that are only present in grouping sets processed by different Agg nodes (and
625  * which are therefore always considered "grouping" here).
626  * ----------------
627  */
628 typedef struct GroupingFuncExprState
629 {
630 	ExprState	xprstate;
631 	struct AggState *aggstate;
632 	List	   *clauses;		/* integer list of column numbers */
633 } GroupingFuncExprState;
634 
635 /* ----------------
636  *		WindowFuncExprState node
637  * ----------------
638  */
639 typedef struct WindowFuncExprState
640 {
641 	ExprState	xprstate;
642 	List	   *args;			/* states of argument expressions */
643 	ExprState  *aggfilter;		/* FILTER expression */
644 	int			wfuncno;		/* ID number for wfunc within its plan node */
645 } WindowFuncExprState;
646 
647 /* ----------------
648  *		ArrayRefExprState node
649  *
650  * Note: array types can be fixed-length (typlen > 0), but only when the
651  * element type is itself fixed-length.  Otherwise they are varlena structures
652  * and have typlen = -1.  In any case, an array type is never pass-by-value.
653  * ----------------
654  */
655 typedef struct ArrayRefExprState
656 {
657 	ExprState	xprstate;
658 	List	   *refupperindexpr;	/* states for child nodes */
659 	List	   *reflowerindexpr;
660 	ExprState  *refexpr;
661 	ExprState  *refassgnexpr;
662 	int16		refattrlength;	/* typlen of array type */
663 	int16		refelemlength;	/* typlen of the array element type */
664 	bool		refelembyval;	/* is the element type pass-by-value? */
665 	char		refelemalign;	/* typalign of the element type */
666 } ArrayRefExprState;
667 
668 /* ----------------
669  *		FuncExprState node
670  *
671  * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
672  * and NullIf nodes; be careful to check what xprstate.expr is actually
673  * pointing at!
674  * ----------------
675  */
676 typedef struct FuncExprState
677 {
678 	ExprState	xprstate;
679 	List	   *args;			/* states of argument expressions */
680 
681 	/*
682 	 * Function manager's lookup info for the target function.  If func.fn_oid
683 	 * is InvalidOid, we haven't initialized it yet (nor any of the following
684 	 * fields).
685 	 */
686 	FmgrInfo	func;
687 
688 	/*
689 	 * For a set-returning function (SRF) that returns a tuplestore, we keep
690 	 * the tuplestore here and dole out the result rows one at a time. The
691 	 * slot holds the row currently being returned.
692 	 */
693 	Tuplestorestate *funcResultStore;
694 	TupleTableSlot *funcResultSlot;
695 
696 	/*
697 	 * In some cases we need to compute a tuple descriptor for the function's
698 	 * output.  If so, it's stored here.
699 	 */
700 	TupleDesc	funcResultDesc;
701 	bool		funcReturnsTuple;		/* valid when funcResultDesc isn't
702 										 * NULL */
703 
704 	/*
705 	 * setArgsValid is true when we are evaluating a set-returning function
706 	 * that uses value-per-call mode and we are in the middle of a call
707 	 * series; we want to pass the same argument values to the function again
708 	 * (and again, until it returns ExprEndResult).  This indicates that
709 	 * fcinfo_data already contains valid argument data.
710 	 */
711 	bool		setArgsValid;
712 
713 	/*
714 	 * Flag to remember whether we found a set-valued argument to the
715 	 * function. This causes the function result to be a set as well. Valid
716 	 * only when setArgsValid is true or funcResultStore isn't NULL.
717 	 */
718 	bool		setHasSetArg;	/* some argument returns a set */
719 
720 	/*
721 	 * Flag to remember whether we have registered a shutdown callback for
722 	 * this FuncExprState.  We do so only if funcResultStore or setArgsValid
723 	 * has been set at least once (since all the callback is for is to release
724 	 * the tuplestore or clear setArgsValid).
725 	 */
726 	bool		shutdown_reg;	/* a shutdown callback is registered */
727 
728 	/*
729 	 * Call parameter structure for the function.  This has been initialized
730 	 * (by InitFunctionCallInfoData) if func.fn_oid is valid.  It also saves
731 	 * argument values between calls, when setArgsValid is true.
732 	 */
733 	FunctionCallInfoData fcinfo_data;
734 } FuncExprState;
735 
736 /* ----------------
737  *		ScalarArrayOpExprState node
738  *
739  * This is a FuncExprState plus some additional data.
740  * ----------------
741  */
742 typedef struct ScalarArrayOpExprState
743 {
744 	FuncExprState fxprstate;
745 	/* Cached info about array element type */
746 	Oid			element_type;
747 	int16		typlen;
748 	bool		typbyval;
749 	char		typalign;
750 } ScalarArrayOpExprState;
751 
752 /* ----------------
753  *		BoolExprState node
754  * ----------------
755  */
756 typedef struct BoolExprState
757 {
758 	ExprState	xprstate;
759 	List	   *args;			/* states of argument expression(s) */
760 } BoolExprState;
761 
762 /* ----------------
763  *		SubPlanState node
764  * ----------------
765  */
766 typedef struct SubPlanState
767 {
768 	ExprState	xprstate;
769 	struct PlanState *planstate;	/* subselect plan's state tree */
770 	struct PlanState *parent;	/* parent plan node's state tree */
771 	ExprState  *testexpr;		/* state of combining expression */
772 	List	   *args;			/* states of argument expression(s) */
773 	HeapTuple	curTuple;		/* copy of most recent tuple from subplan */
774 	Datum		curArray;		/* most recent array from ARRAY() subplan */
775 	/* these are used when hashing the subselect's output: */
776 	ProjectionInfo *projLeft;	/* for projecting lefthand exprs */
777 	ProjectionInfo *projRight;	/* for projecting subselect output */
778 	TupleHashTable hashtable;	/* hash table for no-nulls subselect rows */
779 	TupleHashTable hashnulls;	/* hash table for rows with null(s) */
780 	bool		havehashrows;	/* TRUE if hashtable is not empty */
781 	bool		havenullrows;	/* TRUE if hashnulls is not empty */
782 	MemoryContext hashtablecxt; /* memory context containing hash tables */
783 	MemoryContext hashtempcxt;	/* temp memory context for hash tables */
784 	ExprContext *innerecontext; /* econtext for computing inner tuples */
785 	/* each of the following fields is an array of length numCols: */
786 	AttrNumber *keyColIdx;		/* control data for hash tables */
787 	FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */
788 	FmgrInfo   *tab_eq_funcs;	/* equality functions for table datatype(s) */
789 	FmgrInfo   *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
790 	FmgrInfo   *cur_eq_funcs;	/* equality functions for LHS vs. table */
791 	int			numCols;		/* number of columns being hashed */
792 } SubPlanState;
793 
794 /* ----------------
795  *		AlternativeSubPlanState node
796  * ----------------
797  */
798 typedef struct AlternativeSubPlanState
799 {
800 	ExprState	xprstate;
801 	List	   *subplans;		/* states of alternative subplans */
802 	int			active;			/* list index of the one we're using */
803 } AlternativeSubPlanState;
804 
805 /* ----------------
806  *		FieldSelectState node
807  * ----------------
808  */
809 typedef struct FieldSelectState
810 {
811 	ExprState	xprstate;
812 	ExprState  *arg;			/* input expression */
813 	TupleDesc	argdesc;		/* tupdesc for most recent input */
814 } FieldSelectState;
815 
816 /* ----------------
817  *		FieldStoreState node
818  * ----------------
819  */
820 typedef struct FieldStoreState
821 {
822 	ExprState	xprstate;
823 	ExprState  *arg;			/* input tuple value */
824 	List	   *newvals;		/* new value(s) for field(s) */
825 	TupleDesc	argdesc;		/* tupdesc for most recent input */
826 } FieldStoreState;
827 
828 /* ----------------
829  *		CoerceViaIOState node
830  * ----------------
831  */
832 typedef struct CoerceViaIOState
833 {
834 	ExprState	xprstate;
835 	ExprState  *arg;			/* input expression */
836 	FmgrInfo	outfunc;		/* lookup info for source output function */
837 	FmgrInfo	infunc;			/* lookup info for result input function */
838 	Oid			intypioparam;	/* argument needed for input function */
839 } CoerceViaIOState;
840 
841 /* ----------------
842  *		ArrayCoerceExprState node
843  * ----------------
844  */
845 typedef struct ArrayCoerceExprState
846 {
847 	ExprState	xprstate;
848 	ExprState  *arg;			/* input array value */
849 	Oid			resultelemtype; /* element type of result array */
850 	FmgrInfo	elemfunc;		/* lookup info for element coercion function */
851 	/* use struct pointer to avoid including array.h here */
852 	struct ArrayMapState *amstate;		/* workspace for array_map */
853 } ArrayCoerceExprState;
854 
855 /* ----------------
856  *		ConvertRowtypeExprState node
857  * ----------------
858  */
859 typedef struct ConvertRowtypeExprState
860 {
861 	ExprState	xprstate;
862 	ExprState  *arg;			/* input tuple value */
863 	TupleDesc	indesc;			/* tupdesc for source rowtype */
864 	TupleDesc	outdesc;		/* tupdesc for result rowtype */
865 	/* use "struct" so we needn't include tupconvert.h here */
866 	struct TupleConversionMap *map;
867 	bool		initialized;
868 } ConvertRowtypeExprState;
869 
870 /* ----------------
871  *		CaseExprState node
872  * ----------------
873  */
874 typedef struct CaseExprState
875 {
876 	ExprState	xprstate;
877 	ExprState  *arg;			/* implicit equality comparison argument */
878 	List	   *args;			/* the arguments (list of WHEN clauses) */
879 	ExprState  *defresult;		/* the default result (ELSE clause) */
880 	int16		argtyplen;		/* if arg is provided, its typlen */
881 } CaseExprState;
882 
883 /* ----------------
884  *		CaseWhenState node
885  * ----------------
886  */
887 typedef struct CaseWhenState
888 {
889 	ExprState	xprstate;
890 	ExprState  *expr;			/* condition expression */
891 	ExprState  *result;			/* substitution result */
892 } CaseWhenState;
893 
894 /* ----------------
895  *		ArrayExprState node
896  *
897  * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
898  * arrays.
899  * ----------------
900  */
901 typedef struct ArrayExprState
902 {
903 	ExprState	xprstate;
904 	List	   *elements;		/* states for child nodes */
905 	int16		elemlength;		/* typlen of the array element type */
906 	bool		elembyval;		/* is the element type pass-by-value? */
907 	char		elemalign;		/* typalign of the element type */
908 } ArrayExprState;
909 
910 /* ----------------
911  *		RowExprState node
912  * ----------------
913  */
914 typedef struct RowExprState
915 {
916 	ExprState	xprstate;
917 	List	   *args;			/* the arguments */
918 	TupleDesc	tupdesc;		/* descriptor for result tuples */
919 } RowExprState;
920 
921 /* ----------------
922  *		RowCompareExprState node
923  * ----------------
924  */
925 typedef struct RowCompareExprState
926 {
927 	ExprState	xprstate;
928 	List	   *largs;			/* the left-hand input arguments */
929 	List	   *rargs;			/* the right-hand input arguments */
930 	FmgrInfo   *funcs;			/* array of comparison function info */
931 	Oid		   *collations;		/* array of collations to use */
932 } RowCompareExprState;
933 
934 /* ----------------
935  *		CoalesceExprState node
936  * ----------------
937  */
938 typedef struct CoalesceExprState
939 {
940 	ExprState	xprstate;
941 	List	   *args;			/* the arguments */
942 } CoalesceExprState;
943 
944 /* ----------------
945  *		MinMaxExprState node
946  * ----------------
947  */
948 typedef struct MinMaxExprState
949 {
950 	ExprState	xprstate;
951 	List	   *args;			/* the arguments */
952 	FmgrInfo	cfunc;			/* lookup info for comparison func */
953 } MinMaxExprState;
954 
955 /* ----------------
956  *		XmlExprState node
957  * ----------------
958  */
959 typedef struct XmlExprState
960 {
961 	ExprState	xprstate;
962 	List	   *named_args;		/* ExprStates for named arguments */
963 	List	   *args;			/* ExprStates for other arguments */
964 } XmlExprState;
965 
966 /* ----------------
967  *		NullTestState node
968  * ----------------
969  */
970 typedef struct NullTestState
971 {
972 	ExprState	xprstate;
973 	ExprState  *arg;			/* input expression */
974 	/* used only if input is of composite type: */
975 	TupleDesc	argdesc;		/* tupdesc for most recent input */
976 } NullTestState;
977 
978 /* ----------------
979  *		CoerceToDomainState node
980  * ----------------
981  */
982 typedef struct CoerceToDomainState
983 {
984 	ExprState	xprstate;
985 	ExprState  *arg;			/* input expression */
986 	/* Cached set of constraints that need to be checked */
987 	/* use struct pointer to avoid including typcache.h here */
988 	struct DomainConstraintRef *constraint_ref;
989 } CoerceToDomainState;
990 
991 /*
992  * DomainConstraintState - one item to check during CoerceToDomain
993  *
994  * Note: this is just a Node, and not an ExprState, because it has no
995  * corresponding Expr to link to.  Nonetheless it is part of an ExprState
996  * tree, so we give it a name following the xxxState convention.
997  */
998 typedef enum DomainConstraintType
999 {
1000 	DOM_CONSTRAINT_NOTNULL,
1001 	DOM_CONSTRAINT_CHECK
1002 } DomainConstraintType;
1003 
1004 typedef struct DomainConstraintState
1005 {
1006 	NodeTag		type;
1007 	DomainConstraintType constrainttype;		/* constraint type */
1008 	char	   *name;			/* name of constraint (for error msgs) */
1009 	ExprState  *check_expr;		/* for CHECK, a boolean expression */
1010 } DomainConstraintState;
1011 
1012 
1013 /* ----------------------------------------------------------------
1014  *				 Executor State Trees
1015  *
1016  * An executing query has a PlanState tree paralleling the Plan tree
1017  * that describes the plan.
1018  * ----------------------------------------------------------------
1019  */
1020 
1021 /* ----------------
1022  *		PlanState node
1023  *
1024  * We never actually instantiate any PlanState nodes; this is just the common
1025  * abstract superclass for all PlanState-type nodes.
1026  * ----------------
1027  */
1028 typedef struct PlanState
1029 {
1030 	NodeTag		type;
1031 
1032 	Plan	   *plan;			/* associated Plan node */
1033 
1034 	EState	   *state;			/* at execution time, states of individual
1035 								 * nodes point to one EState for the whole
1036 								 * top-level plan */
1037 
1038 	Instrumentation *instrument;	/* Optional runtime stats for this node */
1039 	WorkerInstrumentation *worker_instrument;	/* per-worker instrumentation */
1040 
1041 	/*
1042 	 * Common structural data for all Plan types.  These links to subsidiary
1043 	 * state trees parallel links in the associated plan tree (except for the
1044 	 * subPlan list, which does not exist in the plan tree).
1045 	 */
1046 	List	   *targetlist;		/* target list to be computed at this node */
1047 	List	   *qual;			/* implicitly-ANDed qual conditions */
1048 	struct PlanState *lefttree; /* input plan tree(s) */
1049 	struct PlanState *righttree;
1050 	List	   *initPlan;		/* Init SubPlanState nodes (un-correlated expr
1051 								 * subselects) */
1052 	List	   *subPlan;		/* SubPlanState nodes in my expressions */
1053 
1054 	/*
1055 	 * State for management of parameter-change-driven rescanning
1056 	 */
1057 	Bitmapset  *chgParam;		/* set of IDs of changed Params */
1058 
1059 	/*
1060 	 * Other run-time state needed by most if not all node types.
1061 	 */
1062 	TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
1063 	ExprContext *ps_ExprContext;	/* node's expression-evaluation context */
1064 	ProjectionInfo *ps_ProjInfo;	/* info for doing tuple projection */
1065 	bool		ps_TupFromTlist;/* state flag for processing set-valued
1066 								 * functions in targetlist */
1067 } PlanState;
1068 
1069 /* ----------------
1070  *	these are defined to avoid confusion problems with "left"
1071  *	and "right" and "inner" and "outer".  The convention is that
1072  *	the "left" plan is the "outer" plan and the "right" plan is
1073  *	the inner plan, but these make the code more readable.
1074  * ----------------
1075  */
1076 #define innerPlanState(node)		(((PlanState *)(node))->righttree)
1077 #define outerPlanState(node)		(((PlanState *)(node))->lefttree)
1078 
1079 /* Macros for inline access to certain instrumentation counters */
1080 #define InstrCountFiltered1(node, delta) \
1081 	do { \
1082 		if (((PlanState *)(node))->instrument) \
1083 			((PlanState *)(node))->instrument->nfiltered1 += (delta); \
1084 	} while(0)
1085 #define InstrCountFiltered2(node, delta) \
1086 	do { \
1087 		if (((PlanState *)(node))->instrument) \
1088 			((PlanState *)(node))->instrument->nfiltered2 += (delta); \
1089 	} while(0)
1090 
1091 /*
1092  * EPQState is state for executing an EvalPlanQual recheck on a candidate
1093  * tuple in ModifyTable or LockRows.  The estate and planstate fields are
1094  * NULL if inactive.
1095  */
1096 typedef struct EPQState
1097 {
1098 	EState	   *estate;			/* subsidiary EState */
1099 	PlanState  *planstate;		/* plan state tree ready to be executed */
1100 	TupleTableSlot *origslot;	/* original output tuple to be rechecked */
1101 	Plan	   *plan;			/* plan tree to be executed */
1102 	List	   *arowMarks;		/* ExecAuxRowMarks (non-locking only) */
1103 	int			epqParam;		/* ID of Param to force scan node re-eval */
1104 } EPQState;
1105 
1106 
1107 /* ----------------
1108  *	 ResultState information
1109  * ----------------
1110  */
1111 typedef struct ResultState
1112 {
1113 	PlanState	ps;				/* its first field is NodeTag */
1114 	ExprState  *resconstantqual;
1115 	bool		rs_done;		/* are we done? */
1116 	bool		rs_checkqual;	/* do we need to check the qual? */
1117 } ResultState;
1118 
1119 /* ----------------
1120  *	 ModifyTableState information
1121  * ----------------
1122  */
1123 typedef struct ModifyTableState
1124 {
1125 	PlanState	ps;				/* its first field is NodeTag */
1126 	CmdType		operation;		/* INSERT, UPDATE, or DELETE */
1127 	bool		canSetTag;		/* do we set the command tag/es_processed? */
1128 	bool		mt_done;		/* are we done? */
1129 	PlanState **mt_plans;		/* subplans (one per target rel) */
1130 	int			mt_nplans;		/* number of plans in the array */
1131 	int			mt_whichplan;	/* which one is being executed (0..n-1) */
1132 	ResultRelInfo *resultRelInfo;		/* per-subplan target relations */
1133 	List	  **mt_arowmarks;	/* per-subplan ExecAuxRowMark lists */
1134 	EPQState	mt_epqstate;	/* for evaluating EvalPlanQual rechecks */
1135 	bool		fireBSTriggers; /* do we need to fire stmt triggers? */
1136 	OnConflictAction mt_onconflict;		/* ON CONFLICT type */
1137 	List	   *mt_arbiterindexes;		/* unique index OIDs to arbitrate
1138 										 * taking alt path */
1139 	TupleTableSlot *mt_existing;	/* slot to store existing target tuple in */
1140 	List	   *mt_excludedtlist;		/* the excluded pseudo relation's
1141 										 * tlist  */
1142 	TupleTableSlot *mt_conflproj;		/* CONFLICT ... SET ... projection
1143 										 * target */
1144 	JunkFilter *mt_confljunk;	/* CONFLICT ... SET might need a junkfilter */
1145 } ModifyTableState;
1146 
1147 /* ----------------
1148  *	 AppendState information
1149  *
1150  *		nplans			how many plans are in the array
1151  *		whichplan		which plan is being executed (0 .. n-1)
1152  * ----------------
1153  */
1154 typedef struct AppendState
1155 {
1156 	PlanState	ps;				/* its first field is NodeTag */
1157 	PlanState **appendplans;	/* array of PlanStates for my inputs */
1158 	int			as_nplans;
1159 	int			as_whichplan;
1160 } AppendState;
1161 
1162 /* ----------------
1163  *	 MergeAppendState information
1164  *
1165  *		nplans			how many plans are in the array
1166  *		nkeys			number of sort key columns
1167  *		sortkeys		sort keys in SortSupport representation
1168  *		slots			current output tuple of each subplan
1169  *		heap			heap of active tuples
1170  *		initialized		true if we have fetched first tuple from each subplan
1171  * ----------------
1172  */
1173 typedef struct MergeAppendState
1174 {
1175 	PlanState	ps;				/* its first field is NodeTag */
1176 	PlanState **mergeplans;		/* array of PlanStates for my inputs */
1177 	int			ms_nplans;
1178 	int			ms_nkeys;
1179 	SortSupport ms_sortkeys;	/* array of length ms_nkeys */
1180 	TupleTableSlot **ms_slots;	/* array of length ms_nplans */
1181 	struct binaryheap *ms_heap; /* binary heap of slot indices */
1182 	bool		ms_initialized; /* are subplans started? */
1183 } MergeAppendState;
1184 
1185 /* ----------------
1186  *	 RecursiveUnionState information
1187  *
1188  *		RecursiveUnionState is used for performing a recursive union.
1189  *
1190  *		recursing			T when we're done scanning the non-recursive term
1191  *		intermediate_empty	T if intermediate_table is currently empty
1192  *		working_table		working table (to be scanned by recursive term)
1193  *		intermediate_table	current recursive output (next generation of WT)
1194  * ----------------
1195  */
1196 typedef struct RecursiveUnionState
1197 {
1198 	PlanState	ps;				/* its first field is NodeTag */
1199 	bool		recursing;
1200 	bool		intermediate_empty;
1201 	Tuplestorestate *working_table;
1202 	Tuplestorestate *intermediate_table;
1203 	/* Remaining fields are unused in UNION ALL case */
1204 	FmgrInfo   *eqfunctions;	/* per-grouping-field equality fns */
1205 	FmgrInfo   *hashfunctions;	/* per-grouping-field hash fns */
1206 	MemoryContext tempContext;	/* short-term context for comparisons */
1207 	TupleHashTable hashtable;	/* hash table for tuples already seen */
1208 	MemoryContext tableContext; /* memory context containing hash table */
1209 } RecursiveUnionState;
1210 
1211 /* ----------------
1212  *	 BitmapAndState information
1213  * ----------------
1214  */
1215 typedef struct BitmapAndState
1216 {
1217 	PlanState	ps;				/* its first field is NodeTag */
1218 	PlanState **bitmapplans;	/* array of PlanStates for my inputs */
1219 	int			nplans;			/* number of input plans */
1220 } BitmapAndState;
1221 
1222 /* ----------------
1223  *	 BitmapOrState information
1224  * ----------------
1225  */
1226 typedef struct BitmapOrState
1227 {
1228 	PlanState	ps;				/* its first field is NodeTag */
1229 	PlanState **bitmapplans;	/* array of PlanStates for my inputs */
1230 	int			nplans;			/* number of input plans */
1231 } BitmapOrState;
1232 
1233 /* ----------------------------------------------------------------
1234  *				 Scan State Information
1235  * ----------------------------------------------------------------
1236  */
1237 
1238 /* ----------------
1239  *	 ScanState information
1240  *
1241  *		ScanState extends PlanState for node types that represent
1242  *		scans of an underlying relation.  It can also be used for nodes
1243  *		that scan the output of an underlying plan node --- in that case,
1244  *		only ScanTupleSlot is actually useful, and it refers to the tuple
1245  *		retrieved from the subplan.
1246  *
1247  *		currentRelation    relation being scanned (NULL if none)
1248  *		currentScanDesc    current scan descriptor for scan (NULL if none)
1249  *		ScanTupleSlot	   pointer to slot in tuple table holding scan tuple
1250  * ----------------
1251  */
1252 typedef struct ScanState
1253 {
1254 	PlanState	ps;				/* its first field is NodeTag */
1255 	Relation	ss_currentRelation;
1256 	HeapScanDesc ss_currentScanDesc;
1257 	TupleTableSlot *ss_ScanTupleSlot;
1258 } ScanState;
1259 
1260 /* ----------------
1261  *	 SeqScanState information
1262  * ----------------
1263  */
1264 typedef struct SeqScanState
1265 {
1266 	ScanState	ss;				/* its first field is NodeTag */
1267 	Size		pscan_len;		/* size of parallel heap scan descriptor */
1268 } SeqScanState;
1269 
1270 /* ----------------
1271  *	 SampleScanState information
1272  * ----------------
1273  */
1274 typedef struct SampleScanState
1275 {
1276 	ScanState	ss;
1277 	List	   *args;			/* expr states for TABLESAMPLE params */
1278 	ExprState  *repeatable;		/* expr state for REPEATABLE expr */
1279 	/* use struct pointer to avoid including tsmapi.h here */
1280 	struct TsmRoutine *tsmroutine;		/* descriptor for tablesample method */
1281 	void	   *tsm_state;		/* tablesample method can keep state here */
1282 	bool		use_bulkread;	/* use bulkread buffer access strategy? */
1283 	bool		use_pagemode;	/* use page-at-a-time visibility checking? */
1284 	bool		begun;			/* false means need to call BeginSampleScan */
1285 	uint32		seed;			/* random seed */
1286 } SampleScanState;
1287 
1288 /*
1289  * These structs store information about index quals that don't have simple
1290  * constant right-hand sides.  See comments for ExecIndexBuildScanKeys()
1291  * for discussion.
1292  */
1293 typedef struct
1294 {
1295 	ScanKey		scan_key;		/* scankey to put value into */
1296 	ExprState  *key_expr;		/* expr to evaluate to get value */
1297 	bool		key_toastable;	/* is expr's result a toastable datatype? */
1298 } IndexRuntimeKeyInfo;
1299 
1300 typedef struct
1301 {
1302 	ScanKey		scan_key;		/* scankey to put value into */
1303 	ExprState  *array_expr;		/* expr to evaluate to get array value */
1304 	int			next_elem;		/* next array element to use */
1305 	int			num_elems;		/* number of elems in current array value */
1306 	Datum	   *elem_values;	/* array of num_elems Datums */
1307 	bool	   *elem_nulls;		/* array of num_elems is-null flags */
1308 } IndexArrayKeyInfo;
1309 
1310 /* ----------------
1311  *	 IndexScanState information
1312  *
1313  *		indexqualorig	   execution state for indexqualorig expressions
1314  *		indexorderbyorig   execution state for indexorderbyorig expressions
1315  *		ScanKeys		   Skey structures for index quals
1316  *		NumScanKeys		   number of ScanKeys
1317  *		OrderByKeys		   Skey structures for index ordering operators
1318  *		NumOrderByKeys	   number of OrderByKeys
1319  *		RuntimeKeys		   info about Skeys that must be evaluated at runtime
1320  *		NumRuntimeKeys	   number of RuntimeKeys
1321  *		RuntimeKeysReady   true if runtime Skeys have been computed
1322  *		RuntimeContext	   expr context for evaling runtime Skeys
1323  *		RelationDesc	   index relation descriptor
1324  *		ScanDesc		   index scan descriptor
1325  *
1326  *		ReorderQueue	   tuples that need reordering due to re-check
1327  *		ReachedEnd		   have we fetched all tuples from index already?
1328  *		OrderByValues	   values of ORDER BY exprs of last fetched tuple
1329  *		OrderByNulls	   null flags for OrderByValues
1330  *		SortSupport		   for reordering ORDER BY exprs
1331  *		OrderByTypByVals   is the datatype of order by expression pass-by-value?
1332  *		OrderByTypLens	   typlens of the datatypes of order by expressions
1333  * ----------------
1334  */
1335 typedef struct IndexScanState
1336 {
1337 	ScanState	ss;				/* its first field is NodeTag */
1338 	List	   *indexqualorig;
1339 	List	   *indexorderbyorig;
1340 	ScanKey		iss_ScanKeys;
1341 	int			iss_NumScanKeys;
1342 	ScanKey		iss_OrderByKeys;
1343 	int			iss_NumOrderByKeys;
1344 	IndexRuntimeKeyInfo *iss_RuntimeKeys;
1345 	int			iss_NumRuntimeKeys;
1346 	bool		iss_RuntimeKeysReady;
1347 	ExprContext *iss_RuntimeContext;
1348 	Relation	iss_RelationDesc;
1349 	IndexScanDesc iss_ScanDesc;
1350 
1351 	/* These are needed for re-checking ORDER BY expr ordering */
1352 	pairingheap *iss_ReorderQueue;
1353 	bool		iss_ReachedEnd;
1354 	Datum	   *iss_OrderByValues;
1355 	bool	   *iss_OrderByNulls;
1356 	SortSupport iss_SortSupport;
1357 	bool	   *iss_OrderByTypByVals;
1358 	int16	   *iss_OrderByTypLens;
1359 } IndexScanState;
1360 
1361 /* ----------------
1362  *	 IndexOnlyScanState information
1363  *
1364  *		indexqual		   execution state for indexqual expressions
1365  *		ScanKeys		   Skey structures for index quals
1366  *		NumScanKeys		   number of ScanKeys
1367  *		OrderByKeys		   Skey structures for index ordering operators
1368  *		NumOrderByKeys	   number of OrderByKeys
1369  *		RuntimeKeys		   info about Skeys that must be evaluated at runtime
1370  *		NumRuntimeKeys	   number of RuntimeKeys
1371  *		RuntimeKeysReady   true if runtime Skeys have been computed
1372  *		RuntimeContext	   expr context for evaling runtime Skeys
1373  *		RelationDesc	   index relation descriptor
1374  *		ScanDesc		   index scan descriptor
1375  *		VMBuffer		   buffer in use for visibility map testing, if any
1376  *		HeapFetches		   number of tuples we were forced to fetch from heap
1377  * ----------------
1378  */
1379 typedef struct IndexOnlyScanState
1380 {
1381 	ScanState	ss;				/* its first field is NodeTag */
1382 	List	   *indexqual;
1383 	ScanKey		ioss_ScanKeys;
1384 	int			ioss_NumScanKeys;
1385 	ScanKey		ioss_OrderByKeys;
1386 	int			ioss_NumOrderByKeys;
1387 	IndexRuntimeKeyInfo *ioss_RuntimeKeys;
1388 	int			ioss_NumRuntimeKeys;
1389 	bool		ioss_RuntimeKeysReady;
1390 	ExprContext *ioss_RuntimeContext;
1391 	Relation	ioss_RelationDesc;
1392 	IndexScanDesc ioss_ScanDesc;
1393 	Buffer		ioss_VMBuffer;
1394 	long		ioss_HeapFetches;
1395 } IndexOnlyScanState;
1396 
1397 /* ----------------
1398  *	 BitmapIndexScanState information
1399  *
1400  *		result			   bitmap to return output into, or NULL
1401  *		ScanKeys		   Skey structures for index quals
1402  *		NumScanKeys		   number of ScanKeys
1403  *		RuntimeKeys		   info about Skeys that must be evaluated at runtime
1404  *		NumRuntimeKeys	   number of RuntimeKeys
1405  *		ArrayKeys		   info about Skeys that come from ScalarArrayOpExprs
1406  *		NumArrayKeys	   number of ArrayKeys
1407  *		RuntimeKeysReady   true if runtime Skeys have been computed
1408  *		RuntimeContext	   expr context for evaling runtime Skeys
1409  *		RelationDesc	   index relation descriptor
1410  *		ScanDesc		   index scan descriptor
1411  * ----------------
1412  */
1413 typedef struct BitmapIndexScanState
1414 {
1415 	ScanState	ss;				/* its first field is NodeTag */
1416 	TIDBitmap  *biss_result;
1417 	ScanKey		biss_ScanKeys;
1418 	int			biss_NumScanKeys;
1419 	IndexRuntimeKeyInfo *biss_RuntimeKeys;
1420 	int			biss_NumRuntimeKeys;
1421 	IndexArrayKeyInfo *biss_ArrayKeys;
1422 	int			biss_NumArrayKeys;
1423 	bool		biss_RuntimeKeysReady;
1424 	ExprContext *biss_RuntimeContext;
1425 	Relation	biss_RelationDesc;
1426 	IndexScanDesc biss_ScanDesc;
1427 } BitmapIndexScanState;
1428 
1429 /* ----------------
1430  *	 BitmapHeapScanState information
1431  *
1432  *		bitmapqualorig	   execution state for bitmapqualorig expressions
1433  *		tbm				   bitmap obtained from child index scan(s)
1434  *		tbmiterator		   iterator for scanning current pages
1435  *		tbmres			   current-page data
1436  *		exact_pages		   total number of exact pages retrieved
1437  *		lossy_pages		   total number of lossy pages retrieved
1438  *		prefetch_iterator  iterator for prefetching ahead of current page
1439  *		prefetch_pages	   # pages prefetch iterator is ahead of current
1440  *		prefetch_target    current target prefetch distance
1441  *		prefetch_maximum   maximum value for prefetch_target
1442  * ----------------
1443  */
1444 typedef struct BitmapHeapScanState
1445 {
1446 	ScanState	ss;				/* its first field is NodeTag */
1447 	List	   *bitmapqualorig;
1448 	TIDBitmap  *tbm;
1449 	TBMIterator *tbmiterator;
1450 	TBMIterateResult *tbmres;
1451 	long		exact_pages;
1452 	long		lossy_pages;
1453 	TBMIterator *prefetch_iterator;
1454 	int			prefetch_pages;
1455 	int			prefetch_target;
1456 	int			prefetch_maximum;
1457 } BitmapHeapScanState;
1458 
1459 /* ----------------
1460  *	 TidScanState information
1461  *
1462  *		isCurrentOf    scan has a CurrentOfExpr qual
1463  *		NumTids		   number of tids in this scan
1464  *		TidPtr		   index of currently fetched tid
1465  *		TidList		   evaluated item pointers (array of size NumTids)
1466  * ----------------
1467  */
1468 typedef struct TidScanState
1469 {
1470 	ScanState	ss;				/* its first field is NodeTag */
1471 	List	   *tss_tidquals;	/* list of ExprState nodes */
1472 	bool		tss_isCurrentOf;
1473 	int			tss_NumTids;
1474 	int			tss_TidPtr;
1475 	ItemPointerData *tss_TidList;
1476 	HeapTupleData tss_htup;
1477 } TidScanState;
1478 
1479 /* ----------------
1480  *	 SubqueryScanState information
1481  *
1482  *		SubqueryScanState is used for scanning a sub-query in the range table.
1483  *		ScanTupleSlot references the current output tuple of the sub-query.
1484  * ----------------
1485  */
1486 typedef struct SubqueryScanState
1487 {
1488 	ScanState	ss;				/* its first field is NodeTag */
1489 	PlanState  *subplan;
1490 } SubqueryScanState;
1491 
1492 /* ----------------
1493  *	 FunctionScanState information
1494  *
1495  *		Function nodes are used to scan the results of a
1496  *		function appearing in FROM (typically a function returning set).
1497  *
1498  *		eflags				node's capability flags
1499  *		ordinality			is this scan WITH ORDINALITY?
1500  *		simple				true if we have 1 function and no ordinality
1501  *		ordinal				current ordinal column value
1502  *		nfuncs				number of functions being executed
1503  *		funcstates			per-function execution states (private in
1504  *							nodeFunctionscan.c)
1505  *		argcontext			memory context to evaluate function arguments in
1506  * ----------------
1507  */
1508 struct FunctionScanPerFuncState;
1509 
1510 typedef struct FunctionScanState
1511 {
1512 	ScanState	ss;				/* its first field is NodeTag */
1513 	int			eflags;
1514 	bool		ordinality;
1515 	bool		simple;
1516 	int64		ordinal;
1517 	int			nfuncs;
1518 	struct FunctionScanPerFuncState *funcstates;		/* array of length
1519 														 * nfuncs */
1520 	MemoryContext argcontext;
1521 } FunctionScanState;
1522 
1523 /* ----------------
1524  *	 ValuesScanState information
1525  *
1526  *		ValuesScan nodes are used to scan the results of a VALUES list
1527  *
1528  *		rowcontext			per-expression-list context
1529  *		exprlists			array of expression lists being evaluated
1530  *		exprstatelists		array of expression state lists, for SubPlans only
1531  *		array_len			size of above arrays
1532  *		curr_idx			current array index (0-based)
1533  *
1534  *	Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
1535  *	expressions attached to the node.  We create a second ExprContext,
1536  *	rowcontext, in which to build the executor expression state for each
1537  *	Values sublist.  Resetting this context lets us get rid of expression
1538  *	state for each row, avoiding major memory leakage over a long values list.
1539  *	However, that doesn't work for sublists containing SubPlans, because a
1540  *	SubPlan has to be connected up to the outer plan tree to work properly.
1541  *	Therefore, for only those sublists containing SubPlans, we do expression
1542  *	state construction at executor start, and store those pointers in
1543  *	exprstatelists[].  NULL entries in that array correspond to simple
1544  *	subexpressions that are handled as described above.
1545  * ----------------
1546  */
1547 typedef struct ValuesScanState
1548 {
1549 	ScanState	ss;				/* its first field is NodeTag */
1550 	ExprContext *rowcontext;
1551 	List	  **exprlists;
1552 	int			array_len;
1553 	int			curr_idx;
1554 	/* in back branches, put this at the end to avoid ABI break: */
1555 	List	  **exprstatelists;
1556 } ValuesScanState;
1557 
1558 /* ----------------
1559  *	 CteScanState information
1560  *
1561  *		CteScan nodes are used to scan a CommonTableExpr query.
1562  *
1563  * Multiple CteScan nodes can read out from the same CTE query.  We use
1564  * a tuplestore to hold rows that have been read from the CTE query but
1565  * not yet consumed by all readers.
1566  * ----------------
1567  */
1568 typedef struct CteScanState
1569 {
1570 	ScanState	ss;				/* its first field is NodeTag */
1571 	int			eflags;			/* capability flags to pass to tuplestore */
1572 	int			readptr;		/* index of my tuplestore read pointer */
1573 	PlanState  *cteplanstate;	/* PlanState for the CTE query itself */
1574 	/* Link to the "leader" CteScanState (possibly this same node) */
1575 	struct CteScanState *leader;
1576 	/* The remaining fields are only valid in the "leader" CteScanState */
1577 	Tuplestorestate *cte_table; /* rows already read from the CTE query */
1578 	bool		eof_cte;		/* reached end of CTE query? */
1579 } CteScanState;
1580 
1581 /* ----------------
1582  *	 WorkTableScanState information
1583  *
1584  *		WorkTableScan nodes are used to scan the work table created by
1585  *		a RecursiveUnion node.  We locate the RecursiveUnion node
1586  *		during executor startup.
1587  * ----------------
1588  */
1589 typedef struct WorkTableScanState
1590 {
1591 	ScanState	ss;				/* its first field is NodeTag */
1592 	RecursiveUnionState *rustate;
1593 } WorkTableScanState;
1594 
1595 /* ----------------
1596  *	 ForeignScanState information
1597  *
1598  *		ForeignScan nodes are used to scan foreign-data tables.
1599  * ----------------
1600  */
1601 typedef struct ForeignScanState
1602 {
1603 	ScanState	ss;				/* its first field is NodeTag */
1604 	List	   *fdw_recheck_quals;		/* original quals not in ss.ps.qual */
1605 	Size		pscan_len;		/* size of parallel coordination information */
1606 	/* use struct pointer to avoid including fdwapi.h here */
1607 	struct FdwRoutine *fdwroutine;
1608 	void	   *fdw_state;		/* foreign-data wrapper can keep state here */
1609 } ForeignScanState;
1610 
1611 /* ----------------
1612  *	 CustomScanState information
1613  *
1614  *		CustomScan nodes are used to execute custom code within executor.
1615  *
1616  * Core code must avoid assuming that the CustomScanState is only as large as
1617  * the structure declared here; providers are allowed to make it the first
1618  * element in a larger structure, and typically would need to do so.  The
1619  * struct is actually allocated by the CreateCustomScanState method associated
1620  * with the plan node.  Any additional fields can be initialized there, or in
1621  * the BeginCustomScan method.
1622  * ----------------
1623  */
1624 struct CustomExecMethods;
1625 
1626 typedef struct CustomScanState
1627 {
1628 	ScanState	ss;
1629 	uint32		flags;			/* mask of CUSTOMPATH_* flags, see
1630 								 * nodes/extensible.h */
1631 	List	   *custom_ps;		/* list of child PlanState nodes, if any */
1632 	Size		pscan_len;		/* size of parallel coordination information */
1633 	const struct CustomExecMethods *methods;
1634 } CustomScanState;
1635 
1636 /* ----------------------------------------------------------------
1637  *				 Join State Information
1638  * ----------------------------------------------------------------
1639  */
1640 
1641 /* ----------------
1642  *	 JoinState information
1643  *
1644  *		Superclass for state nodes of join plans.
1645  * ----------------
1646  */
1647 typedef struct JoinState
1648 {
1649 	PlanState	ps;
1650 	JoinType	jointype;
1651 	List	   *joinqual;		/* JOIN quals (in addition to ps.qual) */
1652 } JoinState;
1653 
1654 /* ----------------
1655  *	 NestLoopState information
1656  *
1657  *		NeedNewOuter	   true if need new outer tuple on next call
1658  *		MatchedOuter	   true if found a join match for current outer tuple
1659  *		NullInnerTupleSlot prepared null tuple for left outer joins
1660  * ----------------
1661  */
1662 typedef struct NestLoopState
1663 {
1664 	JoinState	js;				/* its first field is NodeTag */
1665 	bool		nl_NeedNewOuter;
1666 	bool		nl_MatchedOuter;
1667 	TupleTableSlot *nl_NullInnerTupleSlot;
1668 } NestLoopState;
1669 
1670 /* ----------------
1671  *	 MergeJoinState information
1672  *
1673  *		NumClauses		   number of mergejoinable join clauses
1674  *		Clauses			   info for each mergejoinable clause
1675  *		JoinState		   current state of ExecMergeJoin state machine
1676  *		ExtraMarks		   true to issue extra Mark operations on inner scan
1677  *		ConstFalseJoin	   true if we have a constant-false joinqual
1678  *		FillOuter		   true if should emit unjoined outer tuples anyway
1679  *		FillInner		   true if should emit unjoined inner tuples anyway
1680  *		MatchedOuter	   true if found a join match for current outer tuple
1681  *		MatchedInner	   true if found a join match for current inner tuple
1682  *		OuterTupleSlot	   slot in tuple table for cur outer tuple
1683  *		InnerTupleSlot	   slot in tuple table for cur inner tuple
1684  *		MarkedTupleSlot    slot in tuple table for marked tuple
1685  *		NullOuterTupleSlot prepared null tuple for right outer joins
1686  *		NullInnerTupleSlot prepared null tuple for left outer joins
1687  *		OuterEContext	   workspace for computing outer tuple's join values
1688  *		InnerEContext	   workspace for computing inner tuple's join values
1689  * ----------------
1690  */
1691 /* private in nodeMergejoin.c: */
1692 typedef struct MergeJoinClauseData *MergeJoinClause;
1693 
1694 typedef struct MergeJoinState
1695 {
1696 	JoinState	js;				/* its first field is NodeTag */
1697 	int			mj_NumClauses;
1698 	MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
1699 	int			mj_JoinState;
1700 	bool		mj_ExtraMarks;
1701 	bool		mj_ConstFalseJoin;
1702 	bool		mj_FillOuter;
1703 	bool		mj_FillInner;
1704 	bool		mj_MatchedOuter;
1705 	bool		mj_MatchedInner;
1706 	TupleTableSlot *mj_OuterTupleSlot;
1707 	TupleTableSlot *mj_InnerTupleSlot;
1708 	TupleTableSlot *mj_MarkedTupleSlot;
1709 	TupleTableSlot *mj_NullOuterTupleSlot;
1710 	TupleTableSlot *mj_NullInnerTupleSlot;
1711 	ExprContext *mj_OuterEContext;
1712 	ExprContext *mj_InnerEContext;
1713 } MergeJoinState;
1714 
1715 /* ----------------
1716  *	 HashJoinState information
1717  *
1718  *		hashclauses				original form of the hashjoin condition
1719  *		hj_OuterHashKeys		the outer hash keys in the hashjoin condition
1720  *		hj_InnerHashKeys		the inner hash keys in the hashjoin condition
1721  *		hj_HashOperators		the join operators in the hashjoin condition
1722  *		hj_HashTable			hash table for the hashjoin
1723  *								(NULL if table not built yet)
1724  *		hj_CurHashValue			hash value for current outer tuple
1725  *		hj_CurBucketNo			regular bucket# for current outer tuple
1726  *		hj_CurSkewBucketNo		skew bucket# for current outer tuple
1727  *		hj_CurTuple				last inner tuple matched to current outer
1728  *								tuple, or NULL if starting search
1729  *								(hj_CurXXX variables are undefined if
1730  *								OuterTupleSlot is empty!)
1731  *		hj_OuterTupleSlot		tuple slot for outer tuples
1732  *		hj_HashTupleSlot		tuple slot for inner (hashed) tuples
1733  *		hj_NullOuterTupleSlot	prepared null tuple for right/full outer joins
1734  *		hj_NullInnerTupleSlot	prepared null tuple for left/full outer joins
1735  *		hj_FirstOuterTupleSlot	first tuple retrieved from outer plan
1736  *		hj_JoinState			current state of ExecHashJoin state machine
1737  *		hj_MatchedOuter			true if found a join match for current outer
1738  *		hj_OuterNotEmpty		true if outer relation known not empty
1739  * ----------------
1740  */
1741 
1742 /* these structs are defined in executor/hashjoin.h: */
1743 typedef struct HashJoinTupleData *HashJoinTuple;
1744 typedef struct HashJoinTableData *HashJoinTable;
1745 
1746 typedef struct HashJoinState
1747 {
1748 	JoinState	js;				/* its first field is NodeTag */
1749 	List	   *hashclauses;	/* list of ExprState nodes */
1750 	List	   *hj_OuterHashKeys;		/* list of ExprState nodes */
1751 	List	   *hj_InnerHashKeys;		/* list of ExprState nodes */
1752 	List	   *hj_HashOperators;		/* list of operator OIDs */
1753 	HashJoinTable hj_HashTable;
1754 	uint32		hj_CurHashValue;
1755 	int			hj_CurBucketNo;
1756 	int			hj_CurSkewBucketNo;
1757 	HashJoinTuple hj_CurTuple;
1758 	TupleTableSlot *hj_OuterTupleSlot;
1759 	TupleTableSlot *hj_HashTupleSlot;
1760 	TupleTableSlot *hj_NullOuterTupleSlot;
1761 	TupleTableSlot *hj_NullInnerTupleSlot;
1762 	TupleTableSlot *hj_FirstOuterTupleSlot;
1763 	int			hj_JoinState;
1764 	bool		hj_MatchedOuter;
1765 	bool		hj_OuterNotEmpty;
1766 } HashJoinState;
1767 
1768 
1769 /* ----------------------------------------------------------------
1770  *				 Materialization State Information
1771  * ----------------------------------------------------------------
1772  */
1773 
1774 /* ----------------
1775  *	 MaterialState information
1776  *
1777  *		materialize nodes are used to materialize the results
1778  *		of a subplan into a temporary file.
1779  *
1780  *		ss.ss_ScanTupleSlot refers to output of underlying plan.
1781  * ----------------
1782  */
1783 typedef struct MaterialState
1784 {
1785 	ScanState	ss;				/* its first field is NodeTag */
1786 	int			eflags;			/* capability flags to pass to tuplestore */
1787 	bool		eof_underlying; /* reached end of underlying plan? */
1788 	Tuplestorestate *tuplestorestate;
1789 } MaterialState;
1790 
1791 /* ----------------
1792  *	 SortState information
1793  * ----------------
1794  */
1795 typedef struct SortState
1796 {
1797 	ScanState	ss;				/* its first field is NodeTag */
1798 	bool		randomAccess;	/* need random access to sort output? */
1799 	bool		bounded;		/* is the result set bounded? */
1800 	int64		bound;			/* if bounded, how many tuples are needed */
1801 	bool		sort_Done;		/* sort completed yet? */
1802 	bool		bounded_Done;	/* value of bounded we did the sort with */
1803 	int64		bound_Done;		/* value of bound we did the sort with */
1804 	void	   *tuplesortstate; /* private state of tuplesort.c */
1805 } SortState;
1806 
1807 /* ---------------------
1808  *	GroupState information
1809  * -------------------------
1810  */
1811 typedef struct GroupState
1812 {
1813 	ScanState	ss;				/* its first field is NodeTag */
1814 	FmgrInfo   *eqfunctions;	/* per-field lookup data for equality fns */
1815 	bool		grp_done;		/* indicates completion of Group scan */
1816 } GroupState;
1817 
1818 /* ---------------------
1819  *	AggState information
1820  *
1821  *	ss.ss_ScanTupleSlot refers to output of underlying plan.
1822  *
1823  *	Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1824  *	ecxt_aggnulls arrays, which hold the computed agg values for the current
1825  *	input group during evaluation of an Agg node's output tuple(s).  We
1826  *	create a second ExprContext, tmpcontext, in which to evaluate input
1827  *	expressions and run the aggregate transition functions.
1828  * -------------------------
1829  */
1830 /* these structs are private in nodeAgg.c: */
1831 typedef struct AggStatePerAggData *AggStatePerAgg;
1832 typedef struct AggStatePerTransData *AggStatePerTrans;
1833 typedef struct AggStatePerGroupData *AggStatePerGroup;
1834 typedef struct AggStatePerPhaseData *AggStatePerPhase;
1835 
1836 typedef struct AggState
1837 {
1838 	ScanState	ss;				/* its first field is NodeTag */
1839 	List	   *aggs;			/* all Aggref nodes in targetlist & quals */
1840 	int			numaggs;		/* length of list (could be zero!) */
1841 	int			numtrans;		/* number of pertrans items */
1842 	AggSplit	aggsplit;		/* agg-splitting mode, see nodes.h */
1843 	AggStatePerPhase phase;		/* pointer to current phase data */
1844 	int			numphases;		/* number of phases */
1845 	int			current_phase;	/* current phase number */
1846 	FmgrInfo   *hashfunctions;	/* per-grouping-field hash fns */
1847 	AggStatePerAgg peragg;		/* per-Aggref information */
1848 	AggStatePerTrans pertrans;	/* per-Trans state information */
1849 	ExprContext **aggcontexts;	/* econtexts for long-lived data (per GS) */
1850 	ExprContext *tmpcontext;	/* econtext for input expressions */
1851 	AggStatePerTrans curpertrans;	/* currently active trans state, if any */
1852 	bool		input_done;		/* indicates end of input */
1853 	bool		agg_done;		/* indicates completion of Agg scan */
1854 	int			projected_set;	/* The last projected grouping set */
1855 	int			current_set;	/* The current grouping set being evaluated */
1856 	Bitmapset  *grouped_cols;	/* grouped cols in current projection */
1857 	List	   *all_grouped_cols;		/* list of all grouped cols in DESC
1858 										 * order */
1859 	/* These fields are for grouping set phase data */
1860 	int			maxsets;		/* The max number of sets in any phase */
1861 	AggStatePerPhase phases;	/* array of all phases */
1862 	Tuplesortstate *sort_in;	/* sorted input to phases > 0 */
1863 	Tuplesortstate *sort_out;	/* input is copied here for next phase */
1864 	TupleTableSlot *sort_slot;	/* slot for sort results */
1865 	/* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
1866 	AggStatePerGroup pergroup;	/* per-Aggref-per-group working state */
1867 	HeapTuple	grp_firstTuple; /* copy of first tuple of current group */
1868 	/* these fields are used in AGG_HASHED mode: */
1869 	TupleHashTable hashtable;	/* hash table with one entry per group */
1870 	TupleTableSlot *hashslot;	/* slot for loading hash table */
1871 	List	   *hash_needed;	/* list of columns needed in hash table */
1872 	bool		table_filled;	/* hash table filled yet? */
1873 	TupleHashIterator hashiter; /* for iterating through hash table */
1874 	AggStatePerAgg curperagg;	/* currently active aggregate, if any */
1875 } AggState;
1876 
1877 /* ----------------
1878  *	WindowAggState information
1879  * ----------------
1880  */
1881 /* these structs are private in nodeWindowAgg.c: */
1882 typedef struct WindowStatePerFuncData *WindowStatePerFunc;
1883 typedef struct WindowStatePerAggData *WindowStatePerAgg;
1884 
1885 typedef struct WindowAggState
1886 {
1887 	ScanState	ss;				/* its first field is NodeTag */
1888 
1889 	/* these fields are filled in by ExecInitExpr: */
1890 	List	   *funcs;			/* all WindowFunc nodes in targetlist */
1891 	int			numfuncs;		/* total number of window functions */
1892 	int			numaggs;		/* number that are plain aggregates */
1893 
1894 	WindowStatePerFunc perfunc; /* per-window-function information */
1895 	WindowStatePerAgg peragg;	/* per-plain-aggregate information */
1896 	FmgrInfo   *partEqfunctions;	/* equality funcs for partition columns */
1897 	FmgrInfo   *ordEqfunctions; /* equality funcs for ordering columns */
1898 	Tuplestorestate *buffer;	/* stores rows of current partition */
1899 	int			current_ptr;	/* read pointer # for current */
1900 	int64		spooled_rows;	/* total # of rows in buffer */
1901 	int64		currentpos;		/* position of current row in partition */
1902 	int64		frameheadpos;	/* current frame head position */
1903 	int64		frametailpos;	/* current frame tail position */
1904 	/* use struct pointer to avoid including windowapi.h here */
1905 	struct WindowObjectData *agg_winobj;		/* winobj for aggregate
1906 												 * fetches */
1907 	int64		aggregatedbase; /* start row for current aggregates */
1908 	int64		aggregatedupto; /* rows before this one are aggregated */
1909 
1910 	int			frameOptions;	/* frame_clause options, see WindowDef */
1911 	ExprState  *startOffset;	/* expression for starting bound offset */
1912 	ExprState  *endOffset;		/* expression for ending bound offset */
1913 	Datum		startOffsetValue;		/* result of startOffset evaluation */
1914 	Datum		endOffsetValue; /* result of endOffset evaluation */
1915 
1916 	MemoryContext partcontext;	/* context for partition-lifespan data */
1917 	MemoryContext aggcontext;	/* shared context for aggregate working data */
1918 	MemoryContext curaggcontext;	/* current aggregate's working data */
1919 	ExprContext *tmpcontext;	/* short-term evaluation context */
1920 
1921 	bool		all_first;		/* true if the scan is starting */
1922 	bool		all_done;		/* true if the scan is finished */
1923 	bool		partition_spooled;		/* true if all tuples in current
1924 										 * partition have been spooled into
1925 										 * tuplestore */
1926 	bool		more_partitions;/* true if there's more partitions after this
1927 								 * one */
1928 	bool		framehead_valid;/* true if frameheadpos is known up to date
1929 								 * for current row */
1930 	bool		frametail_valid;/* true if frametailpos is known up to date
1931 								 * for current row */
1932 
1933 	TupleTableSlot *first_part_slot;	/* first tuple of current or next
1934 										 * partition */
1935 
1936 	/* temporary slots for tuples fetched back from tuplestore */
1937 	TupleTableSlot *agg_row_slot;
1938 	TupleTableSlot *temp_slot_1;
1939 	TupleTableSlot *temp_slot_2;
1940 } WindowAggState;
1941 
1942 /* ----------------
1943  *	 UniqueState information
1944  *
1945  *		Unique nodes are used "on top of" sort nodes to discard
1946  *		duplicate tuples returned from the sort phase.  Basically
1947  *		all it does is compare the current tuple from the subplan
1948  *		with the previously fetched tuple (stored in its result slot).
1949  *		If the two are identical in all interesting fields, then
1950  *		we just fetch another tuple from the sort and try again.
1951  * ----------------
1952  */
1953 typedef struct UniqueState
1954 {
1955 	PlanState	ps;				/* its first field is NodeTag */
1956 	FmgrInfo   *eqfunctions;	/* per-field lookup data for equality fns */
1957 	MemoryContext tempContext;	/* short-term context for comparisons */
1958 } UniqueState;
1959 
1960 /* ----------------
1961  * GatherState information
1962  *
1963  *		Gather nodes launch 1 or more parallel workers, run a subplan
1964  *		in those workers, and collect the results.
1965  * ----------------
1966  */
1967 typedef struct GatherState
1968 {
1969 	PlanState	ps;				/* its first field is NodeTag */
1970 	bool		initialized;
1971 	struct ParallelExecutorInfo *pei;
1972 	int			nreaders;
1973 	int			nextreader;
1974 	int			nworkers_launched;
1975 	struct TupleQueueReader **reader;
1976 	TupleTableSlot *funnel_slot;
1977 	bool		need_to_scan_locally;
1978 } GatherState;
1979 
1980 /* ----------------
1981  *	 HashState information
1982  * ----------------
1983  */
1984 typedef struct HashState
1985 {
1986 	PlanState	ps;				/* its first field is NodeTag */
1987 	HashJoinTable hashtable;	/* hash table for the hashjoin */
1988 	List	   *hashkeys;		/* list of ExprState nodes */
1989 	/* hashkeys is same as parent's hj_InnerHashKeys */
1990 } HashState;
1991 
1992 /* ----------------
1993  *	 SetOpState information
1994  *
1995  *		Even in "sorted" mode, SetOp nodes are more complex than a simple
1996  *		Unique, since we have to count how many duplicates to return.  But
1997  *		we also support hashing, so this is really more like a cut-down
1998  *		form of Agg.
1999  * ----------------
2000  */
2001 /* this struct is private in nodeSetOp.c: */
2002 typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
2003 
2004 typedef struct SetOpState
2005 {
2006 	PlanState	ps;				/* its first field is NodeTag */
2007 	FmgrInfo   *eqfunctions;	/* per-grouping-field equality fns */
2008 	FmgrInfo   *hashfunctions;	/* per-grouping-field hash fns */
2009 	bool		setop_done;		/* indicates completion of output scan */
2010 	long		numOutput;		/* number of dups left to output */
2011 	MemoryContext tempContext;	/* short-term context for comparisons */
2012 	/* these fields are used in SETOP_SORTED mode: */
2013 	SetOpStatePerGroup pergroup;	/* per-group working state */
2014 	HeapTuple	grp_firstTuple; /* copy of first tuple of current group */
2015 	/* these fields are used in SETOP_HASHED mode: */
2016 	TupleHashTable hashtable;	/* hash table with one entry per group */
2017 	MemoryContext tableContext; /* memory context containing hash table */
2018 	bool		table_filled;	/* hash table filled yet? */
2019 	TupleHashIterator hashiter; /* for iterating through hash table */
2020 } SetOpState;
2021 
2022 /* ----------------
2023  *	 LockRowsState information
2024  *
2025  *		LockRows nodes are used to enforce FOR [KEY] UPDATE/SHARE locking.
2026  * ----------------
2027  */
2028 typedef struct LockRowsState
2029 {
2030 	PlanState	ps;				/* its first field is NodeTag */
2031 	List	   *lr_arowMarks;	/* List of ExecAuxRowMarks */
2032 	EPQState	lr_epqstate;	/* for evaluating EvalPlanQual rechecks */
2033 	HeapTuple  *lr_curtuples;	/* locked tuples (one entry per RT entry) */
2034 	int			lr_ntables;		/* length of lr_curtuples[] array */
2035 } LockRowsState;
2036 
2037 /* ----------------
2038  *	 LimitState information
2039  *
2040  *		Limit nodes are used to enforce LIMIT/OFFSET clauses.
2041  *		They just select the desired subrange of their subplan's output.
2042  *
2043  * offset is the number of initial tuples to skip (0 does nothing).
2044  * count is the number of tuples to return after skipping the offset tuples.
2045  * If no limit count was specified, count is undefined and noCount is true.
2046  * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
2047  * ----------------
2048  */
2049 typedef enum
2050 {
2051 	LIMIT_INITIAL,				/* initial state for LIMIT node */
2052 	LIMIT_RESCAN,				/* rescan after recomputing parameters */
2053 	LIMIT_EMPTY,				/* there are no returnable rows */
2054 	LIMIT_INWINDOW,				/* have returned a row in the window */
2055 	LIMIT_SUBPLANEOF,			/* at EOF of subplan (within window) */
2056 	LIMIT_WINDOWEND,			/* stepped off end of window */
2057 	LIMIT_WINDOWSTART			/* stepped off beginning of window */
2058 } LimitStateCond;
2059 
2060 typedef struct LimitState
2061 {
2062 	PlanState	ps;				/* its first field is NodeTag */
2063 	ExprState  *limitOffset;	/* OFFSET parameter, or NULL if none */
2064 	ExprState  *limitCount;		/* COUNT parameter, or NULL if none */
2065 	int64		offset;			/* current OFFSET value */
2066 	int64		count;			/* current COUNT, if any */
2067 	bool		noCount;		/* if true, ignore count */
2068 	LimitStateCond lstate;		/* state machine status, as above */
2069 	int64		position;		/* 1-based index of last tuple returned */
2070 	TupleTableSlot *subSlot;	/* tuple last obtained from subplan */
2071 } LimitState;
2072 
2073 #endif   /* EXECNODES_H */
2074