Skip to main content

uqa_execution/
join_output.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Positional output shaping for `JOIN ... USING` and `NATURAL JOIN`.
8
9use crate::RowSchemaExecution;
10use uqa_core::Value;
11use uqa_sql::expr::cast_value;
12
13use crate::{Batch, ColumnIdentity, ExecError, ExecResult, PhysicalOperator, RowSchema};
14
15pub use uqa_sql::schema::join_output::JoinOutputSource;
16
17/// Reorder and merge join columns while retaining the joined physical row.
18/// Inner, left, and right joins are schema-only remaps; a full join appends
19/// only the merged values that cannot be represented by one existing slot.
20pub struct JoinOutput<'a> {
21    child: Box<dyn PhysicalOperator + 'a>,
22    schema: RowSchema,
23    computed: Vec<JoinOutputSource>,
24}
25
26impl<'a> JoinOutput<'a> {
27    /// Compile the positional schema of a qualified join without constructing or executing an operator. Binders use this to expose the exact same merged-column identities and hidden qualified aliases as execution.
28    pub fn try_schema(
29        input: &RowSchema,
30        columns: &[(String, ColumnIdentity, JoinOutputSource)],
31        aliases: &[(ColumnIdentity, JoinOutputSource)],
32    ) -> ExecResult<RowSchema> {
33        compile_layout(input, columns, aliases)
34            .map(|(schema, _)| schema)
35            .map_err(Into::into)
36    }
37
38    pub fn try_new(
39        child: Box<dyn PhysicalOperator + 'a>,
40        columns: Vec<(String, ColumnIdentity, JoinOutputSource)>,
41        aliases: Vec<(ColumnIdentity, JoinOutputSource)>,
42    ) -> ExecResult<Self> {
43        let (schema, computed) = compile_layout(child.row_schema(), &columns, &aliases)?;
44        Ok(Self {
45            child,
46            schema,
47            computed,
48        })
49    }
50}
51
52pub use uqa_sql::schema::join_output::compile_layout;
53
54impl PhysicalOperator for JoinOutput<'_> {
55    fn row_schema(&self) -> &RowSchema {
56        &self.schema
57    }
58
59    fn estimated_cardinality(&self) -> Option<u64> {
60        self.child.estimated_cardinality()
61    }
62
63    fn open(&mut self) -> ExecResult<()> {
64        self.child.open()
65    }
66
67    fn next(&mut self) -> ExecResult<Option<Batch>> {
68        let Some(batch) = self.child.next()? else {
69            return Ok(None);
70        };
71        if self.computed.is_empty() {
72            return Ok(Some(Batch::from_physical_rows(
73                self.schema.clone(),
74                batch.rows,
75            )));
76        }
77        let rows = batch
78            .rows
79            .into_iter()
80            .map(|row| {
81                let values = {
82                    let view = batch.schema.view(&row);
83                    self.computed
84                        .iter()
85                        .map(|source| evaluate_source(source, &view))
86                        .collect::<ExecResult<Vec<_>>>()?
87                };
88                Ok(row.append_values(values))
89            })
90            .collect::<ExecResult<Vec<_>>>()?;
91        Ok(Some(Batch::from_physical_rows(self.schema.clone(), rows)))
92    }
93
94    fn close(&mut self) -> ExecResult<()> {
95        self.child.close()
96    }
97}
98
99pub use uqa_sql::schema::join_output::source_type;
100
101fn evaluate_source(
102    source: &JoinOutputSource,
103    view: &crate::PhysicalRowView<'_>,
104) -> ExecResult<Value> {
105    match source {
106        JoinOutputSource::Input(position) => {
107            Ok(view.value_at(*position).unwrap_or(&Value::Null).clone())
108        }
109        JoinOutputSource::Cast { input, ty } => cast_value(
110            view.value_at(*input).unwrap_or(&Value::Null),
111            &ty.sql_name(),
112        )
113        .map_err(ExecError::from),
114        JoinOutputSource::Coalesce { left, right, ty } => {
115            let target = ty.sql_name();
116            let left = cast_value(view.value_at(*left).unwrap_or(&Value::Null), &target)?;
117            if !matches!(left, Value::Null) {
118                return Ok(left);
119            }
120            cast_value(view.value_at(*right).unwrap_or(&Value::Null), &target)
121                .map_err(ExecError::from)
122        }
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use crate::RowSchemaExecution;
129    use std::collections::BTreeMap;
130    use uqa_sql::ast::ColumnType;
131
132    use super::*;
133    use crate::physical::run_to_rows;
134    use crate::TableScan;
135    use uqa_sql::expr::RowLookup;
136
137    #[test]
138    fn schema_only_merge_reuses_input_slots_and_keeps_qualified_aliases() {
139        let child = TableScan::from_rows(
140            vec![
141                "l.id".into(),
142                "l.name".into(),
143                "r.id".into(),
144                "r.note".into(),
145            ],
146            vec![BTreeMap::from([
147                ("l.id".into(), Value::Int(1)),
148                ("l.name".into(), Value::Str("left".into())),
149                ("r.id".into(), Value::Int(1)),
150                ("r.note".into(), Value::Str("right".into())),
151            ])],
152        );
153        let mut output = JoinOutput::try_new(
154            Box::new(child),
155            vec![
156                (
157                    "id".into(),
158                    ColumnIdentity::unqualified("id"),
159                    JoinOutputSource::Input(0),
160                ),
161                (
162                    "name".into(),
163                    ColumnIdentity::qualified("l", "name"),
164                    JoinOutputSource::Input(1),
165                ),
166                (
167                    "note".into(),
168                    ColumnIdentity::qualified("r", "note"),
169                    JoinOutputSource::Input(3),
170                ),
171            ],
172            vec![
173                (
174                    ColumnIdentity::qualified("l", "id"),
175                    JoinOutputSource::Input(0),
176                ),
177                (
178                    ColumnIdentity::qualified("r", "id"),
179                    JoinOutputSource::Input(2),
180                ),
181            ],
182        )
183        .unwrap();
184        output.open().unwrap();
185        let batch = output.next().unwrap().unwrap();
186        assert_eq!(batch.schema.columns(), ["id", "name", "note"]);
187        let view = batch.schema.view(&batch.rows[0]);
188        assert_eq!(view.qualified_column("l", "id"), Some(&Value::Int(1)));
189        assert_eq!(view.qualified_column("r", "id"), Some(&Value::Int(1)));
190        output.close().unwrap();
191    }
192
193    #[test]
194    fn full_merge_coalesces_only_the_requested_column() {
195        let child = TableScan::from_rows(
196            vec!["l.id".into(), "r.id".into()],
197            vec![BTreeMap::from([
198                ("l.id".into(), Value::Null),
199                ("r.id".into(), Value::Int(3)),
200            ])],
201        );
202        let mut output = JoinOutput::try_new(
203            Box::new(child),
204            vec![(
205                "id".into(),
206                ColumnIdentity::unqualified("id"),
207                JoinOutputSource::Coalesce {
208                    left: 0,
209                    right: 1,
210                    ty: ColumnType::Integer,
211                },
212            )],
213            Vec::new(),
214        )
215        .unwrap();
216        let (_, rows) = run_to_rows(&mut output).unwrap();
217        assert_eq!(rows[0]["id"], Value::Int(3));
218    }
219}