execnodes.h 37.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * execnodes.h
4
 *	  definitions for executor state nodes
5 6
 *
 *
B
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1994, Regents of the University of California
9
 *
10
 * $PostgreSQL: pgsql/src/include/nodes/execnodes.h,v 1.111 2004/01/22 02:23:21 tgl Exp $
11 12 13 14 15 16
 *
 *-------------------------------------------------------------------------
 */
#ifndef EXECNODES_H
#define EXECNODES_H

17
#include "access/relscan.h"
B
Bruce Momjian 已提交
18
#include "executor/hashjoin.h"
19
#include "executor/tuptable.h"
20
#include "fmgr.h"
21
#include "nodes/bitmapset.h"
B
Bruce Momjian 已提交
22
#include "nodes/params.h"
23
#include "nodes/plannodes.h"
24
#include "utils/hsearch.h"
25 26
#include "utils/tuplestore.h"

27 28

/* ----------------
29
 *	  IndexInfo information
30
 *
31
 *		this struct holds the information needed to construct new index
32 33
 *		entries for a particular index.  Used for both index_build and
 *		retail creation of index entries.
34
 *
35 36
 *		NumIndexAttrs		number of columns in this index
 *		KeyAttrNumbers		underlying-rel attribute numbers used as keys
37 38 39
 *							(zeroes indicate expressions)
 *		Expressions			expr trees for expression entries, or NIL if none
 *		ExpressionsState	exec state for expressions, or NIL if none
40
 *		Predicate			partial-index predicate, or NIL if none
41
 *		PredicateState		exec state for predicate, or NIL if none
42
 *		Unique				is it a unique index?
43 44
 * ----------------
 */
45 46
typedef struct IndexInfo
{
47
	NodeTag		type;
48 49
	int			ii_NumIndexAttrs;
	AttrNumber	ii_KeyAttrNumbers[INDEX_MAX_KEYS];
B
Bruce Momjian 已提交
50 51
	List	   *ii_Expressions; /* list of Expr */
	List	   *ii_ExpressionsState;	/* list of ExprState */
52
	List	   *ii_Predicate;	/* list of Expr */
B
Bruce Momjian 已提交
53
	List	   *ii_PredicateState;		/* list of ExprState */
54
	bool		ii_Unique;
55
} IndexInfo;
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/* ----------------
 *	  ExprContext_CB
 *
 *		List of callbacks to be called at ExprContext shutdown.
 * ----------------
 */
typedef void (*ExprContextCallbackFunction) (Datum arg);

typedef struct ExprContext_CB
{
	struct ExprContext_CB *next;
	ExprContextCallbackFunction function;
	Datum		arg;
} ExprContext_CB;

72
/* ----------------
73 74 75 76 77 78 79 80
 *	  ExprContext
 *
 *		This class holds the "current context" information
 *		needed to evaluate expressions for doing tuple qualifications
 *		and tuple projections.	For example, if an expression refers
 *		to an attribute in the current inner tuple then we need to know
 *		what the current inner tuple is and so we look at the expression
 *		context.
81 82
 *
 *	There are two memory contexts associated with an ExprContext:
83
 *	* ecxt_per_query_memory is a query-lifespan context, typically the same
B
Bruce Momjian 已提交
84
 *	  context the ExprContext node itself is allocated in.	This context
85
 *	  can be used for purposes such as storing function call cache info.
86 87 88 89
 *	* ecxt_per_tuple_memory is a short-term context for expression results.
 *	  As the name suggests, it will typically be reset once per tuple,
 *	  before we begin to evaluate expressions for that tuple.  Each
 *	  ExprContext normally has its very own per-tuple memory context.
90
 *
91 92
 *	CurrentMemoryContext should be set to ecxt_per_tuple_memory before
 *	calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
93 94
 * ----------------
 */
95 96
typedef struct ExprContext
{
B
Bruce Momjian 已提交
97
	NodeTag		type;
98

99
	/* Tuples that Var nodes in expression may refer to */
100 101 102
	TupleTableSlot *ecxt_scantuple;
	TupleTableSlot *ecxt_innertuple;
	TupleTableSlot *ecxt_outertuple;
103

104
	/* Memory contexts for expression evaluation --- see notes above */
B
Bruce Momjian 已提交
105 106
	MemoryContext ecxt_per_query_memory;
	MemoryContext ecxt_per_tuple_memory;
107

108
	/* Values to substitute for Param nodes in expression */
B
Bruce Momjian 已提交
109 110
	ParamExecData *ecxt_param_exec_vals;		/* for PARAM_EXEC params */
	ParamListInfo ecxt_param_list_info; /* for other param types */
111

112
	/* Values to substitute for Aggref nodes in expression */
B
Bruce Momjian 已提交
113 114
	Datum	   *ecxt_aggvalues; /* precomputed values for Aggref nodes */
	bool	   *ecxt_aggnulls;	/* null flags for Aggref nodes */
115

116
	/* Value to substitute for CoerceToDomainValue nodes in expression */
B
Bruce Momjian 已提交
117 118 119
	Datum		domainValue_datum;
	bool		domainValue_isNull;

120 121 122
	/* Link to containing EState */
	struct EState *ecxt_estate;

123 124
	/* Functions to call back when ExprContext is shut down */
	ExprContext_CB *ecxt_callbacks;
125
} ExprContext;
126

127 128 129 130 131
/*
 * Set-result status returned by ExecEvalExpr()
 */
typedef enum
{
132 133 134
	ExprSingleResult,			/* expression does not return a set */
	ExprMultipleResult,			/* this result is an element of a set */
	ExprEndResult				/* there are no more elements in the set */
135 136
} ExprDoneCond;

137 138 139 140 141 142 143 144 145 146 147
/*
 * Return modes for functions returning sets.  Note values must be chosen
 * as separate bits so that a bitmask can be formed to indicate supported
 * modes.
 */
typedef enum
{
	SFRM_ValuePerCall = 0x01,	/* one value returned per call */
	SFRM_Materialize = 0x02		/* result set instantiated in Tuplestore */
} SetFunctionReturnMode;

