Skip to main content

uqa_sql/schema/production/composition/
join.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::{
8    identity_types, inline, optional_text, optional_type, records, scores, shifted, ColumnIdentity,
9    Layout, ProductionControl, RowSchema, SQLError, SchemaBuildMetadata, SchemaMap, SchemaMemory,
10    SchemaSet, NULL_SLOT,
11};
12
13impl RowSchema {
14    /// Compose both physical layouts while retaining each selected namespace and metadata owner.
15    pub fn join_with_control(
16        left: &Self,
17        right: &Self,
18        extra_columns: impl IntoIterator<Item = String>,
19        control: &ProductionControl<'_>,
20    ) -> Result<Self, SQLError> {
21        Self::join_column_inputs_with_control(left, right, extra_columns, control)
22    }
23
24    /// Borrow compatibility NULL-extension names without constructing an intermediate name buffer.
25    pub fn join_borrowed_columns_with_control<'a>(
26        left: &Self,
27        right: &Self,
28        extra_columns: impl IntoIterator<Item = &'a str>,
29        control: &ProductionControl<'_>,
30    ) -> Result<Self, SQLError> {
31        Self::join_column_inputs_with_control(left, right, extra_columns, control)
32    }
33
34    fn join_column_inputs_with_control(
35        left: &Self,
36        right: &Self,
37        extra_columns: impl IntoIterator<Item = impl AsRef<str>>,
38        control: &ProductionControl<'_>,
39    ) -> Result<Self, SQLError> {
40        control.check()?;
41        let mut layout = Layout::new(control);
42        layout.append(left, 0, None, control)?;
43        layout.append(right, left.physical_width(), None, control)?;
44        for name in extra_columns {
45            control.check()?;
46            let name = name.as_ref();
47            if !layout.columns.iter().any(|column| column == name) {
48                layout.columns.push_produced(control.copy_text(name)?)?;
49                layout
50                    .identities
51                    .push_produced(ColumnIdentity::from_parts_with_control(
52                        None, name, control,
53                    )?)?;
54                layout.types.push_produced(inline(None, control)?)?;
55                layout.slots.push_copy(NULL_SLOT)?;
56            }
57        }
58        for column in right.index.executor_attributes.keys() {
59            control.check()?;
60            assert!(
61                !left.index.executor_attributes.contains_key(column),
62                "duplicate internal relation attribute in joined row"
63            );
64        }
65        for column in right.index.cold.executor_attribute_types.keys() {
66            control.check()?;
67            assert!(
68                !left
69                    .index
70                    .cold
71                    .executor_attribute_types
72                    .contains_key(column),
73                "duplicate internal relation attribute type in joined row"
74            );
75        }
76        let metadata = metadata(left, right, control)?;
77        layout.finish(
78            left.physical_width() + right.physical_width(),
79            metadata,
80            control,
81        )
82    }
83}
84
85fn metadata(
86    left: &RowSchema,
87    right: &RowSchema,
88    control: &ProductionControl<'_>,
89) -> Result<SchemaBuildMetadata, SQLError> {
90    let (score_sources, memory) = scores(
91        left.index
92            .cold
93            .score_sources
94            .iter()
95            .chain(&right.index.cold.score_sources),
96        control,
97    )?
98    .into_parts();
99    Ok(SchemaBuildMetadata {
100        collations: crate::schema::Collations::joined_with_control(left, right, control)?,
101        record_fields: records(left, right, control)?,
102        aliases: joined_aliases(left, right, control)?,
103        alias_types: identity_types(
104            left.index
105                .cold
106                .aliases
107                .iter()
108                .filter(|(name, _)| !right.index.cold.aliases.contains_key(*name))
109                .chain(right.index.cold.aliases.iter())
110                .map(|(name, ty)| (name, ty.as_ref())),
111            control,
112        )?,
113        internal: joined_internal_slots(left, right, control)?,
114        internal_types: SchemaMap::from_produced(
115            left.index
116                .cold
117                .executor_attribute_types
118                .iter()
119                .chain(&right.index.cold.executor_attribute_types)
120                .map(|(column, ty)| {
121                    Ok((
122                        inline(*column, control)?,
123                        optional_type(ty.as_ref(), control)?,
124                    ))
125                }),
126            control,
127        )?,
128        score_sources,
129        wildcard_hidden: SchemaSet::from_produced(
130            left.index
131                .cold
132                .wildcard_hidden
133                .iter()
134                .copied()
135                .chain(
136                    right
137                        .index
138                        .cold
139                        .wildcard_hidden
140                        .iter()
141                        .map(|position| left.len() + position),
142                )
143                .map(|position| inline(position, control)),
144            control,
145        )?,
146        binding_only: identity_types(
147            left.index
148                .cold
149                .binding_only
150                .iter()
151                .filter(|(name, _)| !right.index.cold.binding_only.contains_key(*name))
152                .chain(right.index.cold.binding_only.iter())
153                .map(|(name, ty)| (name, ty.as_ref())),
154            control,
155        )?,
156        row_types: crate::schema::relation_types::RelationRowTypes::compose_with_control(
157            left, right, false, control,
158        )?,
159        row_presence: crate::schema::relation_presence::RelationPresence::compose_with_control(
160            left, right, false, control,
161        )?,
162        lateral_restrictions: RowSchema::joined_diagnostic_names_with_control(
163            left, right, control,
164        )?,
165        open_qualifiers: SchemaSet::from_produced(
166            left.index
167                .cold
168                .open_qualifiers
169                .iter()
170                .chain(&right.index.cold.open_qualifiers)
171                .map(|name| optional_text(name.as_deref(), control)),
172            control,
173        )?,
174        memory: SchemaMemory::new(memory),
175        ..SchemaBuildMetadata::empty_with_control(control)
176    })
177}
178
179fn joined_aliases(
180    left: &RowSchema,
181    right: &RowSchema,
182    control: &ProductionControl<'_>,
183) -> Result<SchemaMap<super::ColumnIdentity, usize>, SQLError> {
184    SchemaMap::from_produced(
185        left.index
186            .aliases
187            .iter()
188            .filter(|(name, _)| !right.index.aliases.contains_key(*name))
189            .map(|(name, slot)| (name, *slot))
190            .chain(
191                right
192                    .index
193                    .aliases
194                    .iter()
195                    .map(|(name, slot)| (name, shifted(*slot, left.physical_width()))),
196            )
197            .map(|(name, slot)| Ok((name.clone_with_control(control)?, inline(slot, control)?))),
198        control,
199    )
200}
201
202fn joined_internal_slots(
203    left: &RowSchema,
204    right: &RowSchema,
205    control: &ProductionControl<'_>,
206) -> Result<SchemaMap<crate::ast::InternalColumnRef, usize>, SQLError> {
207    SchemaMap::from_produced(
208        left.index
209            .executor_attributes
210            .iter()
211            .map(|(column, slot)| (*column, *slot))
212            .chain(
213                right
214                    .index
215                    .executor_attributes
216                    .iter()
217                    .map(|(column, slot)| (*column, shifted(*slot, left.physical_width()))),
218            )
219            .map(|(column, slot)| Ok((inline(column, control)?, inline(slot, control)?))),
220        control,
221    )
222}