use uqa_sql::SQLError;
pub trait SQLRowSource<T>: Send {
fn next_row(&mut self) -> Result<Option<T>, SQLError>;
fn close(&mut self) -> Result<(), SQLError>;
}
pub struct SQLRowStream<'a, T> {
source: Option<Box<dyn SQLRowSource<T> + 'a>>,
}
impl<'a, T: 'a> SQLRowStream<'a, T> {
pub fn new(rows: impl Iterator<Item = Result<T, SQLError>> + Send + 'a) -> Self {
Self::from_source(IteratorSource(rows))
}
pub fn from_source(source: impl SQLRowSource<T> + 'a) -> Self {
Self {
source: Some(Box::new(source)),
}
}
pub fn map_rows<U: 'a>(
self,
map: impl FnMut(T) -> Result<U, SQLError> + Send + 'a,
) -> SQLRowStream<'a, U> {
SQLRowStream::from_source(MappedRows { rows: self, map })
}
}
impl<T> SQLRowStream<'_, T> {
pub fn close(&mut self) -> Result<(), SQLError> {
self.source
.take()
.map_or(Ok(()), |mut source| source.close())
}
pub(crate) fn fail(&mut self, error: SQLError) -> SQLError {
match self.close() {
Ok(()) => error,
Err(cleanup) => error.with_cleanup(cleanup, "close row stream"),
}
}
}
impl<T> Iterator for SQLRowStream<'_, T> {
type Item = Result<T, SQLError>;
fn next(&mut self) -> Option<Self::Item> {
match self.source.as_mut()?.next_row() {
Ok(Some(row)) => Some(Ok(row)),
Ok(None) => self.close().err().map(Err),
Err(error) => Some(Err(self.fail(error))),
}
}
}
impl<T> std::iter::FusedIterator for SQLRowStream<'_, T> {}
impl<T> Drop for SQLRowStream<'_, T> {
fn drop(&mut self) {
let _ = self.close();
}
}
struct IteratorSource<I>(I);
impl<T, I: Iterator<Item = Result<T, SQLError>> + Send> SQLRowSource<T> for IteratorSource<I> {
fn next_row(&mut self) -> Result<Option<T>, SQLError> {
self.0.next().transpose()
}
fn close(&mut self) -> Result<(), SQLError> {
Ok(())
}
}
struct MappedRows<'a, T, F> {
rows: SQLRowStream<'a, T>,
map: F,
}
impl<T, U, F: FnMut(T) -> Result<U, SQLError> + Send> SQLRowSource<U> for MappedRows<'_, T, F> {
fn next_row(&mut self) -> Result<Option<U>, SQLError> {
self.rows.next().transpose()?.map(&mut self.map).transpose()
}
fn close(&mut self) -> Result<(), SQLError> {
self.rows.close()
}
}
#[cfg(test)]
mod tests;