148 149 150 151
/*
 * When calling a function that might return a set (multiple rows),
 * a node of this type is passed as fcinfo->resultinfo to allow
 * return status to be passed back.  A function returning set should
152
 * raise an error if no such resultinfo is provided.
153 154 155 156
 */
typedef struct ReturnSetInfo
{
	NodeTag		type;
157
	/* values set by caller: */
158
	ExprContext *econtext;		/* context function is being called in */
159
	TupleDesc	expectedDesc;	/* tuple descriptor expected by caller */
160
	int			allowedModes;	/* bitmask: return modes caller can handle */
161 162
	/* result status from function (but pre-initialized by caller): */
	SetFunctionReturnMode returnMode;	/* actual return mode */
163
	ExprDoneCond isDone;		/* status for ValuePerCall mode */
164
	/* fields filled by function in Materialize return mode: */
B
Bruce Momjian 已提交
165
	Tuplestorestate *setResult; /* holds the complete returned tuple set */
166
	TupleDesc	setDesc;		/* actual descriptor for returned tuples */
167 168
} ReturnSetInfo;

169
/* ----------------
170 171
 *		ProjectionInfo node information
 *
172 173 174 175
 *		This is all the information needed to perform projections ---
 *		that is, form new tuples by evaluation of targetlist expressions.
 *		Nodes which need to do projections create one of these.
 *		In theory, when a node wants to perform a projection
176 177 178
 *		it should just update this information as necessary and then
 *		call ExecProject().  -cim 6/3/91
 *
179
 *		ExecProject() evaluates the tlist, forms a tuple, and stores it
B
Bruce Momjian 已提交
180
 *		in the given slot.	As a side-effect, the actual datum values and
181 182
 *		null indicators are placed in the work arrays tupValues/tupNulls.
 *
183
 *		targetlist		target list for projection
184
 *		exprContext		expression context in which to evaluate targetlist
185
 *		slot			slot to place projection result in
186 187 188
 *		tupValues		array of computed values
 *		tupNull			array of null indicators
 *		itemIsDone		workspace for ExecProject
189 190
 * ----------------
 */
191 192
typedef struct ProjectionInfo
{
193 194 195
	NodeTag		type;
	List	   *pi_targetlist;
	ExprContext *pi_exprContext;
196
	TupleTableSlot *pi_slot;
197 198 199
	Datum	   *pi_tupValues;
	char	   *pi_tupNulls;
	ExprDoneCond *pi_itemIsDone;
200
} ProjectionInfo;
201 202

/* ----------------
203 204
 *	  JunkFilter
 *
205
 *	  This class is used to store information regarding junk attributes.
206 207
 *	  A junk attribute is an attribute in a tuple that is needed only for
 *	  storing intermediate information in the executor, and does not belong
208 209 210
 *	  in emitted tuples.	For example, when we do an UPDATE query,
 *	  the planner adds a "junk" entry to the targetlist so that the tuples
 *	  returned to ExecutePlan() contain an extra attribute: the ctid of
B
Bruce Momjian 已提交
211
 *	  the tuple to be updated.	This is needed to do the update, but we
212 213 214
 *	  don't want the ctid to be part of the stored new tuple!  So, we
 *	  apply a "junk filter" to remove the junk attributes and form the
 *	  real output tuple.
215 216 217 218 219 220 221
 *
 *	  targetList:		the original target list (including junk attributes).
 *	  length:			the length of 'targetList'.
 *	  tupType:			the tuple descriptor for the "original" tuple
 *						(including the junk attributes).
 *	  cleanTargetList:	the "clean" target list (junk attributes removed).
 *	  cleanLength:		the length of 'cleanTargetList'
222
 *	  cleanTupType:		the tuple descriptor of the "clean" tuple (with
223
 *						junk attributes removed).
224 225 226 227
 *	  cleanMap:			A map with the correspondence between the non-junk
 *						attribute numbers of the "original" tuple and the
 *						attribute numbers of the "clean" tuple.
 *	  resultSlot:		tuple slot that can be used to hold cleaned tuple.
228 229
 * ----------------
 */
230 231
typedef struct JunkFilter
{
232 233 234 235 236 237 238 239
	NodeTag		type;
	List	   *jf_targetList;
	int			jf_length;
	TupleDesc	jf_tupType;
	List	   *jf_cleanTargetList;
	int			jf_cleanLength;
	TupleDesc	jf_cleanTupType;
	AttrNumber *jf_cleanMap;
240
	TupleTableSlot *jf_resultSlot;
241
} JunkFilter;
242

243 244 245
/* ----------------
 *	  ResultRelInfo information
 *
246 247 248 249
 *		Whenever we update an existing relation, we have to
 *		update indices on the relation, and perhaps also fire triggers.
 *		The ResultRelInfo class is used to hold all the information needed
 *		about a result relation, including indices.. -cim 10/15/89
250 251 252 253 254 255
 *
 *		RangeTableIndex			result relation's range table index
 *		RelationDesc			relation descriptor for result relation
 *		NumIndices				# of indices existing on result relation
 *		IndexRelationDescs		array of relation descriptors for indices
 *		IndexRelationInfo		array of key/attr info for indices
256 257
 *		TrigDesc				triggers to be fired, if any
 *		TrigFunctions			cached lookup info for trigger functions
258
 *		ConstraintExprs			array of constraint-checking expr states
259 260 261 262 263 264 265 266 267 268 269
 *		junkFilter				for removing junk attributes from tuples
 * ----------------
 */
typedef struct ResultRelInfo
{
	NodeTag		type;
	Index		ri_RangeTableIndex;
	Relation	ri_RelationDesc;
	int			ri_NumIndices;
	RelationPtr ri_IndexRelationDescs;
	IndexInfo **ri_IndexRelationInfo;
270 271
	TriggerDesc *ri_TrigDesc;
	FmgrInfo   *ri_TrigFunctions;
272 273 274 275
	List	  **ri_ConstraintExprs;
	JunkFilter *ri_junkFilter;
} ResultRelInfo;

