1/*-------------------------------------------------------------------------
4 * Support routines for scanning RangeFunctions (functions in rangetable).
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/executor/nodeFunctionscan.c
13 *-------------------------------------------------------------------------
17 * ExecFunctionScan scans a function.
18 * ExecFunctionNext retrieve next tuple in sequential order.
19 * ExecInitFunctionScan creates and initializes a functionscan node.
20 * ExecEndFunctionScan releases any storage allocated.
21 * ExecReScanFunctionScan rescans the function
33 * Runtime data for each function being scanned.
39 int colcount;
/* expected number of result columns */
48/* ----------------------------------------------------------------
50 * ----------------------------------------------------------------
52/* ----------------------------------------------------------------
55 * This is a workhorse for ExecFunctionScan
56 * ----------------------------------------------------------------
70 * get information from the estate and scan state
79 * Fast path for the trivial case: the function return type and scan
80 * result type are the same, so we fetch the function result straight
81 * into the scan result slot. No need to update ordinality or
87 * If first time through, read all tuples from function and put them
88 * in a tuplestore. Subsequent calls just fetch tuples from
101 * paranoia - cope if the function, which may have constructed the
102 * tuplestore itself, didn't leave it pointing at the start. This
103 * call is fast, so the overhead shouldn't be an issue.
109 * Get the next tuple from tuplestore.
119 * Increment or decrement ordinal counter before checking for end-of-data,
120 * so that we can move off either end of the result by 1 (and no more than
121 * 1) without losing correct count. See PortalRunSelect for why we can
122 * assume that we won't be called repeatedly in the end-of-data state.
131 * Main loop over functions.
133 * We fetch the function results into func_slots (which match the function
134 * return types), and then copy the values to scanslot (which matches the
135 * scan result type), setting the ordinal column (if any) as well.
140 for (funcno = 0; funcno < node->
nfuncs; funcno++)
146 * If first time through, read all tuples from function and put them
147 * in a tuplestore. Subsequent calls just fetch tuples from
160 * paranoia - cope if the function, which may have constructed the
161 * tuplestore itself, didn't leave it pointing at the start. This
162 * call is fast, so the overhead shouldn't be an issue.
168 * Get the next tuple from tuplestore.
170 * If we have a rowcount for the function, and we know the previous
171 * read position was out of bounds, don't try the read. This allows
172 * backward scan to work when there are mixed row counts present.
185 * If we ran out of data for this function in the forward
186 * direction then we now know how many rows it returned. We need
187 * to know this in order to handle backwards scans. The row count
188 * we store is actually 1+ the actual number, because we have to
189 * position the tuplestore 1 off its end sometimes.
195 * populate the result cols with nulls
207 * we have a result, so just copy it to the result cols.
219 * We're not done until every function result is exhausted; we pad
220 * the shorter results with nulls until then.
227 * ordinal col is always last, per spec.
236 * If alldone, we just return the previously-cleared scanslot. Otherwise,
237 * finish creating the virtual tuple.
246 * FunctionRecheck -- access method routine to recheck a tuple in EvalPlanQual
251 /* nothing to check */
255/* ----------------------------------------------------------------
256 * ExecFunctionScan(node)
258 * Scans the function sequentially and returns the next qualifying
260 * We call the ExecScan() routine and pass it the appropriate
261 * access method functions.
262 * ----------------------------------------------------------------
274/* ----------------------------------------------------------------
275 * ExecInitFunctionScan
276 * ----------------------------------------------------------------
288 /* check for unsupported flags */
292 * FunctionScan should not have any children.
298 * create new ScanState for node
304 scanstate->
eflags = eflags;
307 * are we adding an ordinality column?
311 scanstate->
nfuncs = nfuncs;
315 scanstate->
simple =
false;
318 * Ordinal 0 represents the "before the first row" position.
320 * We need to track ordinal position even when not adding an ordinality
321 * column to the result, in order to handle backwards scanning properly
322 * with multiple functions with different result sizes. (We can't position
323 * any individual function's tuplestore any more than 1 place beyond its
324 * end, so when scanning backwards, we need to know when to start
325 * including the function in the scan again.)
330 * Miscellaneous initialization
332 * create expression context for node
344 int colcount = rtfunc->funccolcount;
354 * Don't allocate the tuplestores; the actual calls to the functions
355 * do that. NULL means that we have not called the function yet (or
356 * need to call it again after a rescan).
362 * Now build a tupdesc showing the result type we expect from the
363 * function. If we have a coldeflist then that takes priority (note
364 * the parser enforces that there is one if the function's nominal
365 * output type is RECORD). Otherwise use get_expr_result_type.
367 * Note that if the function returns a named composite type, that may
368 * now contain more or different columns than it did when the plan was
369 * made. For both that and the RECORD case, we need to check tuple
370 * compatibility. ExecMakeTableFunctionResult handles some of this,
371 * and CheckVarSlotCompatibility provides a backstop.
373 if (rtfunc->funccolnames !=
NIL)
376 rtfunc->funccoltypes,
377 rtfunc->funccoltypmods,
378 rtfunc->funccolcollations);
381 * For RECORD results, make sure a typmod has been assigned. (The
382 * function should do this for itself, but let's cover things in
399 /* Composite data type, e.g. a table's row type */
401 /* Must copy it out of typcache for safety */
406 /* Base data type, i.e. scalar */
410 NULL,
/* don't care about the name here */
420 /* crummy error message, but parser should have caught this */
421 elog(
ERROR,
"function in FROM has unsupported return type");
429 * We only need separate slots for the function results if we are
430 * doing ordinality or multiple functions; otherwise, we'll fetch
431 * function results directly into the scan slot.
446 * Create the combined TupleDesc
448 * If there is just one function without ordinality, the scan result
449 * tupdesc is the same as the function result tupdesc --- except that we
450 * may stuff new names into it below, so drop any rowtype label.
467 for (
i = 0;
i < nfuncs;
i++)
473 for (
j = 1;
j <= colcount;
j++)
477 /* If doing ordinality, add a column of type "bigint" at the end */
482 NULL,
/* don't care about the name here */
492 * Initialize scan slot and type.
498 * Initialize result slot, type and projection.
504 * initialize child expressions
510 * Create a memory context that ExecMakeTableFunctionResult can use to
511 * evaluate function arguments in. We can't use the per-tuple context for
512 * this because it gets reset too often; but we don't want to leak
513 * evaluation results into the query-lifespan context either. We just
514 * need one context, because we evaluate each function separately.
517 "Table function arguments",
523/* ----------------------------------------------------------------
524 * ExecEndFunctionScan
526 * frees any storage allocated through C routines.
527 * ----------------------------------------------------------------
535 * Release slots and tuplestore resources
549/* ----------------------------------------------------------------
550 * ExecReScanFunctionScan
552 * Rescans the relation.
553 * ----------------------------------------------------------------
575 * Here we have a choice whether to drop the tuplestores (and recompute
576 * the function outputs) or just rescan them. We must recompute if an
577 * expression contains changed parameters, else we rescan.
579 * XXX maybe we should recompute if the function is volatile? But in
580 * general the executor doesn't conditionalize its actions on that.
604 /* Reset ordinality counter */
607 /* Make sure we rewind any remaining tuplestores */
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
ExprState * ExecInitQual(List *qual, PlanState *parent)
Tuplestorestate * ExecMakeTableFunctionResult(SetExprState *setexpr, ExprContext *econtext, MemoryContext argContext, TupleDesc expectedDesc, bool randomAccess)
SetExprState * ExecInitTableFunctionResult(Expr *expr, ExprContext *econtext, PlanState *parent)
TupleTableSlot * ExecScan(ScanState *node, ExecScanAccessMtd accessMtd, ExecScanRecheckMtd recheckMtd)
void ExecAssignScanProjectionInfo(ScanState *node)
void ExecScanReScan(ScanState *node)
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
void ExecInitScanTupleSlot(EState *estate, ScanState *scanstate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
void ExecInitResultTypeTL(PlanState *planstate)
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsMinimalTuple
void ExecAssignExprContext(EState *estate, PlanState *planstate)
#define EXEC_FLAG_BACKWARD
bool(* ExecScanRecheckMtd)(ScanState *node, TupleTableSlot *slot)
TupleTableSlot *(* ExecScanAccessMtd)(ScanState *node)
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
@ TYPEFUNC_COMPOSITE_DOMAIN
Assert(PointerIsAligned(start, uint64))
if(TABLE==NULL||TABLE_index==NULL)
MemoryContext CurrentMemoryContext
#define AllocSetContextCreate
#define ALLOCSET_DEFAULT_SIZES
Oid exprCollation(const Node *expr)
static TupleTableSlot * ExecFunctionScan(PlanState *pstate)
FunctionScanState * ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags)
static TupleTableSlot * FunctionNext(FunctionScanState *node)
struct FunctionScanPerFuncState FunctionScanPerFuncState
void ExecReScanFunctionScan(FunctionScanState *node)
void ExecEndFunctionScan(FunctionScanState *node)
static bool FunctionRecheck(FunctionScanState *node, TupleTableSlot *slot)
#define castNode(_type_, nodeptr)
static int list_length(const List *l)
#define Int64GetDatumFast(X)
#define ScanDirectionIsForward(direction)
ScanDirection es_direction
TupleTableSlot * func_slot
struct FunctionScanPerFuncState * funcstates
ExprContext * ps_ExprContext
TupleTableSlot * ps_ResultTupleSlot
ExecProcNodeMtd ExecProcNode
TupleTableSlot * ss_ScanTupleSlot
TupleDesc CreateTemplateTupleDesc(int natts)
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
void TupleDescCopyEntry(TupleDesc dst, AttrNumber dstAttno, TupleDesc src, AttrNumber srcAttno)
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
void tuplestore_rescan(Tuplestorestate *state)
void tuplestore_end(Tuplestorestate *state)
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
static void slot_getallattrs(TupleTableSlot *slot)