uqa_execution/
row_stream.rs1use uqa_sql::SQLError;
10
11pub trait SQLRowSource<T>: Send {
15 fn next_row(&mut self) -> Result<Option<T>, SQLError>;
16 fn close(&mut self) -> Result<(), SQLError>;
17}
18
19pub struct SQLRowStream<'a, T> {
24 source: Option<Box<dyn SQLRowSource<T> + 'a>>,
25}
26
27impl<'a, T: 'a> SQLRowStream<'a, T> {
28 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 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 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;