276
/* ----------------
277
 *	  EState information
278
 *
279
 * Master working state for an Executor invocation
280
 * ----------------
281
 */
282 283
typedef struct EState
{
B
Bruce Momjian 已提交
284
	NodeTag		type;
285 286

	/* Basic state for all query types: */
B
Bruce Momjian 已提交
287
	ScanDirection es_direction; /* current scan direction */
288
	Snapshot	es_snapshot;	/* time qual to use */
289
	Snapshot	es_crosscheck_snapshot;	/* crosscheck time qual for RI */
B
Bruce Momjian 已提交
290
	List	   *es_range_table; /* List of RangeTableEntrys */
291 292

	/* Info about target table for insert/update/delete queries: */
B
Bruce Momjian 已提交
293 294 295 296 297
	ResultRelInfo *es_result_relations; /* array of ResultRelInfos */
	int			es_num_result_relations;		/* length of array */
	ResultRelInfo *es_result_relation_info;		/* currently active array
												 * elt */
	JunkFilter *es_junkFilter;	/* currently active junk filter */
B
Bruce Momjian 已提交
298
	Relation	es_into_relation_descriptor;	/* for SELECT INTO */
299 300

	/* Parameter info: */
301 302
	ParamListInfo es_param_list_info;	/* values of external params */
	ParamExecData *es_param_exec_vals;	/* values of internal params */
303 304 305 306 307 308

	/* Other working state: */
	MemoryContext es_query_cxt; /* per-query context in which EState lives */

	TupleTable	es_tupleTable;	/* Array of TupleTableSlots */

B
Bruce Momjian 已提交
309 310 311
	uint32		es_processed;	/* # of tuples processed */
	Oid			es_lastoid;		/* last oid processed (by INSERT) */
	List	   *es_rowMark;		/* not good place, but there is no other */
B
Bruce Momjian 已提交
312

313
	bool		es_instrument;	/* true requests runtime instrumentation */
314 315
	bool		es_select_into;	/* true if doing SELECT INTO */
	bool		es_into_oids;	/* true to generate OIDs in SELECT INTO */
316

B
Bruce Momjian 已提交
317
	List	   *es_exprcontexts;	/* List of ExprContexts within EState */
318

319 320
	/*
	 * this ExprContext is for per-output-tuple operations, such as
B
Bruce Momjian 已提交
321 322 323
	 * constraint checks and index-value computations.	It will be reset
	 * for each output tuple.  Note that it will be created only if
	 * needed.
324 325
	 */
	ExprContext *es_per_tuple_exprcontext;
326

327
	/* Below is to re-evaluate plan qual in READ COMMITTED mode */
328
	Plan	   *es_topPlan;		/* link to top of plan tree */
B
Bruce Momjian 已提交
329 330 331
	struct evalPlanQual *es_evalPlanQual;		/* chain of PlanQual
												 * states */
	bool	   *es_evTupleNull; /* local array of EPQ status */
332
	HeapTuple  *es_evTuple;		/* shared array of EPQ substitute tuples */
B
Bruce Momjian 已提交
333
	bool		es_useEvalPlan; /* evaluating EPQ tuples? */
334
} EState;
335 336


337 338 339 340 341 342 343 344 345 346 347
/* ----------------------------------------------------------------
 *				 Tuple Hash Tables
 *
 * All-in-memory tuple hash tables are used for a number of purposes.
 * ----------------------------------------------------------------
 */
typedef struct TupleHashEntryData *TupleHashEntry;
typedef struct TupleHashTableData *TupleHashTable;

typedef struct TupleHashEntryData
{
348
	/* firstTuple must be the first field in this struct! */
349 350
	HeapTuple	firstTuple;		/* copy of first tuple in this group */
	/* there may be additional data beyond the end of this struct */
351
} TupleHashEntryData;			/* VARIABLE LENGTH STRUCT */
352 353 354

typedef struct TupleHashTableData
{
355
	HTAB	   *hashtab;		/* underlying dynahash table */
356 357 358
	int			numCols;		/* number of columns in lookup key */
	AttrNumber *keyColIdx;		/* attr numbers of key columns */
	FmgrInfo   *eqfunctions;	/* lookup data for comparison functions */
359
	FmgrInfo   *hashfunctions;	/* lookup data for hash functions */
360 361 362
	MemoryContext tablecxt;		/* memory context containing table */
	MemoryContext tempcxt;		/* context for function evaluations */
	Size		entrysize;		/* actual size to make each hash entry */
363 364
	TupleDesc	tupdesc;		/* tuple descriptor */
} TupleHashTableData;
365

366
typedef HASH_SEQ_STATUS TupleHashIterator;
367

368 369 370 371
#define ResetTupleHashIterator(htable, iter) \
	hash_seq_init(iter, (htable)->hashtab)
#define ScanTupleHashTable(iter) \
	((TupleHashEntry) hash_seq_search(iter))
372 373


374
/* ----------------------------------------------------------------
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
 *				 Expression State Trees
 *
 * Each executable expression tree has a parallel ExprState tree.
 *
 * Unlike PlanState, there is not an exact one-for-one correspondence between
 * ExprState node types and Expr node types.  Many Expr node types have no
 * need for node-type-specific run-time state, and so they can use plain
 * ExprState or GenericExprState as their associated ExprState node type.
 * ----------------------------------------------------------------
 */

/* ----------------
 *		ExprState node
 *
 * ExprState is the common superclass for all ExprState-type nodes.
 *
 * It can also be instantiated directly for leaf Expr nodes that need no
 * local run-time state (such as Var, Const, or Param).
 * ----------------
 */
typedef struct ExprState
{
	NodeTag		type;
	Expr	   *expr;			/* associated Expr node */
399
} ExprState;
400 401 402 403 404 405 406 407 408 409 410 411

/* ----------------
 *		GenericExprState node
 *
 * This is used for Expr node types that need no local run-time state,
 * but have one child Expr node.
 * ----------------
 */
typedef struct GenericExprState
{
	ExprState	xprstate;
	ExprState  *arg;			/* state of my child node */
412
} GenericExprState;
413 414 415 416 417 418 419 420 421 422

