Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
execnodes.h2773 linesDownload Raw Back to nodes
1/*-------------------------------------------------------------------------2 *3 * execnodes.h4 *	  definitions for executor state nodes5 *6 * Most plan node types declared in plannodes.h have a corresponding7 * execution-state node type declared here.  An exception is that8 * expression nodes (subtypes of Expr) are usually represented by steps9 * of an ExprState, and fully handled within execExpr* - but sometimes10 * their state needs to be shared with other parts of the executor, as11 * for example with SubPlanState, which nodeSubplan.c has to modify.12 *13 * Node types declared in this file do not have any copy/equal/out/read14 * support.  (That is currently hard-wired in gen_node_support.pl, rather15 * than being explicitly represented by pg_node_attr decorations here.)16 * There is no need for copy, equal, or read support for executor trees.17 * Output support could be useful for debugging; but there are a lot of18 * specialized fields that would require custom code, so for now it's19 * not provided.20 *21 *22 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group23 * Portions Copyright (c) 1994, Regents of the University of California24 *25 * src/include/nodes/execnodes.h26 *27 *-------------------------------------------------------------------------28 */29#ifndef EXECNODES_H30#define EXECNODES_H31 32#include "access/tupconvert.h"33#include "executor/instrument.h"34#include "fmgr.h"35#include "lib/ilist.h"36#include "lib/pairingheap.h"37#include "nodes/params.h"38#include "nodes/plannodes.h"39#include "nodes/tidbitmap.h"40#include "partitioning/partdefs.h"41#include "storage/condition_variable.h"42#include "utils/hsearch.h"43#include "utils/queryenvironment.h"44#include "utils/reltrigger.h"45#include "utils/sharedtuplestore.h"46#include "utils/snapshot.h"47#include "utils/sortsupport.h"48#include "utils/tuplesort.h"49#include "utils/tuplestore.h"50 51struct PlanState;				/* forward references in this file */52struct ParallelHashJoinState;53struct ExecRowMark;54struct ExprState;55struct ExprContext;56struct RangeTblEntry;			/* avoid including parsenodes.h here */57struct ExprEvalStep;			/* avoid including execExpr.h everywhere */58struct CopyMultiInsertBuffer;59struct LogicalTapeSet;60 61 62/* ----------------63 *		ExprState node64 *65 * ExprState represents the evaluation state for a whole expression tree.66 * It contains instructions (in ->steps) to evaluate the expression.67 * ----------------68 */69typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression,70									struct ExprContext *econtext,71									bool *isNull);72 73/* Bits in ExprState->flags (see also execExpr.h for private flag bits): */74/* expression is for use with ExecQual() */75#define EEO_FLAG_IS_QUAL					(1 << 0)76 77typedef struct ExprState78{79	NodeTag		type;80 81	uint8		flags;			/* bitmask of EEO_FLAG_* bits, see above */82 83	/*84	 * Storage for result value of a scalar expression, or for individual85	 * column results within expressions built by ExecBuildProjectionInfo().86	 */87#define FIELDNO_EXPRSTATE_RESNULL 288	bool		resnull;89#define FIELDNO_EXPRSTATE_RESVALUE 390	Datum		resvalue;91 92	/*93	 * If projecting a tuple result, this slot holds the result; else NULL.94	 */95#define FIELDNO_EXPRSTATE_RESULTSLOT 496	TupleTableSlot *resultslot;97 98	/*99	 * Instructions to compute expression's return value.100	 */101	struct ExprEvalStep *steps;102 103	/*104	 * Function that actually evaluates the expression.  This can be set to105	 * different values depending on the complexity of the expression.106	 */107	ExprStateEvalFunc evalfunc;108 109	/* original expression tree, for debugging only */110	Expr	   *expr;111 112	/* private state for an evalfunc */113	void	   *evalfunc_private;114 115	/*116	 * XXX: following fields only needed during "compilation" (ExecInitExpr);117	 * could be thrown away afterwards.118	 */119 120	int			steps_len;		/* number of steps currently */121	int			steps_alloc;	/* allocated length of steps array */122 123#define FIELDNO_EXPRSTATE_PARENT 11124	struct PlanState *parent;	/* parent PlanState node, if any */125	ParamListInfo ext_params;	/* for compiling PARAM_EXTERN nodes */126 127	Datum	   *innermost_caseval;128	bool	   *innermost_casenull;129 130	Datum	   *innermost_domainval;131	bool	   *innermost_domainnull;132} ExprState;133 134 135/* ----------------136 *	  IndexInfo information137 *138 *		this struct holds the information needed to construct new index139 *		entries for a particular index.  Used for both index_build and140 *		retail creation of index entries.141 *142 *		NumIndexAttrs		total number of columns in this index143 *		NumIndexKeyAttrs	number of key columns in index144 *		IndexAttrNumbers	underlying-rel attribute numbers used as keys145 *							(zeroes indicate expressions). It also contains146 * 							info about included columns.147 *		Expressions			expr trees for expression entries, or NIL if none148 *		ExpressionsState	exec state for expressions, or NIL if none149 *		Predicate			partial-index predicate, or NIL if none150 *		PredicateState		exec state for predicate, or NIL if none151 *		ExclusionOps		Per-column exclusion operators, or NULL if none152 *		ExclusionProcs		Underlying function OIDs for ExclusionOps153 *		ExclusionStrats		Opclass strategy numbers for ExclusionOps154 *		UniqueOps			These are like Exclusion*, but for unique indexes155 *		UniqueProcs156 *		UniqueStrats157 *		Unique				is it a unique index?158 *		OpclassOptions		opclass-specific options, or NULL if none159 *		ReadyForInserts		is it valid for inserts?160 *		CheckedUnchanged	IndexUnchanged status determined yet?161 *		IndexUnchanged		aminsert hint, cached for retail inserts162 *		Concurrent			are we doing a concurrent index build?163 *		BrokenHotChain		did we detect any broken HOT chains?164 *		Summarizing			is it a summarizing index?165 *		ParallelWorkers		# of workers requested (excludes leader)166 *		Am					Oid of index AM167 *		AmCache				private cache area for index AM168 *		Context				memory context holding this IndexInfo169 *170 * ii_Concurrent, ii_BrokenHotChain, and ii_ParallelWorkers are used only171 * during index build; they're conventionally zeroed otherwise.172 * ----------------173 */174typedef struct IndexInfo175{176	NodeTag		type;177	int			ii_NumIndexAttrs;	/* total number of columns in index */178	int			ii_NumIndexKeyAttrs;	/* number of key columns in index */179	AttrNumber	ii_IndexAttrNumbers[INDEX_MAX_KEYS];180	List	   *ii_Expressions; /* list of Expr */181	List	   *ii_ExpressionsState;	/* list of ExprState */182	List	   *ii_Predicate;	/* list of Expr */183	ExprState  *ii_PredicateState;184	Oid		   *ii_ExclusionOps;	/* array with one entry per column */185	Oid		   *ii_ExclusionProcs;	/* array with one entry per column */186	uint16	   *ii_ExclusionStrats; /* array with one entry per column */187	Oid		   *ii_UniqueOps;	/* array with one entry per column */188	Oid		   *ii_UniqueProcs; /* array with one entry per column */189	uint16	   *ii_UniqueStrats;	/* array with one entry per column */190	Datum	   *ii_OpclassOptions;	/* array with one entry per column */191	bool		ii_Unique;192	bool		ii_NullsNotDistinct;193	bool		ii_ReadyForInserts;194	bool		ii_CheckedUnchanged;195	bool		ii_IndexUnchanged;196	bool		ii_Concurrent;197	bool		ii_BrokenHotChain;198	bool		ii_Summarizing;199	int			ii_ParallelWorkers;200	Oid			ii_Am;201	void	   *ii_AmCache;202	MemoryContext ii_Context;203} IndexInfo;204 205/* ----------------206 *	  ExprContext_CB207 *208 *		List of callbacks to be called at ExprContext shutdown.209 * ----------------210 */211typedef void (*ExprContextCallbackFunction) (Datum arg);212 213typedef struct ExprContext_CB214{215	struct ExprContext_CB *next;216	ExprContextCallbackFunction function;217	Datum		arg;218} ExprContext_CB;219 220/* ----------------221 *	  ExprContext222 *223 *		This class holds the "current context" information224 *		needed to evaluate expressions for doing tuple qualifications225 *		and tuple projections.  For example, if an expression refers226 *		to an attribute in the current inner tuple then we need to know227 *		what the current inner tuple is and so we look at the expression228 *		context.229 *230 *	There are two memory contexts associated with an ExprContext:231 *	* ecxt_per_query_memory is a query-lifespan context, typically the same232 *	  context the ExprContext node itself is allocated in.  This context233 *	  can be used for purposes such as storing function call cache info.234 *	* ecxt_per_tuple_memory is a short-term context for expression results.235 *	  As the name suggests, it will typically be reset once per tuple,236 *	  before we begin to evaluate expressions for that tuple.  Each237 *	  ExprContext normally has its very own per-tuple memory context.238 *239 *	CurrentMemoryContext should be set to ecxt_per_tuple_memory before240 *	calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().241 * ----------------242 */243typedef struct ExprContext244{245	NodeTag		type;246 247	/* Tuples that Var nodes in expression may refer to */248#define FIELDNO_EXPRCONTEXT_SCANTUPLE 1249	TupleTableSlot *ecxt_scantuple;250#define FIELDNO_EXPRCONTEXT_INNERTUPLE 2251	TupleTableSlot *ecxt_innertuple;252#define FIELDNO_EXPRCONTEXT_OUTERTUPLE 3253	TupleTableSlot *ecxt_outertuple;254 255	/* Memory contexts for expression evaluation --- see notes above */256	MemoryContext ecxt_per_query_memory;257	MemoryContext ecxt_per_tuple_memory;258 259	/* Values to substitute for Param nodes in expression */260	ParamExecData *ecxt_param_exec_vals;	/* for PARAM_EXEC params */261	ParamListInfo ecxt_param_list_info; /* for other param types */262 263	/*264	 * Values to substitute for Aggref nodes in the expressions of an Agg265	 * node, or for WindowFunc nodes within a WindowAgg node.266	 */267#define FIELDNO_EXPRCONTEXT_AGGVALUES 8268	Datum	   *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */269#define FIELDNO_EXPRCONTEXT_AGGNULLS 9270	bool	   *ecxt_aggnulls;	/* null flags for aggs/windowfuncs */271 272	/* Value to substitute for CaseTestExpr nodes in expression */273#define FIELDNO_EXPRCONTEXT_CASEDATUM 10274	Datum		caseValue_datum;275#define FIELDNO_EXPRCONTEXT_CASENULL 11276	bool		caseValue_isNull;277 278	/* Value to substitute for CoerceToDomainValue nodes in expression */279#define FIELDNO_EXPRCONTEXT_DOMAINDATUM 12280	Datum		domainValue_datum;281#define FIELDNO_EXPRCONTEXT_DOMAINNULL 13282	bool		domainValue_isNull;283 284	/* Link to containing EState (NULL if a standalone ExprContext) */285	struct EState *ecxt_estate;286 287	/* Functions to call back when ExprContext is shut down or rescanned */288	ExprContext_CB *ecxt_callbacks;289} ExprContext;290 291/*292 * Set-result status used when evaluating functions potentially returning a293 * set.294 */295typedef enum296{297	ExprSingleResult,			/* expression does not return a set */298	ExprMultipleResult,			/* this result is an element of a set */299	ExprEndResult				/* there are no more elements in the set */300} ExprDoneCond;301 302/*303 * Return modes for functions returning sets.  Note values must be chosen304 * as separate bits so that a bitmask can be formed to indicate supported305 * modes.  SFRM_Materialize_Random and SFRM_Materialize_Preferred are306 * auxiliary flags about SFRM_Materialize mode, rather than separate modes.307 */308typedef enum309{310	SFRM_ValuePerCall = 0x01,	/* one value returned per call */311	SFRM_Materialize = 0x02,	/* result set instantiated in Tuplestore */312	SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */313	SFRM_Materialize_Preferred = 0x08	/* caller prefers Tuplestore */314} SetFunctionReturnMode;315 316/*317 * When calling a function that might return a set (multiple rows),318 * a node of this type is passed as fcinfo->resultinfo to allow319 * return status to be passed back.  A function returning set should320 * raise an error if no such resultinfo is provided.321 */322typedef struct ReturnSetInfo323{324	NodeTag		type;325	/* values set by caller: */326	ExprContext *econtext;		/* context function is being called in */327	TupleDesc	expectedDesc;	/* tuple descriptor expected by caller */328	int			allowedModes;	/* bitmask: return modes caller can handle */329	/* result status from function (but pre-initialized by caller): */330	SetFunctionReturnMode returnMode;	/* actual return mode */331	ExprDoneCond isDone;		/* status for ValuePerCall mode */332	/* fields filled by function in Materialize return mode: */333	Tuplestorestate *setResult; /* holds the complete returned tuple set */334	TupleDesc	setDesc;		/* actual descriptor for returned tuples */335} ReturnSetInfo;336 337/* ----------------338 *		ProjectionInfo node information339 *340 *		This is all the information needed to perform projections ---341 *		that is, form new tuples by evaluation of targetlist expressions.342 *		Nodes which need to do projections create one of these.343 *344 *		The target tuple slot is kept in ProjectionInfo->pi_state.resultslot.345 *		ExecProject() evaluates the tlist, forms a tuple, and stores it346 *		in the given slot.  Note that the result will be a "virtual" tuple347 *		unless ExecMaterializeSlot() is then called to force it to be348 *		converted to a physical tuple.  The slot must have a tupledesc349 *		that matches the output of the tlist!350 * ----------------351 */352typedef struct ProjectionInfo353{354	NodeTag		type;355	/* instructions to evaluate projection */356	ExprState	pi_state;357	/* expression context in which to evaluate expression */358	ExprContext *pi_exprContext;359} ProjectionInfo;360 361/* ----------------362 *	  JunkFilter363 *364 *	  This class is used to store information regarding junk attributes.365 *	  A junk attribute is an attribute in a tuple that is needed only for366 *	  storing intermediate information in the executor, and does not belong367 *	  in emitted tuples.  For example, when we do an UPDATE query,368 *	  the planner adds a "junk" entry to the targetlist so that the tuples369 *	  returned to ExecutePlan() contain an extra attribute: the ctid of370 *	  the tuple to be updated.  This is needed to do the update, but we371 *	  don't want the ctid to be part of the stored new tuple!  So, we372 *	  apply a "junk filter" to remove the junk attributes and form the373 *	  real output tuple.  The junkfilter code also provides routines to374 *	  extract the values of the junk attribute(s) from the input tuple.375 *376 *	  targetList:		the original target list (including junk attributes).377 *	  cleanTupType:		the tuple descriptor for the "clean" tuple (with378 *						junk attributes removed).379 *	  cleanMap:			A map with the correspondence between the non-junk380 *						attribute numbers of the "original" tuple and the381 *						attribute numbers of the "clean" tuple.382 *	  resultSlot:		tuple slot used to hold cleaned tuple.383 * ----------------384 */385typedef struct JunkFilter386{387	NodeTag		type;388	List	   *jf_targetList;389	TupleDesc	jf_cleanTupType;390	AttrNumber *jf_cleanMap;391	TupleTableSlot *jf_resultSlot;392} JunkFilter;393 394/*395 * OnConflictSetState396 *397 * Executor state of an ON CONFLICT DO UPDATE operation.398 */399typedef struct OnConflictSetState400{401	NodeTag		type;402 403	TupleTableSlot *oc_Existing;	/* slot to store existing target tuple in */404	TupleTableSlot *oc_ProjSlot;	/* CONFLICT ... SET ... projection target */405	ProjectionInfo *oc_ProjInfo;	/* for ON CONFLICT DO UPDATE SET */406	ExprState  *oc_WhereClause; /* state for the WHERE clause */407} OnConflictSetState;408 409/* ----------------410 *	 MergeActionState information411 *412 *	Executor state for a MERGE action.413 * ----------------414 */415typedef struct MergeActionState416{417	NodeTag		type;418 419	MergeAction *mas_action;	/* associated MergeAction node */420	ProjectionInfo *mas_proj;	/* projection of the action's targetlist for421								 * this rel */422	ExprState  *mas_whenqual;	/* WHEN [NOT] MATCHED AND conditions */423} MergeActionState;424 425/*426 * ResultRelInfo427 *428 * Whenever we update an existing relation, we have to update indexes on the429 * relation, and perhaps also fire triggers.  ResultRelInfo holds all the430 * information needed about a result relation, including indexes.431 *432 * Normally, a ResultRelInfo refers to a table that is in the query's range433 * table; then ri_RangeTableIndex is the RT index and ri_RelationDesc is434 * just a copy of the relevant es_relations[] entry.  However, in some435 * situations we create ResultRelInfos for relations that are not in the436 * range table, namely for targets of tuple routing in a partitioned table,437 * and when firing triggers in tables other than the target tables (See438 * ExecGetTriggerResultRel).  In these situations, ri_RangeTableIndex is 0439 * and ri_RelationDesc is a separately-opened relcache pointer that needs to440 * be separately closed.441 */442typedef struct ResultRelInfo443{444	NodeTag		type;445 446	/* result relation's range table index, or 0 if not in range table */447	Index		ri_RangeTableIndex;448 449	/* relation descriptor for result relation */450	Relation	ri_RelationDesc;451 452	/* # of indices existing on result relation */453	int			ri_NumIndices;454 455	/* array of relation descriptors for indices */456	RelationPtr ri_IndexRelationDescs;457 458	/* array of key/attr info for indices */459	IndexInfo **ri_IndexRelationInfo;460 461	/*462	 * For UPDATE/DELETE result relations, the attribute number of the row463	 * identity junk attribute in the source plan's output tuples464	 */465	AttrNumber	ri_RowIdAttNo;466 467	/* For UPDATE, attnums of generated columns to be computed */468	Bitmapset  *ri_extraUpdatedCols;469 470	/* Projection to generate new tuple in an INSERT/UPDATE */471	ProjectionInfo *ri_projectNew;472	/* Slot to hold that tuple */473	TupleTableSlot *ri_newTupleSlot;474	/* Slot to hold the old tuple being updated */475	TupleTableSlot *ri_oldTupleSlot;476	/* Have the projection and the slots above been initialized? */477	bool		ri_projectNewInfoValid;478 479	/* triggers to be fired, if any */480	TriggerDesc *ri_TrigDesc;481 482	/* cached lookup info for trigger functions */483	FmgrInfo   *ri_TrigFunctions;484 485	/* array of trigger WHEN expr states */486	ExprState **ri_TrigWhenExprs;487 488	/* optional runtime measurements for triggers */489	Instrumentation *ri_TrigInstrument;490 491	/* On-demand created slots for triggers / returning processing */492	TupleTableSlot *ri_ReturningSlot;	/* for trigger output tuples */493	TupleTableSlot *ri_TrigOldSlot; /* for a trigger's old tuple */494	TupleTableSlot *ri_TrigNewSlot; /* for a trigger's new tuple */495 496	/* FDW callback functions, if foreign table */497	struct FdwRoutine *ri_FdwRoutine;498 499	/* available to save private state of FDW */500	void	   *ri_FdwState;501 502	/* true when modifying foreign table directly */503	bool		ri_usesFdwDirectModify;504 505	/* batch insert stuff */506	int			ri_NumSlots;	/* number of slots in the array */507	int			ri_NumSlotsInitialized; /* number of initialized slots */508	int			ri_BatchSize;	/* max slots inserted in a single batch */509	TupleTableSlot **ri_Slots;	/* input tuples for batch insert */510	TupleTableSlot **ri_PlanSlots;511 512	/* list of WithCheckOption's to be checked */513	List	   *ri_WithCheckOptions;514 515	/* list of WithCheckOption expr states */516	List	   *ri_WithCheckOptionExprs;517 518	/* array of constraint-checking expr states */519	ExprState **ri_ConstraintExprs;520 521	/* arrays of stored generated columns expr states, for INSERT and UPDATE */522	ExprState **ri_GeneratedExprsI;523	ExprState **ri_GeneratedExprsU;524 525	/* number of stored generated columns we need to compute */526	int			ri_NumGeneratedNeededI;527	int			ri_NumGeneratedNeededU;528 529	/* list of RETURNING expressions */530	List	   *ri_returningList;531 532	/* for computing a RETURNING list */533	ProjectionInfo *ri_projectReturning;534 535	/* list of arbiter indexes to use to check conflicts */536	List	   *ri_onConflictArbiterIndexes;537 538	/* ON CONFLICT evaluation state */539	OnConflictSetState *ri_onConflict;540 541	/* for MERGE, lists of MergeActionState */542	List	   *ri_matchedMergeAction;543	List	   *ri_notMatchedMergeAction;544 545	/* partition check expression state (NULL if not set up yet) */546	ExprState  *ri_PartitionCheckExpr;547 548	/*549	 * Map to convert child result relation tuples to the format of the table550	 * actually mentioned in the query (called "root").  Computed only if551	 * needed.  A NULL map value indicates that no conversion is needed, so we552	 * must have a separate flag to show if the map has been computed.553	 */554	TupleConversionMap *ri_ChildToRootMap;555	bool		ri_ChildToRootMapValid;556 557	/*558	 * As above, but in the other direction.559	 */560	TupleConversionMap *ri_RootToChildMap;561	bool		ri_RootToChildMapValid;562 563	/*564	 * Information needed by tuple routing target relations565	 *566	 * RootResultRelInfo gives the target relation mentioned in the query, if567	 * it's a partitioned table. It is not set if the target relation568	 * mentioned in the query is an inherited table, nor when tuple routing is569	 * not needed.570	 *571	 * PartitionTupleSlot is non-NULL if RootToChild conversion is needed and572	 * the relation is a partition.573	 */574	struct ResultRelInfo *ri_RootResultRelInfo;575	TupleTableSlot *ri_PartitionTupleSlot;576 577	/* for use by copyfrom.c when performing multi-inserts */578	struct CopyMultiInsertBuffer *ri_CopyMultiInsertBuffer;579 580	/*581	 * Used when a leaf partition is involved in a cross-partition update of582	 * one of its ancestors; see ExecCrossPartitionUpdateForeignKey().583	 */584	List	   *ri_ancestorResultRels;585} ResultRelInfo;586 587/* ----------------588 *	  AsyncRequest589 *590 * State for an asynchronous tuple request.591 * ----------------592 */593typedef struct AsyncRequest594{595	struct PlanState *requestor;	/* Node that wants a tuple */596	struct PlanState *requestee;	/* Node from which a tuple is wanted */597	int			request_index;	/* Scratch space for requestor */598	bool		callback_pending;	/* Callback is needed */599	bool		request_complete;	/* Request complete, result valid */600	TupleTableSlot *result;		/* Result (NULL or an empty slot if no more601								 * tuples) */602} AsyncRequest;603 604/* ----------------605 *	  EState information606 *607 * Working state for an Executor invocation608 * ----------------609 */610typedef struct EState611{612	NodeTag		type;613 614	/* Basic state for all query types: */615	ScanDirection es_direction; /* current scan direction */616	Snapshot	es_snapshot;	/* time qual to use */617	Snapshot	es_crosscheck_snapshot; /* crosscheck time qual for RI */618	List	   *es_range_table; /* List of RangeTblEntry */619	Index		es_range_table_size;	/* size of the range table arrays */620	Relation   *es_relations;	/* Array of per-range-table-entry Relation621								 * pointers, or NULL if not yet opened */622	struct ExecRowMark **es_rowmarks;	/* Array of per-range-table-entry623										 * ExecRowMarks, or NULL if none */624	List	   *es_rteperminfos;	/* List of RTEPermissionInfo */625	PlannedStmt *es_plannedstmt;	/* link to top of plan tree */626	const char *es_sourceText;	/* Source text from QueryDesc */627 628	JunkFilter *es_junkFilter;	/* top-level junk filter, if any */629 630	/* If query can insert/delete tuples, the command ID to mark them with */631	CommandId	es_output_cid;632 633	/* Info about target table(s) for insert/update/delete queries: */634	ResultRelInfo **es_result_relations;	/* Array of per-range-table-entry635											 * ResultRelInfo pointers, or NULL636											 * if not a target table */637	List	   *es_opened_result_relations; /* List of non-NULL entries in638											 * es_result_relations in no639											 * specific order */640 641	PartitionDirectory es_partition_directory;	/* for PartitionDesc lookup */642 643	/*644	 * The following list contains ResultRelInfos created by the tuple routing645	 * code for partitions that aren't found in the es_result_relations array.646	 */647	List	   *es_tuple_routing_result_relations;648 649	/* Stuff used for firing triggers: */650	List	   *es_trig_target_relations;	/* trigger-only ResultRelInfos */651 652	/* Parameter info: */653	ParamListInfo es_param_list_info;	/* values of external params */654	ParamExecData *es_param_exec_vals;	/* values of internal params */655 656	QueryEnvironment *es_queryEnv;	/* query environment */657 658	/* Other working state: */659	MemoryContext es_query_cxt; /* per-query context in which EState lives */660 661	List	   *es_tupleTable;	/* List of TupleTableSlots */662 663	uint64		es_processed;	/* # of tuples processed during one664								 * ExecutorRun() call. */665	uint64		es_total_processed; /* total # of tuples aggregated across all666									 * ExecutorRun() calls. */667 668	int			es_top_eflags;	/* eflags passed to ExecutorStart */669	int			es_instrument;	/* OR of InstrumentOption flags */670	bool		es_finished;	/* true when ExecutorFinish is done */671 672	List	   *es_exprcontexts;	/* List of ExprContexts within EState */673 674	List	   *es_subplanstates;	/* List of PlanState for SubPlans */675 676	List	   *es_auxmodifytables; /* List of secondary ModifyTableStates */677 678	/*679	 * this ExprContext is for per-output-tuple operations, such as constraint680	 * checks and index-value computations.  It will be reset for each output681	 * tuple.  Note that it will be created only if needed.682	 */683	ExprContext *es_per_tuple_exprcontext;684 685	/*686	 * If not NULL, this is an EPQState's EState. This is a field in EState687	 * both to allow EvalPlanQual aware executor nodes to detect that they688	 * need to perform EPQ related work, and to provide necessary information689	 * to do so.690	 */691	struct EPQState *es_epq_active;692 693	bool		es_use_parallel_mode;	/* can we use parallel workers? */694 695	/* The per-query shared memory area to use for parallel execution. */696	struct dsa_area *es_query_dsa;697 698	/*699	 * JIT information. es_jit_flags indicates whether JIT should be performed700	 * and with which options.  es_jit is created on-demand when JITing is701	 * performed.702	 *703	 * es_jit_worker_instr is the combined, on demand allocated,704	 * instrumentation from all workers. The leader's instrumentation is kept705	 * separate, and is combined on demand by ExplainPrintJITSummary().706	 */707	int			es_jit_flags;708	struct JitContext *es_jit;709	struct JitInstrumentation *es_jit_worker_instr;710 711	/*712	 * Lists of ResultRelInfos for foreign tables on which batch-inserts are713	 * to be executed and owning ModifyTableStates, stored in the same order.714	 */715	List	   *es_insert_pending_result_relations;716	List	   *es_insert_pending_modifytables;717} EState;718 719 720/*721 * ExecRowMark -722 *	   runtime representation of FOR [KEY] UPDATE/SHARE clauses723 *724 * When doing UPDATE/DELETE/MERGE/SELECT FOR [KEY] UPDATE/SHARE, we will have725 * an ExecRowMark for each non-target relation in the query (except inheritance726 * parent RTEs, which can be ignored at runtime).  Virtual relations such as727 * subqueries-in-FROM will have an ExecRowMark with relation == NULL.  See728 * PlanRowMark for details about most of the fields.  In addition to fields729 * directly derived from PlanRowMark, we store an activity flag (to denote730 * inactive children of inheritance trees), curCtid, which is used by the731 * WHERE CURRENT OF code, and ermExtra, which is available for use by the plan732 * node that sources the relation (e.g., for a foreign table the FDW can use733 * ermExtra to hold information).734 *735 * EState->es_rowmarks is an array of these structs, indexed by RT index,736 * with NULLs for irrelevant RT indexes.  es_rowmarks itself is NULL if737 * there are no rowmarks.738 */739typedef struct ExecRowMark740{741	Relation	relation;		/* opened and suitably locked relation */742	Oid			relid;			/* its OID (or InvalidOid, if subquery) */743	Index		rti;			/* its range table index */744	Index		prti;			/* parent range table index, if child */745	Index		rowmarkId;		/* unique identifier for resjunk columns */746	RowMarkType markType;		/* see enum in nodes/plannodes.h */747	LockClauseStrength strength;	/* LockingClause's strength, or LCS_NONE */748	LockWaitPolicy waitPolicy;	/* NOWAIT and SKIP LOCKED */749	bool		ermActive;		/* is this mark relevant for current tuple? */750	ItemPointerData curCtid;	/* ctid of currently locked tuple, if any */751	void	   *ermExtra;		/* available for use by relation source node */752} ExecRowMark;753 754/*755 * ExecAuxRowMark -756 *	   additional runtime representation of FOR [KEY] UPDATE/SHARE clauses757 *758 * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to759 * deal with.  In addition to a pointer to the related entry in es_rowmarks,760 * this struct carries the column number(s) of the resjunk columns associated761 * with the rowmark (see comments for PlanRowMark for more detail).762 */763typedef struct ExecAuxRowMark764{765	ExecRowMark *rowmark;		/* related entry in es_rowmarks */766	AttrNumber	ctidAttNo;		/* resno of ctid junk attribute, if any */767	AttrNumber	toidAttNo;		/* resno of tableoid junk attribute, if any */768	AttrNumber	wholeAttNo;		/* resno of whole-row junk attribute, if any */769} ExecAuxRowMark;770 771 772/* ----------------------------------------------------------------773 *				 Tuple Hash Tables774 *775 * All-in-memory tuple hash tables are used for a number of purposes.776 *777 * Note: tab_hash_funcs are for the key datatype(s) stored in the table,778 * and tab_eq_funcs are non-cross-type equality operators for those types.779 * Normally these are the only functions used, but FindTupleHashEntry()780 * supports searching a hashtable using cross-data-type hashing.  For that,781 * the caller must supply hash functions for the LHS datatype as well as782 * the cross-type equality operators to use.  in_hash_funcs and cur_eq_func783 * are set to point to the caller's function arrays while doing such a search.784 * During LookupTupleHashEntry(), they point to tab_hash_funcs and785 * tab_eq_func respectively.786 * ----------------------------------------------------------------787 */788typedef struct TupleHashEntryData *TupleHashEntry;789typedef struct TupleHashTableData *TupleHashTable;790 791typedef struct TupleHashEntryData792{793	MinimalTuple firstTuple;	/* copy of first tuple in this group */794	void	   *additional;		/* user data */795	uint32		status;			/* hash status */796	uint32		hash;			/* hash value (cached) */797} TupleHashEntryData;798 799/* define parameters necessary to generate the tuple hash table interface */800#define SH_PREFIX tuplehash801#define SH_ELEMENT_TYPE TupleHashEntryData802#define SH_KEY_TYPE MinimalTuple803#define SH_SCOPE extern804#define SH_DECLARE805#include "lib/simplehash.h"806 807typedef struct TupleHashTableData808{809	tuplehash_hash *hashtab;	/* underlying hash table */810	int			numCols;		/* number of columns in lookup key */811	AttrNumber *keyColIdx;		/* attr numbers of key columns */812	FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */813	ExprState  *tab_eq_func;	/* comparator for table datatype(s) */814	Oid		   *tab_collations; /* collations for hash and comparison */815	MemoryContext tablecxt;		/* memory context containing table */816	MemoryContext tempcxt;		/* context for function evaluations */817	Size		entrysize;		/* actual size to make each hash entry */818	TupleTableSlot *tableslot;	/* slot for referencing table entries */819	/* The following fields are set transiently for each table search: */820	TupleTableSlot *inputslot;	/* current input tuple's slot */821	FmgrInfo   *in_hash_funcs;	/* hash functions for input datatype(s) */822	ExprState  *cur_eq_func;	/* comparator for input vs. table */823	uint32		hash_iv;		/* hash-function IV */824	ExprContext *exprcontext;	/* expression context */825}			TupleHashTableData;826 827typedef tuplehash_iterator TupleHashIterator;828 829/*830 * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.831 * Use ResetTupleHashIterator if the table can be frozen (in this case no832 * explicit scan termination is needed).833 */834#define InitTupleHashIterator(htable, iter) \835	tuplehash_start_iterate(htable->hashtab, iter)836#define TermTupleHashIterator(iter) \837	((void) 0)838#define ResetTupleHashIterator(htable, iter) \839	InitTupleHashIterator(htable, iter)840#define ScanTupleHashTable(htable, iter) \841	tuplehash_iterate(htable->hashtab, iter)842 843 844/* ----------------------------------------------------------------845 *				 Expression State Nodes846 *847 * Formerly, there was a separate executor expression state node corresponding848 * to each node in a planned expression tree.  That's no longer the case; for849 * common expression node types, all the execution info is embedded into850 * step(s) in a single ExprState node.  But we still have a few executor state851 * node types for selected expression node types, mostly those in which info852 * has to be shared with other parts of the execution state tree.853 * ----------------------------------------------------------------854 */855 856/* ----------------857 *		WindowFuncExprState node858 * ----------------859 */860typedef struct WindowFuncExprState861{862	NodeTag		type;863	WindowFunc *wfunc;			/* expression plan node */864	List	   *args;			/* ExprStates for argument expressions */865	ExprState  *aggfilter;		/* FILTER expression */866	int			wfuncno;		/* ID number for wfunc within its plan node */867} WindowFuncExprState;868 869 870/* ----------------871 *		SetExprState node872 *873 * State for evaluating a potentially set-returning expression (like FuncExpr874 * or OpExpr).  In some cases, like some of the expressions in ROWS FROM(...)875 * the expression might not be a SRF, but nonetheless it uses the same876 * machinery as SRFs; it will be treated as a SRF returning a single row.877 * ----------------878 */879typedef struct SetExprState880{881	NodeTag		type;882	Expr	   *expr;			/* expression plan node */883	List	   *args;			/* ExprStates for argument expressions */884 885	/*886	 * In ROWS FROM, functions can be inlined, removing the FuncExpr normally887	 * inside.  In such a case this is the compiled expression (which cannot888	 * return a set), which'll be evaluated using regular ExecEvalExpr().889	 */890	ExprState  *elidedFuncState;891 892	/*893	 * Function manager's lookup info for the target function.  If func.fn_oid894	 * is InvalidOid, we haven't initialized it yet (nor any of the following895	 * fields, except funcReturnsSet).896	 */897	FmgrInfo	func;898 899	/*900	 * For a set-returning function (SRF) that returns a tuplestore, we keep901	 * the tuplestore here and dole out the result rows one at a time. The902	 * slot holds the row currently being returned.903	 */904	Tuplestorestate *funcResultStore;905	TupleTableSlot *funcResultSlot;906 907	/*908	 * In some cases we need to compute a tuple descriptor for the function's909	 * output.  If so, it's stored here.910	 */911	TupleDesc	funcResultDesc;912	bool		funcReturnsTuple;	/* valid when funcResultDesc isn't NULL */913 914	/*915	 * Remember whether the function is declared to return a set.  This is set916	 * by ExecInitExpr, and is valid even before the FmgrInfo is set up.917	 */918	bool		funcReturnsSet;919 920	/*921	 * setArgsValid is true when we are evaluating a set-returning function922	 * that uses value-per-call mode and we are in the middle of a call923	 * series; we want to pass the same argument values to the function again924	 * (and again, until it returns ExprEndResult).  This indicates that925	 * fcinfo_data already contains valid argument data.926	 */927	bool		setArgsValid;928 929	/*930	 * Flag to remember whether we have registered a shutdown callback for931	 * this SetExprState.  We do so only if funcResultStore or setArgsValid932	 * has been set at least once (since all the callback is for is to release933	 * the tuplestore or clear setArgsValid).934	 */935	bool		shutdown_reg;	/* a shutdown callback is registered */936 937	/*938	 * Call parameter structure for the function.  This has been initialized939	 * (by InitFunctionCallInfoData) if func.fn_oid is valid.  It also saves940	 * argument values between calls, when setArgsValid is true.941	 */942	FunctionCallInfo fcinfo;943} SetExprState;944 945/* ----------------946 *		SubPlanState node947 * ----------------948 */949typedef struct SubPlanState950{951	NodeTag		type;952	SubPlan    *subplan;		/* expression plan node */953	struct PlanState *planstate;	/* subselect plan's state tree */954	struct PlanState *parent;	/* parent plan node's state tree */955	ExprState  *testexpr;		/* state of combining expression */956	List	   *args;			/* states of argument expression(s) */957	HeapTuple	curTuple;		/* copy of most recent tuple from subplan */958	Datum		curArray;		/* most recent array from ARRAY() subplan */959	/* these are used when hashing the subselect's output: */960	TupleDesc	descRight;		/* subselect desc after projection */961	ProjectionInfo *projLeft;	/* for projecting lefthand exprs */962	ProjectionInfo *projRight;	/* for projecting subselect output */963	TupleHashTable hashtable;	/* hash table for no-nulls subselect rows */964	TupleHashTable hashnulls;	/* hash table for rows with null(s) */965	bool		havehashrows;	/* true if hashtable is not empty */966	bool		havenullrows;	/* true if hashnulls is not empty */967	MemoryContext hashtablecxt; /* memory context containing hash tables */968	MemoryContext hashtempcxt;	/* temp memory context for hash tables */969	ExprContext *innerecontext; /* econtext for computing inner tuples */970	int			numCols;		/* number of columns being hashed */971	/* each of the remaining fields is an array of length numCols: */972	AttrNumber *keyColIdx;		/* control data for hash tables */973	Oid		   *tab_eq_funcoids;	/* equality func oids for table974									 * datatype(s) */975	Oid		   *tab_collations; /* collations for hash and comparison */976	FmgrInfo   *tab_hash_funcs; /* hash functions for table datatype(s) */977	FmgrInfo   *tab_eq_funcs;	/* equality functions for table datatype(s) */978	FmgrInfo   *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */979	FmgrInfo   *cur_eq_funcs;	/* equality functions for LHS vs. table */980	ExprState  *cur_eq_comp;	/* equality comparator for LHS vs. table */981} SubPlanState;982 983/*984 * DomainConstraintState - one item to check during CoerceToDomain985 *986 * Note: we consider this to be part of an ExprState tree, so we give it987 * a name following the xxxState convention.  But there's no directly988 * associated plan-tree node.989 */990typedef enum DomainConstraintType991{992	DOM_CONSTRAINT_NOTNULL,993	DOM_CONSTRAINT_CHECK994} DomainConstraintType;995 996typedef struct DomainConstraintState997{998	NodeTag		type;999	DomainConstraintType constrainttype;	/* constraint type */1000	char	   *name;			/* name of constraint (for error msgs) */1001	Expr	   *check_expr;		/* for CHECK, a boolean expression */1002	ExprState  *check_exprstate;	/* check_expr's eval state, or NULL */1003} DomainConstraintState;1004 1005 1006/* ----------------------------------------------------------------1007 *				 Executor State Trees1008 *1009 * An executing query has a PlanState tree paralleling the Plan tree1010 * that describes the plan.1011 * ----------------------------------------------------------------1012 */1013 1014/* ----------------1015 *	 ExecProcNodeMtd1016 *1017 * This is the method called by ExecProcNode to return the next tuple1018 * from an executor node.  It returns NULL, or an empty TupleTableSlot,1019 * if no more tuples are available.1020 * ----------------1021 */1022typedef TupleTableSlot *(*ExecProcNodeMtd) (struct PlanState *pstate);1023 1024/* ----------------1025 *		PlanState node1026 *1027 * We never actually instantiate any PlanState nodes; this is just the common1028 * abstract superclass for all PlanState-type nodes.1029 * ----------------1030 */1031typedef struct PlanState1032{1033	pg_node_attr(abstract)1034 1035	NodeTag		type;1036 1037	Plan	   *plan;			/* associated Plan node */1038 1039	EState	   *state;			/* at execution time, states of individual1040								 * nodes point to one EState for the whole1041								 * top-level plan */1042 1043	ExecProcNodeMtd ExecProcNode;	/* function to return next tuple */1044	ExecProcNodeMtd ExecProcNodeReal;	/* actual function, if above is a1045										 * wrapper */1046 1047	Instrumentation *instrument;	/* Optional runtime stats for this node */1048	WorkerInstrumentation *worker_instrument;	/* per-worker instrumentation */1049 1050	/* Per-worker JIT instrumentation */1051	struct SharedJitInstrumentation *worker_jit_instrument;1052 1053	/*1054	 * Common structural data for all Plan types.  These links to subsidiary1055	 * state trees parallel links in the associated plan tree (except for the1056	 * subPlan list, which does not exist in the plan tree).1057	 */1058	ExprState  *qual;			/* boolean qual condition */1059	struct PlanState *lefttree; /* input plan tree(s) */1060	struct PlanState *righttree;1061 1062	List	   *initPlan;		/* Init SubPlanState nodes (un-correlated expr1063								 * subselects) */1064	List	   *subPlan;		/* SubPlanState nodes in my expressions */1065 1066	/*1067	 * State for management of parameter-change-driven rescanning1068	 */1069	Bitmapset  *chgParam;		/* set of IDs of changed Params */1070 1071	/*1072	 * Other run-time state needed by most if not all node types.1073	 */1074	TupleDesc	ps_ResultTupleDesc; /* node's return type */1075	TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */1076	ExprContext *ps_ExprContext;	/* node's expression-evaluation context */1077	ProjectionInfo *ps_ProjInfo;	/* info for doing tuple projection */1078 1079	bool		async_capable;	/* true if node is async-capable */1080 1081	/*1082	 * Scanslot's descriptor if known. This is a bit of a hack, but otherwise1083	 * it's hard for expression compilation to optimize based on the1084	 * descriptor, without encoding knowledge about all executor nodes.1085	 */1086	TupleDesc	scandesc;1087 1088	/*1089	 * Define the slot types for inner, outer and scanslots for expression1090	 * contexts with this state as a parent.  If *opsset is set, then1091	 * *opsfixed indicates whether *ops is guaranteed to be the type of slot1092	 * used. That means that every slot in the corresponding1093	 * ExprContext.ecxt_*tuple will point to a slot of that type, while1094	 * evaluating the expression.  If *opsfixed is false, but *ops is set,1095	 * that indicates the most likely type of slot.1096	 *1097	 * The scan* fields are set by ExecInitScanTupleSlot(). If that's not1098	 * called, nodes can initialize the fields themselves.1099	 *1100	 * If outer/inneropsset is false, the information is inferred on-demand1101	 * using ExecGetResultSlotOps() on ->righttree/lefttree, using the1102	 * corresponding node's resultops* fields.1103	 *1104	 * The result* fields are automatically set when ExecInitResultSlot is1105	 * used (be it directly or when the slot is created by1106	 * ExecAssignScanProjectionInfo() /1107	 * ExecConditionalAssignProjectionInfo()).  If no projection is necessary1108	 * ExecConditionalAssignProjectionInfo() defaults those fields to the scan1109	 * operations.1110	 */1111	const TupleTableSlotOps *scanops;1112	const TupleTableSlotOps *outerops;1113	const TupleTableSlotOps *innerops;1114	const TupleTableSlotOps *resultops;1115	bool		scanopsfixed;1116	bool		outeropsfixed;1117	bool		inneropsfixed;1118	bool		resultopsfixed;1119	bool		scanopsset;1120	bool		outeropsset;1121	bool		inneropsset;1122	bool		resultopsset;1123} PlanState;1124 1125/* ----------------1126 *	these are defined to avoid confusion problems with "left"1127 *	and "right" and "inner" and "outer".  The convention is that1128 *	the "left" plan is the "outer" plan and the "right" plan is1129 *	the inner plan, but these make the code more readable.1130 * ----------------1131 */1132#define innerPlanState(node)		(((PlanState *)(node))->righttree)1133#define outerPlanState(node)		(((PlanState *)(node))->lefttree)1134 1135/* Macros for inline access to certain instrumentation counters */1136#define InstrCountTuples2(node, delta) \1137	do { \1138		if (((PlanState *)(node))->instrument) \1139			((PlanState *)(node))->instrument->ntuples2 += (delta); \1140	} while (0)1141#define InstrCountFiltered1(node, delta) \1142	do { \1143		if (((PlanState *)(node))->instrument) \1144			((PlanState *)(node))->instrument->nfiltered1 += (delta); \1145	} while(0)1146#define InstrCountFiltered2(node, delta) \1147	do { \1148		if (((PlanState *)(node))->instrument) \1149			((PlanState *)(node))->instrument->nfiltered2 += (delta); \1150	} while(0)1151 1152/*1153 * EPQState is state for executing an EvalPlanQual recheck on a candidate1154 * tuples e.g. in ModifyTable or LockRows.1155 *1156 * To execute EPQ a separate EState is created (stored in ->recheckestate),1157 * which shares some resources, like the rangetable, with the main query's1158 * EState (stored in ->parentestate). The (sub-)tree of the plan that needs to1159 * be rechecked (in ->plan), is separately initialized (into1160 * ->recheckplanstate), but shares plan nodes with the corresponding nodes in1161 * the main query. The scan nodes in that separate executor tree are changed1162 * to return only the current tuple of interest for the respective1163 * table. Those tuples are either provided by the caller (using1164 * EvalPlanQualSlot), and/or found using the rowmark mechanism (non-locking1165 * rowmarks by the EPQ machinery itself, locking ones by the caller).1166 *1167 * While the plan to be checked may be changed using EvalPlanQualSetPlan(),1168 * all such plans need to share the same EState.1169 */1170typedef struct EPQState1171{1172	/* These are initialized by EvalPlanQualInit() and do not change later: */1173	EState	   *parentestate;	/* main query's EState */1174	int			epqParam;		/* ID of Param to force scan node re-eval */1175	List	   *resultRelations;	/* integer list of RT indexes, or NIL */1176 1177	/*1178	 * relsubs_slot[scanrelid - 1] holds the EPQ test tuple to be returned by1179	 * the scan node for the scanrelid'th RT index, in place of performing an1180	 * actual table scan.  Callers should use EvalPlanQualSlot() to fetch1181	 * these slots.1182	 */1183	List	   *tuple_table;	/* tuple table for relsubs_slot */1184	TupleTableSlot **relsubs_slot;1185 1186	/*1187	 * Initialized by EvalPlanQualInit(), may be changed later with1188	 * EvalPlanQualSetPlan():1189	 */1190 1191	Plan	   *plan;			/* plan tree to be executed */1192	List	   *arowMarks;		/* ExecAuxRowMarks (non-locking only) */1193 1194 1195	/*1196	 * The original output tuple to be rechecked.  Set by1197	 * EvalPlanQualSetSlot(), before EvalPlanQualNext() or EvalPlanQual() may1198	 * be called.1199	 */1200	TupleTableSlot *origslot;

Showing the first 1,200 of 2773 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai