gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2371 lines
85KB

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