/* ----------------
 *		AggrefExprState node
 * ----------------
 */
typedef struct AggrefExprState
{
	ExprState	xprstate;
	ExprState  *target;			/* state of my child node */
	int			aggno;			/* ID number for agg within its plan node */
423
} AggrefExprState;
424 425 426

/* ----------------
 *		ArrayRefExprState node
427 428 429 430
 *
 * Note: array types can be fixed-length (typlen > 0), but only when the
 * element type is itself fixed-length.  Otherwise they are varlena structures
 * and have typlen = -1.  In any case, an array type is never pass-by-value.
431 432 433 434 435
 * ----------------
 */
typedef struct ArrayRefExprState
{
	ExprState	xprstate;
B
Bruce Momjian 已提交
436
	List	   *refupperindexpr;	/* states for child nodes */
437 438 439
	List	   *reflowerindexpr;
	ExprState  *refexpr;
	ExprState  *refassgnexpr;
440 441 442 443
	int16		refattrlength;	/* typlen of array type */
	int16		refelemlength;	/* typlen of the array element type */
	bool		refelembyval;	/* is the element type pass-by-value? */
	char		refelemalign;	/* typalign of the element type */
444
} ArrayRefExprState;
445 446 447 448

/* ----------------
 *		FuncExprState node
 *
449 450 451
 * Although named for FuncExpr, this is also used for OpExpr, DistinctExpr,
 * and NullIf nodes; be careful to check what xprstate.expr is actually
 * pointing at!
452 453 454 455 456 457 458 459
 * ----------------
 */
typedef struct FuncExprState
{
	ExprState	xprstate;
	List	   *args;			/* states of argument expressions */

	/*
B
Bruce Momjian 已提交
460 461
	 * Function manager's lookup info for the target function.  If
	 * func.fn_oid is InvalidOid, we haven't initialized it yet.
462 463 464 465
	 */
	FmgrInfo	func;

	/*
B
Bruce Momjian 已提交
466 467
	 * We also need to store argument values across calls when evaluating
	 * a function-returning-set.
468
	 *
B
Bruce Momjian 已提交
469 470
	 * setArgsValid is true when we are evaluating a set-valued function and
	 * we are in the middle of a call series; we want to pass the same
471 472 473 474 475 476 477 478 479 480 481 482
	 * argument values to the function again (and again, until it returns
	 * ExprEndResult).
	 */
	bool		setArgsValid;

	/*
	 * Flag to remember whether we found a set-valued argument to the
	 * function. This causes the function result to be a set as well.
	 * Valid only when setArgsValid is true.
	 */
	bool		setHasSetArg;	/* some argument returns a set */

483 484 485 486 487 488 489
	/*
	 * Flag to remember whether we have registered a shutdown callback for
	 * this FuncExprState.  We do so only if setArgsValid has been true at
	 * least once (since all the callback is for is to clear setArgsValid).
	 */
	bool		shutdown_reg;	/* a shutdown callback is registered */

490 491 492 493 494
	/*
	 * Current argument data for a set-valued function; contains valid
	 * data only if setArgsValid is true.
	 */
	FunctionCallInfoData setArgs;
495
} FuncExprState;
496

497 498 499 500 501 502 503 504
/* ----------------
 *		ScalarArrayOpExprState node
 *
 * This is a FuncExprState plus some additional data.
 * ----------------
 */
typedef struct ScalarArrayOpExprState
{
B
Bruce Momjian 已提交
505
	FuncExprState fxprstate;
506
	/* Cached info about array element type */
B
Bruce Momjian 已提交
507 508 509 510
	Oid			element_type;
	int16		typlen;
	bool		typbyval;
	char		typalign;
511
} ScalarArrayOpExprState;
512

513 514 515 516 517 518 519 520
/* ----------------
 *		BoolExprState node
 * ----------------
 */
typedef struct BoolExprState
{
	ExprState	xprstate;
	List	   *args;			/* states of argument expression(s) */
521
} BoolExprState;
522 523

/* ----------------
524
 *		SubPlanState node
525 526
 * ----------------
 */
527
typedef struct SubPlanState
528 529
{
	ExprState	xprstate;
530
	EState	   *sub_estate;		/* subselect plan has its own EState */
B
Bruce Momjian 已提交
531
	struct PlanState *planstate;	/* subselect plan's state tree */
532 533
	List	   *exprs;			/* states of combining expression(s) */
	List	   *args;			/* states of argument expression(s) */
534 535
	bool		needShutdown;	/* TRUE = need to shutdown subplan */
	HeapTuple	curTuple;		/* copy of most recent tuple from subplan */
536
	/* these are used when hashing the subselect's output: */
537 538
	ProjectionInfo *projLeft;	/* for projecting lefthand exprs */
	ProjectionInfo *projRight;	/* for projecting subselect output */
539 540
	TupleHashTable hashtable;	/* hash table for no-nulls subselect rows */
	TupleHashTable hashnulls;	/* hash table for rows with null(s) */
541 542 543
	bool		havehashrows;	/* TRUE if hashtable is not empty */
	bool		havenullrows;	/* TRUE if hashnulls is not empty */
	MemoryContext tablecxt;		/* memory context containing tables */
B
Bruce Momjian 已提交
544
	ExprContext *innerecontext; /* working context for comparisons */
545 546
	AttrNumber *keyColIdx;		/* control data for hash tables */
	FmgrInfo   *eqfunctions;	/* comparison functions for hash tables */
547
	FmgrInfo   *hashfunctions;	/* lookup data for hash functions */
548
} SubPlanState;
549 550 551 552 553 554 555 556 557 558

/* ----------------
 *		CaseExprState node
 * ----------------
 */
typedef struct CaseExprState
{
	ExprState	xprstate;
	List	   *args;			/* the arguments (list of WHEN clauses) */
	ExprState  *defresult;		/* the default result (ELSE clause) */
559
} CaseExprState;
560 561 562 563 564 565 566 567 568 569

/* ----------------
 *		CaseWhenState node
 * ----------------
 */
