Skip to main content

uqa_sql/semantics/
join_using.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Schema binding and positional output shaping for `PostgreSQL` qualified joins.
8
9use uqa_core::memory::ProductionControl;
10
11mod production;
12pub use production::{
13    join_using_column_names_with_control, join_using_predicate_owned,
14    resolve_join_using_with_control,
15};
16
17use crate::ast::{ColumnType, JoinKind, JoinUsing};
18use crate::schema::join_output::JoinOutputSource;
19use crate::SQLError;
20use crate::{ColumnIdentity, RowSchema, ScalarExpr};
21
22#[derive(Debug, Clone)]
23pub struct ResolvedJoinUsing {
24    columns: Vec<ResolvedJoinColumn>,
25    alias: Option<String>,
26}
27
28pub type JoinUsingLayout = (
29    Vec<(String, ColumnIdentity, JoinOutputSource)>,
30    Vec<(ColumnIdentity, JoinOutputSource)>,
31);
32
33#[derive(Debug, Clone)]
34struct ResolvedJoinColumn {
35    name: String,
36    left: usize,
37    right: usize,
38    comparison_type: Option<ColumnType>,
39    output_type: Option<ColumnType>,
40}
41
42fn missing_using_column(column: &str, side: &str) -> SQLError {
43    SQLError::Routine {
44        sqlstate: "42703".into(),
45        message: format!(
46            "column \"{column}\" specified in USING clause does not exist in {side} table"
47        ),
48    }
49}
50
51fn ambiguous_using_column(column: &str, side: &str) -> SQLError {
52    SQLError::Routine {
53        sqlstate: "42702".into(),
54        message: format!("common column name \"{column}\" appears more than once in {side} table"),
55    }
56}
57
58pub fn resolve_join_using(
59    explicit: Option<&JoinUsing>,
60    natural: bool,
61    left: &RowSchema,
62    right: &RowSchema,
63) -> Result<Option<ResolvedJoinUsing>, SQLError> {
64    resolve_join_using_with_control(
65        explicit,
66        natural,
67        left,
68        right,
69        &ProductionControl::uncontrolled(),
70    )
71    .map(|using| {
72        using.map(|using| {
73            using
74                .into_uncontrolled()
75                .expect("ordinary USING resolution has no reservation")
76        })
77    })
78}
79
80impl ResolvedJoinUsing {
81    /// Borrow the physical inputs consumed by the USING equality predicates without constructing their scalar trees. Logical positions and NULL slots resolve through the original child layouts, with cancellation checked even when a pair contributes no physical input.
82    pub fn visit_input_slots(
83        &self,
84        left: &RowSchema,
85        right: &RowSchema,
86        control: &ProductionControl<'_>,
87        visitor: &mut impl FnMut(usize) -> Result<(), SQLError>,
88    ) -> Result<(), SQLError> {
89        control.check()?;
90        for column in &self.columns {
91            for slot in [
92                left.slot(column.left),
93                right
94                    .slot(column.right)
95                    .map(|slot| left.physical_width() + slot),
96            ] {
97                control.check()?;
98                if let Some(slot) = slot {
99                    visitor(slot)?;
100                }
101            }
102        }
103        Ok(())
104    }
105}
106
107pub fn join_using_predicate(
108    using: &ResolvedJoinUsing,
109    left: &RowSchema,
110    right: &RowSchema,
111) -> Option<ScalarExpr> {
112    let control = ProductionControl::uncontrolled();
113    join_using_predicate_owned(using, left, right, &control)
114        .expect("ordinary USING predicate")
115        .map(|predicate| {
116            predicate
117                .finish(&control)
118                .expect("ordinary USING scalar")
119                .into_uncontrolled()
120                .expect("ordinary USING scalar has no reservation")
121        })
122}
123
124/// Bind the visible and hidden output identities of a qualified join without
125/// constructing or executing the join. Static source-schema binding and the
126/// physical operator share this layout so an empty or correlated right side
127/// cannot lose its declared types.
128pub fn join_using_output_schema(
129    kind: JoinKind,
130    left: &RowSchema,
131    right: &RowSchema,
132    using: &ResolvedJoinUsing,
133) -> Result<RowSchema, SQLError> {
134    join_using_output_schema_with_control(
135        kind,
136        left,
137        right,
138        using,
139        &ProductionControl::uncontrolled(),
140    )
141}
142
143/// Add a parenthesized JOIN alias to the input-side schemas for null-rejection analysis. Merged FULL JOIN columns belong to neither side exclusively because their value is a coalesce of both inputs.
144pub fn join_alias_input_schemas(
145    kind: JoinKind,
146    left: &RowSchema,
147    right: &RowSchema,
148    using: Option<&ResolvedJoinUsing>,
149    alias: &str,
150    column_aliases: &[String],
151) -> Result<(RowSchema, RowSchema), SQLError> {
152    join_alias_input_schemas_with_control(
153        kind,
154        left,
155        right,
156        using,
157        alias,
158        column_aliases,
159        &ProductionControl::uncontrolled(),
160    )
161}
162
163mod input_aliases;
164pub use input_aliases::join_alias_input_schemas_with_control;
165
166pub fn join_using_layout(
167    kind: JoinKind,
168    left: &RowSchema,
169    right: &RowSchema,
170    using: &ResolvedJoinUsing,
171) -> Result<JoinUsingLayout, SQLError> {
172    Ok(join_using_layout_with_control(
173        kind,
174        left,
175        right,
176        using,
177        &ProductionControl::uncontrolled(),
178    )?
179    .into_uncontrolled()
180    .expect("ordinary JOIN output has no reservation"))
181}
182
183mod output;
184pub use output::{join_using_layout_with_control, join_using_output_schema_with_control};
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    struct Types;
191    impl crate::FunctionTypeResolver for Types {
192        fn resolve_function_type(
193            &self,
194            _: &str,
195            _: Option<&crate::ast::FunctionBinding>,
196            _: &[Option<String>],
197            _: &[Option<ColumnType>],
198            _: bool,
199        ) -> Result<Option<ColumnType>, SQLError> {
200            Ok(None)
201        }
202    }
203    impl crate::routines::RoutineResolution for Types {}
204
205    #[test]
206    fn natural_columns_follow_left_input_order() {
207        let left = RowSchema::with_qualified_types(
208            "l",
209            vec!["b".into(), "a".into(), "only".into()],
210            vec![None; 3],
211        );
212        let right = RowSchema::with_qualified_types(
213            "r",
214            vec!["a".into(), "b".into(), "other".into()],
215            vec![None; 3],
216        );
217        let resolved = resolve_join_using(None, true, &left, &right)
218            .unwrap()
219            .unwrap();
220        assert_eq!(
221            resolved
222                .columns
223                .iter()
224                .map(|column| column.name.as_str())
225                .collect::<Vec<_>>(),
226            ["b", "a"]
227        );
228    }
229
230    #[test]
231    fn nested_using_predicate_preserves_resolved_input_positions() {
232        let base = |alias: &str| {
233            RowSchema::with_qualified_types(
234                alias,
235                vec!["payload".into(), "id".into()],
236                vec![Some(ColumnType::Text), Some(ColumnType::Integer)],
237            )
238        };
239        let using = JoinUsing {
240            columns: vec!["id".into()],
241            alias: None,
242        };
243        let nested = |a: &str, b: &str, kind| {
244            let (a, b) = (base(a), base(b));
245            let resolved = resolve_join_using(Some(&using), false, &a, &b)
246                .unwrap()
247                .unwrap();
248            join_using_output_schema(kind, &a, &b, &resolved).unwrap()
249        };
250        for kind in [
251            JoinKind::Inner,
252            JoinKind::Left,
253            JoinKind::Right,
254            JoinKind::Full,
255        ] {
256            let left = nested("a", "b", kind);
257            let right = nested("c", "d", kind);
258            let resolved = resolve_join_using(Some(&using), false, &left, &right)
259                .unwrap()
260                .unwrap();
261            let predicate = join_using_predicate(&resolved, &left, &right).unwrap();
262            let joined = RowSchema::join(&left, &right, []);
263            let mut slots = Vec::new();
264            resolved
265                .visit_input_slots(
266                    &left,
267                    &right,
268                    &ProductionControl::uncontrolled(),
269                    &mut |slot| {
270                        slots.push(slot);
271                        Ok(())
272                    },
273                )
274                .unwrap();
275            assert_eq!(
276                slots,
277                [
278                    left.physical_slot(0).unwrap(),
279                    left.physical_width() + right.physical_slot(0).unwrap(),
280                ]
281            );
282            let crate::plan::UnifiedPlan::Query(query) =
283                crate::plan::UnifiedPlan::lower(crate::compile("SELECT 1").unwrap().remove(0))
284            else {
285                panic!("query")
286            };
287            let crate::plan::RelationalPlan::QueryBlock(mut block) = query.root else {
288                panic!("block")
289            };
290            block.r#where = Some(predicate);
291            crate::binding::validate_query_block_references(
292                &Types,
293                &block,
294                &joined,
295                &[],
296                &crate::binding::fixture::empty_binding_context(),
297                None,
298            )
299            .unwrap();
300            assert_ne!(
301                left.physical_slot(0),
302                Some(0),
303                "logical positions must not be physical offsets"
304            );
305        }
306    }
307
308    #[test]
309    fn using_requires_one_column_on_each_side() {
310        let left = RowSchema::with_identities(
311            vec!["id".into(), "id".into()],
312            vec![
313                ColumnIdentity::qualified("l", "id"),
314                ColumnIdentity::qualified("other", "id"),
315            ],
316            vec![None; 2],
317        );
318        let right = RowSchema::with_qualified_types("r", vec!["id".into()], vec![None]);
319        let error = resolve_join_using(
320            Some(&JoinUsing {
321                columns: vec!["id".into()],
322                alias: None,
323            }),
324            false,
325            &left,
326            &right,
327        )
328        .unwrap_err();
329        assert_eq!(error.sqlstate(), Some("42702"));
330    }
331}