uqa_execution/
map_rows.rs1use 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
18pub struct MapRows<'a> {
21 child: Box<dyn PhysicalOperator + 'a>,
22 mapper: SharedRowMapper<'a>,
23 schema: RowSchema,
24}
25
26impl<'a> MapRows<'a> {
27 pub fn new(
28 child: Box<dyn PhysicalOperator + 'a>,
29 schema: Vec<String>,
30 mapper: SharedRowMapper<'a>,
31 ) -> Self {
32 Self {
33 child,
34 mapper,
35 schema: RowSchema::new(schema),
36 }
37 }
38}
39
40impl PhysicalOperator for MapRows<'_> {
41 fn row_schema(&self) -> &RowSchema {
42 &self.schema
43 }
44
45 fn estimated_cardinality(&self) -> Option<u64> {
46 self.child.estimated_cardinality()
47 }
48
49 fn open(&mut self) -> ExecResult<()> {
50 self.child.open()
51 }
52
53 fn next(&mut self) -> ExecResult<Option<Batch>> {
54 let Some(batch) = self.child.next()? else {
55 return Ok(None);
56 };
57 let rows = batch
58 .rows
59 .iter()
60 .map(|row| (self.mapper)(batch.schema.view(row).to_result_row()))
61 .collect::<ExecResult<Vec<_>>>()?;
62 Ok(Some(Batch::new(self.schema.clone(), rows)))
63 }
64
65 fn close(&mut self) -> ExecResult<()> {
66 self.child.close()
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use std::collections::BTreeMap;
73
74 use uqa_core::Value;
75
76 use super::*;
77 use crate::{physical::run_to_rows, ExecError, TableScan};
78
79 #[test]
80 fn mapper_preserves_late_errors() {
81 let rows = vec![
82 BTreeMap::from([("v".into(), Value::Int(1))]),
83 BTreeMap::from([("v".into(), Value::Int(2))]),
84 ];
85 let child = Box::new(TableScan::from_rows(vec!["v".into()], rows));
86 let mapper = Arc::new(|row: ResultRow| {
87 if row.get("v") == Some(&Value::Int(2)) {
88 Err(ExecError::Other("map failed".into()))
89 } else {
90 Ok(row)
91 }
92 });
93 let mut operator = MapRows::new(child, vec!["v".into()], mapper);
94 let error = run_to_rows(&mut operator).unwrap_err();
95 assert!(error.to_string().contains("map failed"));
96 }
97}