typedef struct CaseWhenState
{
	ExprState	xprstate;
	ExprState  *expr;			/* condition expression */
	ExprState  *result;			/* substitution result */
570
} CaseWhenState;
571

572 573 574 575 576 577 578 579 580 581 582 583 584 585
/* ----------------
 *		ArrayExprState node
 *
 * Note: ARRAY[] expressions always produce varlena arrays, never fixed-length
 * arrays.
 * ----------------
 */
typedef struct ArrayExprState
{
	ExprState	xprstate;
	List	   *elements;		/* states for child nodes */
	int16		elemlength;		/* typlen of the array element type */
	bool		elembyval;		/* is the element type pass-by-value? */
	char		elemalign;		/* typalign of the element type */
586
} ArrayExprState;
587

588 589 590 591 592 593 594
/* ----------------
 *		CoalesceExprState node
 * ----------------
 */
typedef struct CoalesceExprState
{
	ExprState	xprstate;
B
Bruce Momjian 已提交
595
	List	   *args;			/* the arguments */
596
} CoalesceExprState;
597

598
/* ----------------
599
 *		CoerceToDomainState node
600 601
 * ----------------
 */
602
typedef struct CoerceToDomainState
603 604 605
{
	ExprState	xprstate;
	ExprState  *arg;			/* input expression */
606 607
	/* Cached list of constraints that need to be checked */
	List	   *constraints;	/* list of DomainConstraintState nodes */
608
} CoerceToDomainState;
609 610 611 612 613 614 615 616 617 618 619 620

/*
 * DomainConstraintState - one item to check during CoerceToDomain
 *
 * Note: this is just a Node, and not an ExprState, because it has no
 * corresponding Expr to link to.  Nonetheless it is part of an ExprState
 * tree, so we give it a name following the xxxState convention.
 */
typedef enum DomainConstraintType
{
	DOM_CONSTRAINT_NOTNULL,
	DOM_CONSTRAINT_CHECK
621
} DomainConstraintType;
622 623 624 625

typedef struct DomainConstraintState
{
	NodeTag		type;
B
Bruce Momjian 已提交
626
	DomainConstraintType constrainttype;		/* constraint type */
627 628
	char	   *name;			/* name of constraint (for error msgs) */
	ExprState  *check_expr;		/* for CHECK, a boolean expression */
629
} DomainConstraintState;
630 631 632 633 634 635 636


/* ----------------------------------------------------------------
 *				 Executor State Trees
 *
 * An executing query has a PlanState tree paralleling the Plan tree
 * that describes the plan.
637 638 639 640
 * ----------------------------------------------------------------
 */

/* ----------------
641
 *		PlanState node
642
 *
643 644
 * We never actually instantiate any PlanState nodes; this is just the common
 * abstract superclass for all PlanState-type nodes.
645 646
 * ----------------
 */
647
typedef struct PlanState
648
{
649
	NodeTag		type;
650

651
	Plan	   *plan;			/* associated Plan node */
652

653 654 655 656 657 658 659 660
	EState	   *state;			/* at execution time, state's of
								 * individual nodes point to one EState
								 * for the whole top-level plan */

	struct Instrumentation *instrument; /* Optional runtime stats for this
										 * plan node */

	/*
B
Bruce Momjian 已提交
661 662 663 664
	 * Common structural data for all Plan types.  These links to
	 * subsidiary state trees parallel links in the associated plan tree
	 * (except for the subPlan list, which does not exist in the plan
	 * tree).
665 666 667
	 */
	List	   *targetlist;		/* target list to be computed at this node */
	List	   *qual;			/* implicitly-ANDed qual conditions */
B
Bruce Momjian 已提交
668
	struct PlanState *lefttree; /* input plan tree(s) */
669
	struct PlanState *righttree;
670
	List	   *initPlan;		/* Init SubPlanState nodes (un-correlated
671
								 * expr subselects) */
672
	List	   *subPlan;		/* SubPlanState nodes in my expressions */
673 674 675 676

	/*
	 * State for management of parameter-change-driven rescanning
	 */
677
	Bitmapset  *chgParam;		/* set of IDs of changed Params */
678 679 680 681

	/*
	 * Other run-time state needed by most if not all node types.
	 */
B
Bruce Momjian 已提交
682 683 684 685 686 687
	TupleTableSlot *ps_OuterTupleSlot;	/* slot for current "outer" tuple */
	TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
	ExprContext *ps_ExprContext;	/* node's expression-evaluation context */
	ProjectionInfo *ps_ProjInfo;	/* info for doing tuple projection */
	bool		ps_TupFromTlist;/* state flag for processing set-valued
								 * functions in targetlist */
688
} PlanState;
689 690 691 692 693 694 695

/* ----------------
 *	these are are defined to avoid confusion problems with "left"
 *	and "right" and "inner" and "outer".  The convention is that
 *	the "left" plan is the "outer" plan and the "right" plan is
 *	the inner plan, but these make the code more readable.
 * ----------------
696
 */
697 698 699
#define innerPlanState(node)		(((PlanState *)(node))->righttree)
#define outerPlanState(node)		(((PlanState *)(node))->lefttree)

700 701

/* ----------------
702
 *	 ResultState information
703 704
 * ----------------
 */
705 706
typedef struct ResultState
{
707
	PlanState	ps;				/* its first field is NodeTag */
708
	ExprState  *resconstantqual;
709 710
	bool		rs_done;		/* are we done? */
	bool		rs_checkqual;	/* do we need to check the qual? */
711
} ResultState;
712 713

/* ----------------
714 715
 *	 AppendState information
 *
716
 *		nplans			how many plans are in the list
717
 *		whichplan		which plan is being executed (0 .. n-1)
718 719
 *		firstplan		first plan to execute (usually 0)
 *		lastplan		last plan to execute (usually n-1)
720 721
 * ----------------
 */
722 723
typedef struct AppendState
{
724 725 726
	PlanState	ps;				/* its first field is NodeTag */
	PlanState **appendplans;	/* array of PlanStates for my inputs */
	int			as_nplans;
727
	int			as_whichplan;
728 729
	int			as_firstplan;
	int			as_lastplan;
B
Bruce Momjian 已提交
730
} AppendState;
731 732

