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::{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 crate::SQLRowSource<PhysicalRow> for DeferredTableFunctionRows<'_> {
30    fn next_row(&mut self) -> Result<Option<PhysicalRow>, SQLError> {
31        if let Some(start) = self.start.take() {
32            match start() {
33                Ok(rows) => self.rows = Some(rows),
34                Err(error) => return Err(error),
35            }
36        }
37        self.rows
38            .as_mut()
39            .map_or(Ok(None), |rows| rows.next().transpose())
40    }
41
42    fn close(&mut self) -> Result<(), SQLError> {
43        self.start = None;
44        self.rows.take().map_or(Ok(()), |mut rows| rows.close())
45    }
46}
47
48#[cfg(test)]
49mod tests;