1use crate::{Batch, ExecResult, OwnedPhysicalRow, PhysicalOperator, PhysicalRow, RowSchema};
10
11pub struct ScopeOverlay<'a> {
13 child: Box<dyn PhysicalOperator + 'a>,
14 schema: RowSchema,
15 outer: PhysicalRow,
16}
17
18impl<'a> ScopeOverlay<'a> {
19 pub fn new(child: Box<dyn PhysicalOperator + 'a>, outer: OwnedPhysicalRow) -> Self {
21 let schema = RowSchema::with_outer_schema(child.row_schema(), &outer.schema);
22 Self {
23 child,
24 schema,
25 outer: outer.row,
26 }
27 }
28}
29
30impl PhysicalOperator for ScopeOverlay<'_> {
31 fn row_schema(&self) -> &RowSchema {
32 &self.schema
33 }
34
35 fn estimated_cardinality(&self) -> Option<u64> {
36 self.child.estimated_cardinality()
37 }
38
39 fn open(&mut self) -> ExecResult<()> {
40 self.child.open()
41 }
42
43 fn next(&mut self) -> ExecResult<Option<Batch>> {
44 let Some(batch) = self.child.next()? else {
45 return Ok(None);
46 };
47 let rows = batch
48 .rows
49 .into_iter()
50 .map(|row| PhysicalRow::concat_left_owned(row, &self.outer))
51 .collect();
52 Ok(Some(Batch::from_physical_rows(self.schema.clone(), rows)))
53 }
54
55 fn close(&mut self) -> ExecResult<()> {
56 self.child.close()
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use crate::RowSchemaExecution;
63 use uqa_core::Value;
64 use uqa_sql::expr::RowLookup;
65
66 use super::*;
67 use crate::{ColumnIdentity, ColumnSelection, TableScan};
68
69 fn one_row(qualifier: &str, columns: &[&str], values: &[i64]) -> Box<dyn PhysicalOperator> {
70 let row = columns
71 .iter()
72 .zip(values)
73 .map(|(column, value)| ((*column).to_string(), Value::Int(*value)))
74 .collect();
75 let scan: Box<dyn PhysicalOperator> = Box::new(TableScan::from_rows(
76 columns.iter().map(|column| (*column).to_string()).collect(),
77 vec![row],
78 ));
79 let mapping = columns
80 .iter()
81 .enumerate()
82 .map(|(position, column)| {
83 (
84 (*column).to_string(),
85 ColumnIdentity::qualified(qualifier, *column),
86 position,
87 )
88 })
89 .collect();
90 Box::new(ColumnSelection::with_identities(scan, mapping))
91 }
92
93 #[test]
94 fn current_scope_shadows_outer_names_without_exposing_outer_star_columns() {
95 let child = one_row("inner", &["id", "value"], &[1, 2]);
96 let outer_schema = RowSchema::with_qualified_types(
97 "outer",
98 vec!["id".into(), "note".into()],
99 vec![None, None],
100 );
101 let outer = OwnedPhysicalRow::new(
102 outer_schema,
103 PhysicalRow::from_values(vec![Value::Int(9), Value::Int(10)]),
104 );
105 let mut overlay = ScopeOverlay::new(child, outer);
106 overlay.open().unwrap();
107 let batch = overlay.next().unwrap().unwrap();
108 assert_eq!(batch.schema.columns(), ["id", "value"]);
109 let view = batch.schema.view(&batch.rows[0]);
110 assert_eq!(view.column("id"), Some(&Value::Int(1)));
111 assert_eq!(view.column("note"), Some(&Value::Int(10)));
112 assert_eq!(view.qualified_column("outer", "id"), Some(&Value::Int(9)));
113 }
114
115 #[test]
116 fn ambiguous_current_and_outer_names_are_not_resolved_arbitrarily() {
117 let row = [
118 ("left slot".into(), Value::Int(1)),
119 ("right slot".into(), Value::Int(2)),
120 ]
121 .into_iter()
122 .collect();
123 let scan: Box<dyn PhysicalOperator> = Box::new(TableScan::from_rows(
124 vec!["left slot".into(), "right slot".into()],
125 vec![row],
126 ));
127 let child: Box<dyn PhysicalOperator> = Box::new(ColumnSelection::with_identities(
128 scan,
129 vec![
130 ("id".into(), ColumnIdentity::qualified("left", "id"), 0),
131 ("id".into(), ColumnIdentity::qualified("right", "id"), 1),
132 ],
133 ));
134 let outer = OwnedPhysicalRow::new(
135 RowSchema::new(vec!["id".into()]),
136 PhysicalRow::from_values(vec![Value::Int(9)]),
137 );
138 let mut overlay = ScopeOverlay::new(child, outer);
139 overlay.open().unwrap();
140 let batch = overlay.next().unwrap().unwrap();
141 assert!(batch.schema.view(&batch.rows[0]).column_is_ambiguous("id"));
142
143 let child = one_row("inner", &["value"], &[1]);
144 let outer_schema = RowSchema::with_identities(
145 vec!["left slot".into(), "right slot".into()],
146 vec![
147 ColumnIdentity::qualified("left", "id"),
148 ColumnIdentity::qualified("right", "id"),
149 ],
150 vec![None, None],
151 );
152 let outer = OwnedPhysicalRow::new(
153 outer_schema,
154 PhysicalRow::from_values(vec![Value::Int(9), Value::Int(10)]),
155 );
156 let mut overlay = ScopeOverlay::new(child, outer);
157 overlay.open().unwrap();
158 let batch = overlay.next().unwrap().unwrap();
159 assert!(batch.schema.view(&batch.rows[0]).column_is_ambiguous("id"));
160 }
161
162 #[test]
163 fn typed_outer_scope_preserves_declared_sql_identity() {
164 let child = one_row("inner", &["id"], &[1]);
165 let outer_schema = RowSchema::with_qualified_types(
166 "outer",
167 vec!["value".into()],
168 vec![Some(uqa_sql::ast::ColumnType::SmallInteger)],
169 );
170 let outer =
171 OwnedPhysicalRow::new(outer_schema, PhysicalRow::from_values(vec![Value::Int(7)]));
172 let overlay = ScopeOverlay::new(child, outer);
173 assert_eq!(
174 overlay.row_schema().qualified_type("outer", "value"),
175 Some(&uqa_sql::ast::ColumnType::SmallInteger)
176 );
177 assert_eq!(
178 overlay.row_schema().type_of("value"),
179 Some(&uqa_sql::ast::ColumnType::SmallInteger)
180 );
181 }
182
183 #[test]
184 fn outer_scope_preserves_hidden_structured_aliases_without_extra_value_slots() {
185 let child = one_row("inner", &["id"], &[1]);
186 let outer_schema = RowSchema::with_identity_aliases(
187 &RowSchema::new(vec!["payload".into()]),
188 &[(ColumnIdentity::qualified("outer.dot", "column.dot"), 0)],
189 );
190 let outer =
191 OwnedPhysicalRow::new(outer_schema, PhysicalRow::from_values(vec![Value::Int(9)]));
192 let mut overlay = ScopeOverlay::new(child, outer);
193 assert_eq!(overlay.row_schema().physical_width(), 2);
194 overlay.open().unwrap();
195 let batch = overlay.next().unwrap().unwrap();
196 let view = batch.schema.view(&batch.rows[0]);
197 assert_eq!(
198 view.qualified_column("outer.dot", "column.dot"),
199 Some(&Value::Int(9))
200 );
201 assert_eq!(view.qualified_column("outer", "dot.column.dot"), None);
202 }
203
204 #[test]
205 fn outer_scope_preserves_binding_only_qualified_identities() {
206 let child = one_row("inner", &["id"], &[1]);
207 let outer_schema = RowSchema::with_typed_virtual_identities(
208 &RowSchema::with_qualified_types(
209 "target",
210 vec!["id".into()],
211 vec![Some(uqa_sql::ast::ColumnType::Integer)],
212 ),
213 &[(
214 ColumnIdentity::qualified("before", "item_label"),
215 Some(uqa_sql::ast::ColumnType::Text),
216 )],
217 );
218 let outer =
219 OwnedPhysicalRow::new(outer_schema, PhysicalRow::from_values(vec![Value::Int(9)]));
220 let overlay = ScopeOverlay::new(child, outer);
221 assert!(overlay
222 .row_schema()
223 .has_qualified_column("before", "item_label"));
224 assert_eq!(
225 overlay.row_schema().qualified_type("before", "item_label"),
226 Some(&uqa_sql::ast::ColumnType::Text)
227 );
228 assert_eq!(overlay.row_schema().columns(), ["id"]);
229 assert_eq!(overlay.row_schema().physical_width(), 2);
230
231 let child = one_row("before", &["id"], &[1]);
232 let shadowed = ScopeOverlay::new(
233 child,
234 OwnedPhysicalRow::new(
235 RowSchema::with_typed_virtual_identities(
236 &RowSchema::new(Vec::new()),
237 &[(
238 ColumnIdentity::qualified("before", "item_label"),
239 Some(uqa_sql::ast::ColumnType::Text),
240 )],
241 ),
242 PhysicalRow::from_values(Vec::new()),
243 ),
244 );
245 assert!(!shadowed
246 .row_schema()
247 .has_qualified_column("before", "item_label"));
248 }
249}