/* ----------------------------------------------------------------
733
 *				 Scan State Information
734 735 736 737
 * ----------------------------------------------------------------
 */

/* ----------------
738
 *	 ScanState information
739
 *
740
 *		ScanState extends PlanState for node types that represent
741 742 743 744
 *		scans of an underlying relation.  It can also be used for nodes
 *		that scan the output of an underlying plan node --- in that case,
 *		only ScanTupleSlot is actually useful, and it refers to the tuple
 *		retrieved from the subplan.
745
 *
746 747
 *		currentRelation    relation being scanned (NULL if none)
 *		currentScanDesc    current scan descriptor for scan (NULL if none)
748
 *		ScanTupleSlot	   pointer to slot in tuple table holding scan tuple
749 750
 * ----------------
 */
751
typedef struct ScanState
752
{
753 754 755 756
	PlanState	ps;				/* its first field is NodeTag */
	Relation	ss_currentRelation;
	HeapScanDesc ss_currentScanDesc;
	TupleTableSlot *ss_ScanTupleSlot;
757
} ScanState;
758

759
/*
760
 * SeqScan uses a bare ScanState as its state node, since it needs
761 762
 * no additional fields.
 */
763
typedef ScanState SeqScanState;
764

765
/* ----------------
766 767 768
 *	 IndexScanState information
 *
 *		NumIndices		   number of indices in this scan
769
 *		IndexPtr		   current index in use
770 771
 *		ScanKeys		   Skey structures to scan index rels
 *		NumScanKeys		   array of no of keys in each Skey struct
772 773
 *		RuntimeKeyInfo	   array of array of exprstates for Skeys
 *						   that will be evaluated at runtime
774
 *		RuntimeContext	   expr context for evaling runtime Skeys
775
 *		RuntimeKeysReady   true if runtime Skeys have been computed
776 777
 *		RelationDescs	   ptr to array of relation descriptors
 *		ScanDescs		   ptr to array of scan descriptors
778
 *		LossyQuals		   ptr to array of qual lists for lossy operators
779 780
 *		DupHash			   hashtable for recognizing dups in multiple scan
 *		MaxHash			   max # entries we will allow in hashtable
781 782
 * ----------------
 */
783 784
typedef struct IndexScanState
{
785 786 787
	ScanState	ss;				/* its first field is NodeTag */
	List	   *indxqual;
	List	   *indxqualorig;
B
Bruce Momjian 已提交
788 789 790 791 792
	int			iss_NumIndices;
	int			iss_IndexPtr;
	int			iss_MarkIndexPtr;
	ScanKey    *iss_ScanKeys;
	int		   *iss_NumScanKeys;
793
	ExprState ***iss_RuntimeKeyInfo;
794
	ExprContext *iss_RuntimeContext;
795
	bool		iss_RuntimeKeysReady;
B
Bruce Momjian 已提交
796 797
	RelationPtr iss_RelationDescs;
	IndexScanDescPtr iss_ScanDescs;
798
	List	  **iss_LossyQuals;
799 800
	HTAB	   *iss_DupHash;
	long		iss_MaxHash;
801
} IndexScanState;
802

803 804 805 806
/* ----------------
 *	 TidScanState information
 *
 *		NumTids		   number of tids in this scan
807 808
 *		TidPtr		   current tid in use
 *		TidList		   evaluated item pointers
809 810 811 812
 * ----------------
 */
typedef struct TidScanState
{
813
	ScanState	ss;				/* its first field is NodeTag */
814
	List	   *tss_tideval;	/* list of ExprState nodes */
815 816 817
	int			tss_NumTids;
	int			tss_TidPtr;
	int			tss_MarkTidPtr;
818
	ItemPointerData *tss_TidList;
819
	HeapTupleData tss_htup;
820
} TidScanState;
821

822 823 824 825 826 827 828 829 830 831 832 833
/* ----------------
 *	 SubqueryScanState information
 *
 *		SubqueryScanState is used for scanning a sub-query in the range table.
 *		The sub-query will have its own EState, which we save here.
 *		ScanTupleSlot references the current output tuple of the sub-query.
 *
 *		SubEState		   exec state for sub-query
 * ----------------
 */
typedef struct SubqueryScanState
{
834 835
	ScanState	ss;				/* its first field is NodeTag */
	PlanState  *subplan;
836 837 838
	EState	   *sss_SubEState;
} SubqueryScanState;

839 840 841 842 843 844
/* ----------------
 *	 FunctionScanState information
 *
 *		Function nodes are used to scan the results of a
 *		function appearing in FROM (typically a function returning set).
 *
845
 *		tupdesc				expected return tuple description
846
 *		tuplestorestate		private state of tuplestore.c
847
 *		funcexpr			state for function expression being evaluated
848 849 850 851
 * ----------------
 */
typedef struct FunctionScanState
{
852
	ScanState	ss;				/* its first field is NodeTag */
B
Bruce Momjian 已提交
853
	TupleDesc	tupdesc;
854
	Tuplestorestate *tuplestorestate;
855
	ExprState  *funcexpr;
856 857
} FunctionScanState;

858
/* ----------------------------------------------------------------
859
 *				 Join State Information
860 861 862 863
 * ----------------------------------------------------------------
 */

/* ----------------
864
 *	 JoinState information
865
 *
866
 *		Superclass for state nodes of join plans.
867 868
 * ----------------
 */
869 870 871 872 873 874
typedef struct JoinState
{
	PlanState	ps;
	JoinType	jointype;
	List	   *joinqual;		/* JOIN quals (in addition to ps.qual) */
} JoinState;
875 876

/* ----------------
877
 *	 NestLoopState information
878
 *
B
Bruce Momjian 已提交
879 880
 *		NeedNewOuter	   true if need new outer tuple on next call
 *		MatchedOuter	   true if found a join match for current outer tuple
881
 *		NullInnerTupleSlot prepared null tuple for left outer joins
882 883
 * ----------------
 */
