Skip to main content

uqa_execution/
scope_overlay.rs

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