Skip to main content

uqa_execution/
map_rows.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Streaming whole-row mapping adapter.
8
9use crate::RowSchemaExecution;
10use std::sync::Arc;
11
12use uqa_sql::ResultRow;
13
14use crate::{Batch, ExecResult, PhysicalOperator, RowSchema};
15
16pub type SharedRowMapper<'a> = Arc<dyn Fn(ResultRow) -> ExecResult<ResultRow> + Send + Sync + 'a>;
17
18/// Apply a fallible mapping to each input row without changing batch
19/// backpressure or collecting the child relation.
20pub struct MapRows<'a> {
21    child: Box<dyn PhysicalOperator + 'a>,
22    input_pending: crate::physical::demand::PendingRows,
23    mapper: SharedRowMapper<'a>,
24    schema: RowSchema,
25}
26
27impl<'a> MapRows<'a> {
28    pub fn new(
29        child: Box<dyn PhysicalOperator + 'a>,
30        schema: Vec<String>,
31        mapper: SharedRowMapper<'a>,
32    ) -> Self {
33        Self {
34            child,
35            input_pending: crate::physical::demand::PendingRows::default(),
36            mapper,
37            schema: RowSchema::new(schema),
38        }
39    }
40}
41
42impl MapRows<'_> {
43    fn pull(&mut self, demand: Option<std::num::NonZeroUsize>) -> ExecResult<Option<Batch>> {
44        let Some(batch) = self.input_pending.pull(self.child.as_mut(), demand)? else {
45            return Ok(None);
46        };
47        let rows = batch
48            .rows
49            .iter()
50            .map(|row| (self.mapper)(batch.schema.view(row).to_result_row()))
51            .collect::<ExecResult<Vec<_>>>()?;
52        Ok(Some(Batch::new(self.schema.clone(), rows)))
53    }
54}
55
56impl PhysicalOperator for MapRows<'_> {
57    fn row_schema(&self) -> &RowSchema {
58        &self.schema
59    }
60
61    fn estimated_cardinality(&self) -> Option<u64> {
62        self.child.estimated_cardinality()
63    }
64
65    fn open(&mut self) -> ExecResult<()> {
66        self.input_pending.clear();
67        self.child.open()
68    }
69
70    fn next(&mut self) -> ExecResult<Option<Batch>> {
71        self.pull(None)
72    }
73
74    fn next_with_demand(&mut self, rows: std::num::NonZeroUsize) -> ExecResult<Option<Batch>> {
75        self.pull(Some(rows))
76    }
77
78    fn close(&mut self) -> ExecResult<()> {
79        self.input_pending.clear();
80        self.child.close()
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use std::collections::BTreeMap;
87
88    use uqa_core::Value;
89
90    use super::*;
91    use crate::{physical::run_to_rows, ExecError, TableScan};
92
93    #[test]
94    fn mapper_preserves_late_errors() {
95        let rows = vec![
96            BTreeMap::from([("v".into(), Value::Int(1))]),
97            BTreeMap::from([("v".into(), Value::Int(2))]),
98        ];
99        let child = Box::new(TableScan::from_rows(vec!["v".into()], rows));
100        let mapper = Arc::new(|row: ResultRow| {
101            if row.get("v") == Some(&Value::Int(2)) {
102                Err(ExecError::Other("map failed".into()))
103            } else {
104                Ok(row)
105            }
106        });
107        let mut operator = MapRows::new(child, vec!["v".into()], mapper);
108        let error = run_to_rows(&mut operator).unwrap_err();
109        assert!(error.to_string().contains("map failed"));
110    }
111}