Skip to main content

uqa_sql/schema/
schema_layout.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Logical-to-physical layout inspection and wildcard expansion.
8
9use super::identity_lookup::ColumnKey;
10use super::{ColumnIdentity, ColumnType, HashSet, RowSchema, NULL_SLOT};
11
12impl RowSchema {
13    /// Compare the complete physical row contract while the original schema retains analysis-only namespaces and record descriptors. A restored row must match this layout before it can reuse the original binding context.
14    pub fn has_same_physical_layout(&self, other: &Self) -> bool {
15        let left = &self.index;
16        let right = &other.index;
17        left.columns == right.columns
18            && left.identities == right.identities
19            && left.slots == right.slots
20            && left.physical_width == right.physical_width
21            && left.aliases == right.aliases
22            && left.executor_attributes == right.executor_attributes
23            && left.cold.columns == right.cold.columns
24            && left.cold.aliases == right.cold.aliases
25            && left.cold.executor_attribute_types == right.cold.executor_attribute_types
26            && left.cold.score_sources == right.cold.score_sources
27            && left.cold.row_presence == right.cold.row_presence
28            && left.cold.wildcard_hidden == right.cold.wildcard_hidden
29            && left
30                .cold
31                .collations
32                .same_physical_bindings(&right.cold.collations)
33    }
34
35    /// Whether one logical source attribute participates in `*` expansion.
36    #[must_use]
37    pub fn wildcard_position_visible(&self, position: usize) -> bool {
38        position < self.len() && !self.index.cold.wildcard_hidden.contains(&position)
39    }
40
41    pub fn columns(&self) -> &[String] {
42        &self.index.columns
43    }
44
45    pub fn len(&self) -> usize {
46        self.index.columns.len()
47    }
48
49    pub fn is_empty(&self) -> bool {
50        self.index.columns.is_empty()
51    }
52
53    pub fn iter(&self) -> std::slice::Iter<'_, String> {
54        self.index.columns.iter()
55    }
56
57    /// Static SQL type at one logical output position.
58    pub fn column_type(&self, logical: usize) -> Option<&ColumnType> {
59        self.index
60            .cold
61            .columns
62            .get(logical)
63            .and_then(Option::as_ref)
64    }
65
66    /// Static SQL types aligned with [`Self::columns`].
67    pub fn column_types(&self) -> &[Option<ColumnType>] {
68        &self.index.cold.columns
69    }
70
71    /// Structured SQL identities aligned with [`Self::columns`].
72    pub fn identities(&self) -> &[ColumnIdentity] {
73        &self.index.identities
74    }
75
76    pub fn identity(&self, logical: usize) -> Option<&ColumnIdentity> {
77        self.index.identities.get(logical)
78    }
79
80    pub fn public_name(&self, logical: usize) -> Option<&str> {
81        self.identity(logical).map(ColumnIdentity::column)
82    }
83
84    pub fn position(&self, name: &str) -> Option<usize> {
85        self.index.exact.get(name).copied()
86    }
87
88    /// Resolve one visible unqualified SQL identity to its logical position. Ambiguous names deliberately do not select an arbitrary owner.
89    pub fn unqualified_position(&self, column: &str) -> Option<usize> {
90        if self.index.ambiguous_unqualified.contains(column) {
91            return None;
92        }
93        self.index.unqualified.get(column).copied()
94    }
95
96    /// Resolve one visible qualified identity to its logical position.
97    pub fn qualified_position(&self, qualifier: &str, column: &str) -> Option<usize> {
98        let identity = ColumnIdentity::qualified(qualifier, column);
99        if self.index.ambiguous_qualified.contains(&identity) {
100            return None;
101        }
102        self.index.qualified.get(&identity).copied()
103    }
104
105    pub fn physical_width(&self) -> usize {
106        self.index.physical_width
107    }
108
109    /// Resolve one logical output position to its flattened physical slot.
110    pub fn physical_slot(&self, logical: usize) -> Option<usize> {
111        self.slot(logical)
112    }
113
114    /// Static type attached to one flattened physical slot, including
115    /// executor-only internal attributes that have no logical SQL position.
116    pub fn physical_type(&self, physical: usize) -> Option<&ColumnType> {
117        self.index
118            .slots
119            .iter()
120            .position(|slot| *slot == physical)
121            .and_then(|logical| self.column_type(logical))
122            .or_else(|| {
123                self.index.aliases.iter().find_map(|(identity, slot)| {
124                    (*slot == physical)
125                        .then(|| {
126                            self.index
127                                .cold
128                                .aliases
129                                .get(identity)
130                                .and_then(Option::as_ref)
131                        })
132                        .flatten()
133                })
134            })
135            .or_else(|| {
136                self.index
137                    .executor_attributes
138                    .iter()
139                    .find_map(|(column, slot)| {
140                        (*slot == physical)
141                            .then(|| {
142                                self.index
143                                    .cold
144                                    .executor_attribute_types
145                                    .get(column)
146                                    .and_then(Option::as_ref)
147                            })
148                            .flatten()
149                    })
150            })
151    }
152
153    /// Resolve a structured SQL identity, including a hidden JOIN USING alias, to its flattened physical slot. Ambiguous identities deliberately return `None` rather than selecting an arbitrary source value.
154    pub fn physical_slot_for_identity(&self, identity: &ColumnIdentity) -> Option<usize> {
155        match identity.qualifier() {
156            Some(qualifier) => self.qualified_slot(qualifier, identity.column()),
157            None => self.column_slot(identity.column()),
158        }
159    }
160
161    pub fn slot(&self, logical: usize) -> Option<usize> {
162        self.index
163            .slots
164            .get(logical)
165            .copied()
166            .filter(|slot| *slot != NULL_SLOT)
167    }
168
169    pub fn exact_slot(&self, name: &str) -> Option<usize> {
170        self.index
171            .exact
172            .get(name)
173            .and_then(|logical| self.slot(*logical))
174            .filter(|slot| *slot != NULL_SLOT)
175    }
176
177    pub(super) fn exact_type(&self, name: &str) -> Option<&ColumnType> {
178        self.index
179            .exact
180            .get(name)
181            .and_then(|logical| self.column_type(*logical))
182    }
183
184    pub fn column_slot(&self, name: &str) -> Option<usize> {
185        if self.index.ambiguous_unqualified.contains(name) {
186            return None;
187        }
188        self.index
189            .unqualified
190            .get(name)
191            .and_then(|logical| self.slot(*logical))
192            .or_else(|| {
193                self.index
194                    .aliases
195                    .get(&(None, name) as &dyn ColumnKey)
196                    .copied()
197            })
198            .filter(|slot| *slot != NULL_SLOT)
199    }
200
201    pub(crate) fn has_qualified_slot_before(&self, qualifier: &str, boundary: usize) -> bool {
202        self.identities()
203            .iter()
204            .enumerate()
205            .any(|(logical, identity)| {
206                identity.qualifier() == Some(qualifier)
207                    && self.slot(logical).unwrap_or(NULL_SLOT) < boundary
208            })
209            || self
210                .index
211                .aliases
212                .iter()
213                .any(|(identity, slot)| identity.qualifier() == Some(qualifier) && *slot < boundary)
214    }
215
216    /// Physical projection layout for `qualifier.*` in relation-column order. Hidden identities introduced by `JOIN ... USING` remain selectable, so each side's wildcard retains its own merged-column value.
217    pub fn qualified_star_layout(
218        &self,
219        qualifier: &str,
220    ) -> Vec<(String, usize, Option<ColumnType>)> {
221        self.qualified_star_position_layout(qualifier)
222            .into_iter()
223            .map(|(column, _, slot, ty)| (column, slot, ty))
224            .collect()
225    }
226
227    /// Bound layout for `qualifier.*`. Visible columns retain their logical positions; hidden aliases such as the suppressed side of `JOIN ... USING` expose only their physical slot.
228    pub fn qualified_star_position_layout(
229        &self,
230        qualifier: &str,
231    ) -> Vec<(String, Option<usize>, usize, Option<ColumnType>)> {
232        let mut entries = Vec::new();
233        let mut visible_layout = HashSet::new();
234        for (logical, identity) in self.identities().iter().enumerate() {
235            if identity.qualifier() == Some(qualifier) {
236                let slot = self.slot(logical).unwrap_or(NULL_SLOT);
237                visible_layout.insert((identity.clone(), slot));
238                entries.push((
239                    identity.clone(),
240                    Some(logical),
241                    slot,
242                    self.column_type(logical).cloned(),
243                ));
244            }
245        }
246        for (identity, slot) in &self.index.aliases {
247            if identity.qualifier() == Some(qualifier)
248                && !visible_layout.contains(&(identity.clone(), *slot))
249            {
250                entries.push((
251                    identity.clone(),
252                    None,
253                    *slot,
254                    self.index.cold.aliases.get(identity).cloned().flatten(),
255                ));
256            }
257        }
258        entries.sort_by_key(|(_, _, slot, _)| *slot);
259        entries
260            .into_iter()
261            .map(|(identity, logical, slot, ty)| (identity.column().to_string(), logical, slot, ty))
262            .collect()
263    }
264
265    pub fn qualified_slot(&self, qualifier: &str, column: &str) -> Option<usize> {
266        let identity = (Some(qualifier), column);
267        let identity = &identity as &dyn ColumnKey;
268        if self.index.ambiguous_qualified.contains(identity) {
269            return None;
270        }
271        self.index
272            .qualified
273            .get(identity)
274            .and_then(|logical| self.slot(*logical))
275            .or_else(|| self.index.aliases.get(identity).copied())
276            .filter(|slot| *slot != NULL_SLOT)
277    }
278
279    /// Borrow physical wildcard demand without copying column names or types. Visible and hidden identities may repeat the same slot; a positional consumer deduplicates them under its own allowance.
280    pub fn qualified_star_slots<'a>(
281        &'a self,
282        qualifier: &'a str,
283    ) -> impl Iterator<Item = usize> + 'a {
284        self.identities()
285            .iter()
286            .enumerate()
287            .filter(move |(_, identity)| identity.qualifier() == Some(qualifier))
288            .map(|(logical, _)| self.slot(logical).unwrap_or(NULL_SLOT))
289            .chain(
290                self.index
291                    .aliases
292                    .iter()
293                    .filter(move |(identity, _)| identity.qualifier() == Some(qualifier))
294                    .map(|(_, slot)| *slot),
295            )
296    }
297}
298
299impl<'a> IntoIterator for &'a RowSchema {
300    type Item = &'a String;
301    type IntoIter = std::slice::Iter<'a, String>;
302
303    fn into_iter(self) -> Self::IntoIter {
304        self.iter()
305    }
306}