Skip to main content

uqa_execution/query/table_functions/
deferred.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Table-function rows whose call starts at the first row request, as `PostgreSQL`'s function scan evaluates its call only when it is first asked for a row.
8
9use crate::{ExecResult, PhysicalProjectRows, PhysicalRow};
10use uqa_sql::SQLError;
11
12type StartCall<'a> = Box<dyn FnOnce() -> Result<PhysicalProjectRows, SQLError> + Send + 'a>;
13
14/// The rows of a table-function call that has not started yet. The first row request evaluates the call's arguments and starts its stream; a consumer that requests no row never evaluates the call.
15pub struct DeferredTableFunctionRows<'a> {
16    start: Option<StartCall<'a>>,
17    rows: Option<PhysicalProjectRows>,
18}
19
20impl<'a> DeferredTableFunctionRows<'a> {
21    pub fn new(start: impl FnOnce() -> Result<PhysicalProjectRows, SQLError> + Send + 'a) -> Self {
22        Self {
23            start: Some(Box::new(start)),
24            rows: None,
25        }
26    }
27}
28
29impl Iterator for DeferredTableFunctionRows<'_> {
30    type Item = ExecResult<PhysicalRow>;
31
32    fn next(&mut self) -> Option<Self::Item> {
33        if let Some(start) = self.start.take() {
34            match start() {
35                Ok(rows) => self.rows = Some(rows),
36                Err(error) => return Some(Err(error.into())),
37            }
38        }
39        self.rows.as_mut()?.next()
40    }
41}
42
43#[cfg(test)]
44mod tests;