884 885
typedef struct NestLoopState
{
886
	JoinState	js;				/* its first field is NodeTag */
887 888 889
	bool		nl_NeedNewOuter;
	bool		nl_MatchedOuter;
	TupleTableSlot *nl_NullInnerTupleSlot;
890
} NestLoopState;
891 892

/* ----------------
893
 *	 MergeJoinState information
894
 *
895 896
 *		OuterSkipQual	   outerKey1 < innerKey1 ...
 *		InnerSkipQual	   outerKey1 > innerKey1 ...
897
 *		JoinState		   current "state" of join. see executor.h
B
Bruce Momjian 已提交
898 899 900 901
 *		MatchedOuter	   true if found a join match for current outer tuple
 *		MatchedInner	   true if found a join match for current inner tuple
 *		OuterTupleSlot	   pointer to slot in tuple table for cur outer tuple
 *		InnerTupleSlot	   pointer to slot in tuple table for cur inner tuple
902
 *		MarkedTupleSlot    pointer to slot in tuple table for marked tuple
903 904
 *		NullOuterTupleSlot prepared null tuple for right outer joins
 *		NullInnerTupleSlot prepared null tuple for left outer joins
905 906
 * ----------------
 */
907 908
typedef struct MergeJoinState
{
909
	JoinState	js;				/* its first field is NodeTag */
B
Bruce Momjian 已提交
910 911 912
	List	   *mergeclauses;	/* list of ExprState nodes */
	List	   *mj_OuterSkipQual;		/* list of ExprState nodes */
	List	   *mj_InnerSkipQual;		/* list of ExprState nodes */
913
	int			mj_JoinState;
914 915 916 917
	bool		mj_MatchedOuter;
	bool		mj_MatchedInner;
	TupleTableSlot *mj_OuterTupleSlot;
	TupleTableSlot *mj_InnerTupleSlot;
918
	TupleTableSlot *mj_MarkedTupleSlot;
919 920
	TupleTableSlot *mj_NullOuterTupleSlot;
	TupleTableSlot *mj_NullInnerTupleSlot;
921
} MergeJoinState;
922 923

/* ----------------
924 925
 *	 HashJoinState information
 *
926 927 928 929 930 931
 *		hj_HashTable			hash table for the hashjoin
 *		hj_CurBucketNo			bucket# for current outer tuple
 *		hj_CurTuple				last inner tuple matched to current outer
 *								tuple, or NULL if starting search
 *								(CurBucketNo and CurTuple are meaningless
 *								 unless OuterTupleSlot is nonempty!)
932 933
 *		hj_OuterHashKeys		the outer hash keys in the hashjoin condition
 *		hj_InnerHashKeys		the inner hash keys in the hashjoin condition
934
 *		hj_HashOperators		the join operators in the hashjoin condition
935 936
 *		hj_OuterTupleSlot		tuple slot for outer tuples
 *		hj_HashTupleSlot		tuple slot for hashed tuples
B
Bruce Momjian 已提交
937 938 939
 *		hj_NullInnerTupleSlot	prepared null tuple for left outer joins
 *		hj_NeedNewOuter			true if need new outer tuple on next call
 *		hj_MatchedOuter			true if found a join match for current outer
940
 *		hj_hashdone				true if hash-table-build phase is done
941 942
 * ----------------
 */
943 944
typedef struct HashJoinState
{
945
	JoinState	js;				/* its first field is NodeTag */
946
	List	   *hashclauses;	/* list of ExprState nodes */
B
Bruce Momjian 已提交
947 948 949
	HashJoinTable hj_HashTable;
	int			hj_CurBucketNo;
	HashJoinTuple hj_CurTuple;
B
Bruce Momjian 已提交
950 951 952
	List	   *hj_OuterHashKeys;		/* list of ExprState nodes */
	List	   *hj_InnerHashKeys;		/* list of ExprState nodes */
	List	   *hj_HashOperators;		/* list of operator OIDs */
953 954
	TupleTableSlot *hj_OuterTupleSlot;
	TupleTableSlot *hj_HashTupleSlot;
955 956 957 958
	TupleTableSlot *hj_NullInnerTupleSlot;
	bool		hj_NeedNewOuter;
	bool		hj_MatchedOuter;
	bool		hj_hashdone;
959
} HashJoinState;
960 961 962


/* ----------------------------------------------------------------
963
 *				 Materialization State Information
964 965 966 967
 * ----------------------------------------------------------------
 */

/* ----------------
968
 *	 MaterialState information
969
 *
970
 *		materialize nodes are used to materialize the results
971
 *		of a subplan into a temporary file.
972
 *
973
 *		ss.ss_ScanTupleSlot refers to output of underlying plan.
974 975
 * ----------------
 */
976 977
typedef struct MaterialState
{
978
	ScanState	ss;				/* its first field is NodeTag */
B
Bruce Momjian 已提交
979 980
	void	   *tuplestorestate;	/* private state of tuplestore.c */
	bool		eof_underlying; /* reached end of underlying plan? */
981
} MaterialState;
982

983 984 985 986 987 988 989 990
/* ----------------
 *	 SortState information
 * ----------------
 */
typedef struct SortState
{
	ScanState	ss;				/* its first field is NodeTag */
	bool		sort_Done;		/* sort completed yet? */
B
Bruce Momjian 已提交
991
	void	   *tuplesortstate; /* private state of tuplesort.c */
992 993
} SortState;

994
/* ---------------------
995 996 997 998 999 1000 1001
 *	GroupState information
 * -------------------------
 */
typedef struct GroupState
{
	ScanState	ss;				/* its first field is NodeTag */
	FmgrInfo   *eqfunctions;	/* per-field lookup data for equality fns */
B
Bruce Momjian 已提交
1002
	HeapTuple	grp_firstTuple; /* copy of first tuple of current group */
1003 1004 1005 1006 1007
	bool		grp_done;		/* indicates completion of Group scan */
} GroupState;

