Skip to main content

uqa_execution/
row_stream.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Owned row production with an explicit, fallible cleanup boundary.
8
9use uqa_sql::SQLError;
10
11/// A row producer whose resources require fallible cleanup. A successful
12/// construction transfers its resources to [`SQLRowStream`]. `close` must
13/// release them even when it reports an error; it is invoked at most once.
14pub trait SQLRowSource<T>: Send {
15    fn next_row(&mut self) -> Result<Option<T>, SQLError>;
16    fn close(&mut self) -> Result<(), SQLError>;
17}
18
19/// A fused row stream that closes its producer on EOF, failure or explicit
20/// early termination. A cleanup failure is a query error, never EOF. Dropping
21/// an abandoned stream is best-effort cleanup; execution must call `close`
22/// while it can still report an error to its consumer.
23pub struct SQLRowStream<'a, T> {
24    source: Option<Box<dyn SQLRowSource<T> + 'a>>,
25}
26
27impl<'a, T: 'a> SQLRowStream<'a, T> {
28    /// Adapt an ordinary iterator with infallible resource release. Sources
29    /// with fallible cleanup must use `from_source` instead.
30    pub fn new(rows: impl Iterator<Item = Result<T, SQLError>> + Send + 'a) -> Self {
31        Self::from_source(IteratorSource(rows))
32    }
33
34    pub fn from_source(source: impl SQLRowSource<T> + 'a) -> Self {
35        Self {
36            source: Some(Box::new(source)),
37        }
38    }
39
40    /// Transform rows without losing the producer's cleanup contract.
41    pub fn map_rows<U: 'a>(
42        self,
43        map: impl FnMut(T) -> Result<U, SQLError> + Send + 'a,
44    ) -> SQLRowStream<'a, U> {
45        SQLRowStream::from_source(MappedRows { rows: self, map })
46    }
47}
48
49impl<T> SQLRowStream<'_, T> {
50    /// Consume the producer before invoking cleanup, including when it fails.
51    /// Repeated close calls succeed without invoking the producer again.
52    pub fn close(&mut self) -> Result<(), SQLError> {
53        self.source
54            .take()
55            .map_or(Ok(()), |mut source| source.close())
56    }
57
58    pub(crate) fn fail(&mut self, error: SQLError) -> SQLError {
59        match self.close() {
60            Ok(()) => error,
61            Err(cleanup) => error.with_cleanup(cleanup, "close row stream"),
62        }
63    }
64}
65
66impl<T> Iterator for SQLRowStream<'_, T> {
67    type Item = Result<T, SQLError>;
68
69    fn next(&mut self) -> Option<Self::Item> {
70        match self.source.as_mut()?.next_row() {
71            Ok(Some(row)) => Some(Ok(row)),
72            Ok(None) => self.close().err().map(Err),
73            Err(error) => Some(Err(self.fail(error))),
74        }
75    }
76}
77
78impl<T> std::iter::FusedIterator for SQLRowStream<'_, T> {}
79
80impl<T> Drop for SQLRowStream<'_, T> {
81    fn drop(&mut self) {
82        let _ = self.close();
83    }
84}
85
86struct IteratorSource<I>(I);
87
88impl<T, I: Iterator<Item = Result<T, SQLError>> + Send> SQLRowSource<T> for IteratorSource<I> {
89    fn next_row(&mut self) -> Result<Option<T>, SQLError> {
90        self.0.next().transpose()
91    }
92
93    fn close(&mut self) -> Result<(), SQLError> {
94        Ok(())
95    }
96}
97
98struct MappedRows<'a, T, F> {
99    rows: SQLRowStream<'a, T>,
100    map: F,
101}
102
103impl<T, U, F: FnMut(T) -> Result<U, SQLError> + Send> SQLRowSource<U> for MappedRows<'_, T, F> {
104    fn next_row(&mut self) -> Result<Option<U>, SQLError> {
105        self.rows.next().transpose()?.map(&mut self.map).transpose()
106    }
107
108    fn close(&mut self) -> Result<(), SQLError> {
109        self.rows.close()
110    }
111}
112
113#[cfg(test)]
114mod tests;