/* ---------------------
 *	AggState information
1008
 *
1009
 *	ss.ss_ScanTupleSlot refers to output of underlying plan.
1010
 *
1011
 *	Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
1012 1013 1014 1015
 *	ecxt_aggnulls arrays, which hold the computed agg values for the current
 *	input group during evaluation of an Agg node's output tuple(s).  We
 *	create a second ExprContext, tmpcontext, in which to evaluate input
 *	expressions and run the aggregate transition functions.
1016 1017
 * -------------------------
 */
1018 1019 1020
/* these structs are private in nodeAgg.c: */
typedef struct AggStatePerAggData *AggStatePerAgg;
typedef struct AggStatePerGroupData *AggStatePerGroup;
1021

1022 1023
typedef struct AggState
{
1024
	ScanState	ss;				/* its first field is NodeTag */
1025
	List	   *aggs;			/* all Aggref nodes in targetlist & quals */
1026
	int			numaggs;		/* length of list (could be zero!) */
1027
	FmgrInfo   *eqfunctions;	/* per-grouping-field equality fns */
1028
	FmgrInfo   *hashfunctions;	/* per-grouping-field hash fns */
1029 1030 1031
	AggStatePerAgg peragg;		/* per-Aggref information */
	MemoryContext aggcontext;	/* memory context for long-lived data */
	ExprContext *tmpcontext;	/* econtext for input expressions */
1032
	bool		agg_done;		/* indicates completion of Agg scan */
1033 1034
	/* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
	AggStatePerGroup pergroup;	/* per-Aggref-per-group working state */
B
Bruce Momjian 已提交
1035
	HeapTuple	grp_firstTuple; /* copy of first tuple of current group */
1036
	/* these fields are used in AGG_HASHED mode: */
1037
	TupleHashTable hashtable;	/* hash table with one entry per group */
1038
	bool		table_filled;	/* hash table filled yet? */
B
Bruce Momjian 已提交
1039
	TupleHashIterator hashiter; /* for iterating through hash table */
B
Bruce Momjian 已提交
1040
} AggState;
1041 1042

/* ----------------
1043 1044 1045 1046 1047
 *	 UniqueState information
 *
 *		Unique nodes are used "on top of" sort nodes to discard
 *		duplicate tuples returned from the sort phase.	Basically
 *		all it does is compare the current tuple from the subplan
1048 1049 1050
 *		with the previously fetched tuple stored in priorTuple.
 *		If the two are identical in all interesting fields, then
 *		we just fetch another tuple from the sort and try again.
1051 1052
 * ----------------
 */
1053 1054
typedef struct UniqueState
{
1055
	PlanState	ps;				/* its first field is NodeTag */
1056 1057
	FmgrInfo   *eqfunctions;	/* per-field lookup data for equality fns */
	HeapTuple	priorTuple;		/* most recently returned tuple, or NULL */
1058
	MemoryContext tempContext;	/* short-term context for comparisons */
1059
} UniqueState;
1060

1061 1062 1063 1064 1065 1066 1067 1068
/* ----------------
 *	 HashState information
 * ----------------
 */
typedef struct HashState
{
	PlanState	ps;				/* its first field is NodeTag */
	HashJoinTable hashtable;	/* hash table for the hashjoin */
1069 1070
	List	   *hashkeys;		/* list of ExprState nodes */
	/* hashkeys is same as parent's hj_InnerHashKeys */
1071 1072
} HashState;

1073 1074 1075 1076
/* ----------------
 *	 SetOpState information
 *
 *		SetOp nodes are used "on top of" sort nodes to discard
B
Bruce Momjian 已提交
1077
 *		duplicate tuples returned from the sort phase.	These are
1078 1079 1080 1081 1082 1083
 *		more complex than a simple Unique since we have to count
 *		how many duplicates to return.
 * ----------------
 */
typedef struct SetOpState
{
1084
	PlanState	ps;				/* its first field is NodeTag */
1085 1086 1087 1088 1089 1090 1091 1092
	FmgrInfo   *eqfunctions;	/* per-field lookup data for equality fns */
	bool		subplan_done;	/* has subplan returned EOF? */
	long		numLeft;		/* number of left-input dups of cur group */
	long		numRight;		/* number of right-input dups of cur group */
	long		numOutput;		/* number of dups left to output */
	MemoryContext tempContext;	/* short-term context for comparisons */
} SetOpState;

1093 1094 1095 1096 1097 1098 1099 1100 1101
/* ----------------
 *	 LimitState information
 *
 *		Limit nodes are used to enforce LIMIT/OFFSET clauses.
 *		They just select the desired subrange of their subplan's output.
 *
 * offset is the number of initial tuples to skip (0 does nothing).
 * count is the number of tuples to return after skipping the offset tuples.
 * If no limit count was specified, count is undefined and noCount is true.
1102
 * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
1103 1104
 * ----------------
 */
1105 1106 1107 1108 1109 1110 1111 1112
typedef enum
{
	LIMIT_INITIAL,				/* initial state for LIMIT node */
	LIMIT_EMPTY,				/* there are no returnable rows */
	LIMIT_INWINDOW,				/* have returned a row in the window */
	LIMIT_SUBPLANEOF,			/* at EOF of subplan (within window) */
	LIMIT_WINDOWEND,			/* stepped off end of window */
	LIMIT_WINDOWSTART			/* stepped off beginning of window */
1113
} LimitStateCond;
1114

1115 1116
typedef struct LimitState
{
1117
	PlanState	ps;				/* its first field is NodeTag */
1118 1119
	ExprState  *limitOffset;	/* OFFSET parameter, or NULL if none */
	ExprState  *limitCount;		/* COUNT parameter, or NULL if none */
1120 1121 1122
	long		offset;			/* current OFFSET value */
	long		count;			/* current COUNT, if any */
	bool		noCount;		/* if true, ignore count */
1123 1124 1125
	LimitStateCond lstate;		/* state machine status, as above */
	long		position;		/* 1-based index of last tuple returned */
	TupleTableSlot *subSlot;	/* tuple last obtained from subplan */
1126 1127
} LimitState;

1128
#endif   /* EXECNODES_H */