Skip to main content

uqa_sql/schema/
collations.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Selected collation metadata follows logical bindings independently of value slots.
8
9use super::{
10    ColumnIdentity, ColumnType, InternalColumnRef, RowSchema, SchemaLayoutError,
11    SchemaLayoutResult, SchemaMap,
12};
13use crate::catalog::type_metadata::pg_type_collation_oid;
14use std::collections::BTreeMap;
15
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub(super) struct Collations(Option<Box<Bindings>>);
18
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20struct Bindings {
21    columns: BTreeMap<usize, u32>,
22    aliases: BTreeMap<ColumnIdentity, u32>,
23    internal: BTreeMap<InternalColumnRef, u32>,
24    virtual_columns: BTreeMap<ColumnIdentity, u32>,
25}
26
27/// A selected collation belongs to a logical identity even when its physical value is NULL or shared with another identity.
28#[derive(Clone, Copy, Debug)]
29pub enum CollationBinding<'a> {
30    Column(usize),
31    Alias(&'a ColumnIdentity),
32    Internal(InternalColumnRef),
33}
34
35fn type_default(ty: Option<&ColumnType>) -> Option<u32> {
36    ty.map(|ty| u32::try_from(pg_type_collation_oid(ty)).expect("type collation identity"))
37}
38
39fn override_value(oid: Option<u32>, ty: Option<&ColumnType>) -> Option<u32> {
40    oid.filter(|oid| {
41        ty.is_some_and(|ty| {
42            crate::schema::composites::type_is_collatable(ty)
43                && type_default(Some(ty)) != Some(*oid)
44        })
45    })
46}
47
48impl Collations {
49    pub(super) fn same_physical_bindings(&self, other: &Self) -> bool {
50        let empty = Bindings::default();
51        let left = self.0.as_deref().unwrap_or(&empty);
52        let right = other.0.as_deref().unwrap_or(&empty);
53        left.columns == right.columns
54            && left.aliases == right.aliases
55            && left.internal == right.internal
56    }
57
58    pub(super) fn joined(left: &RowSchema, right: &RowSchema) -> Self {
59        let mut result = left.index.cold.collations.clone();
60        if let Some(target) = &mut result.0 {
61            if !target.aliases.is_empty() {
62                for identity in right.index.cold.aliases.keys() {
63                    target.aliases.remove(identity);
64                }
65            }
66            if !target.virtual_columns.is_empty() {
67                for identity in right.index.cold.binding_only.keys() {
68                    target.virtual_columns.remove(identity);
69                }
70            }
71        }
72        if let Some(source) = &right.index.cold.collations.0 {
73            let target = result.0.get_or_insert_with(Default::default);
74            target.columns.extend(
75                source
76                    .columns
77                    .iter()
78                    .map(|(position, oid)| (left.len() + position, *oid)),
79            );
80            target.aliases.extend(
81                source
82                    .aliases
83                    .iter()
84                    .map(|(identity, oid)| (identity.clone(), *oid)),
85            );
86            target
87                .internal
88                .extend(source.internal.iter().map(|(column, oid)| (*column, *oid)));
89            target.virtual_columns.extend(
90                source
91                    .virtual_columns
92                    .iter()
93                    .map(|(identity, oid)| (identity.clone(), *oid)),
94            );
95        }
96        result.compact();
97        result
98    }
99
100    fn compact(&mut self) {
101        if self.0.as_ref().is_some_and(|bindings| {
102            bindings.columns.is_empty()
103                && bindings.aliases.is_empty()
104                && bindings.internal.is_empty()
105                && bindings.virtual_columns.is_empty()
106        }) {
107            self.0 = None;
108        }
109    }
110
111    pub(super) fn column(&mut self, position: usize, oid: Option<u32>, ty: Option<&ColumnType>) {
112        let value = override_value(oid, ty);
113        if let Some(value) = value {
114            self.0
115                .get_or_insert_with(Default::default)
116                .columns
117                .insert(position, value);
118        } else if let Some(bindings) = &mut self.0 {
119            bindings.columns.remove(&position);
120        }
121    }
122
123    pub(super) fn alias(
124        &mut self,
125        identity: &ColumnIdentity,
126        oid: Option<u32>,
127        ty: Option<&ColumnType>,
128    ) {
129        let value = override_value(oid, ty);
130        if let Some(value) = value {
131            self.0
132                .get_or_insert_with(Default::default)
133                .aliases
134                .insert(identity.clone(), value);
135        } else if let Some(bindings) = &mut self.0 {
136            bindings.aliases.remove(identity);
137        }
138    }
139
140    pub(super) fn internal(
141        &mut self,
142        column: InternalColumnRef,
143        oid: Option<u32>,
144        ty: Option<&ColumnType>,
145    ) {
146        let value = override_value(oid, ty);
147        if let Some(value) = value {
148            self.0
149                .get_or_insert_with(Default::default)
150                .internal
151                .insert(column, value);
152        } else if let Some(bindings) = &mut self.0 {
153            bindings.internal.remove(&column);
154        }
155    }
156
157    pub(super) fn virtual_column(
158        &mut self,
159        identity: &ColumnIdentity,
160        oid: Option<u32>,
161        ty: Option<&ColumnType>,
162    ) {
163        let value = override_value(oid, ty);
164        if let Some(value) = value {
165            self.0
166                .get_or_insert_with(Default::default)
167                .virtual_columns
168                .insert(identity.clone(), value);
169        } else if let Some(bindings) = &mut self.0 {
170            bindings.virtual_columns.remove(identity);
171        }
172    }
173
174    pub(super) fn clear_columns(&mut self) {
175        if let Some(bindings) = &mut self.0 {
176            bindings.columns.clear();
177        }
178    }
179
180    /// Schema construction discards metadata for removed identities and defaults. Schemas with only type-default collations have no extra allocation.
181    pub(super) fn retain(
182        &mut self,
183        columns: &[Option<ColumnType>],
184        aliases: &SchemaMap<ColumnIdentity, Option<ColumnType>>,
185        internal: &SchemaMap<InternalColumnRef, Option<ColumnType>>,
186        virtual_columns: &SchemaMap<ColumnIdentity, Option<ColumnType>>,
187    ) {
188        let Some(bindings) = &mut self.0 else {
189            return;
190        };
191        bindings.columns.retain(|position, oid| {
192            override_value(Some(*oid), columns.get(*position).and_then(Option::as_ref)).is_some()
193        });
194        bindings.aliases.retain(|identity, oid| {
195            override_value(Some(*oid), aliases.get(identity).and_then(Option::as_ref)).is_some()
196        });
197        bindings.internal.retain(|column, oid| {
198            override_value(Some(*oid), internal.get(column).and_then(Option::as_ref)).is_some()
199        });
200        bindings.virtual_columns.retain(|identity, oid| {
201            override_value(
202                Some(*oid),
203                virtual_columns.get(identity).and_then(Option::as_ref),
204            )
205            .is_some()
206        });
207        if bindings.columns.is_empty()
208            && bindings.aliases.is_empty()
209            && bindings.internal.is_empty()
210            && bindings.virtual_columns.is_empty()
211        {
212            self.0 = None;
213        }
214    }
215}
216
217impl RowSchema {
218    /// Observe retained expression metadata or a direct logical reference, including selected clauses, static bindings and executor attributes without a visible output position.
219    pub fn input_collation(&self, expression: &crate::ScalarExpr) -> Option<u32> {
220        super::ScalarTypeSchema::input_collation(self, expression)
221    }
222
223    /// Bind a direct scalar reference without confusing its SQL identity with another logical column that shares the same physical value. Static binding-only names remain with expression evaluation.
224    pub fn projection_input(&self, expression: &crate::ScalarExpr) -> Option<super::ProjectedSlot> {
225        let (logical, alias) = match expression {
226            crate::ScalarExpr::Column(name) => {
227                if self.column_is_ambiguous(name) {
228                    return None;
229                }
230                let logical = self.unqualified_position(name);
231                (
232                    logical,
233                    logical.is_none().then(|| ColumnIdentity::unqualified(name)),
234                )
235            }
236            crate::ScalarExpr::QualifiedColumn { qualifier, column } => {
237                if self.qualified_column_is_ambiguous(qualifier, column) {
238                    return None;
239                }
240                let logical = self.qualified_position(qualifier, column);
241                (
242                    logical,
243                    logical
244                        .is_none()
245                        .then(|| ColumnIdentity::qualified(qualifier, column)),
246                )
247            }
248            crate::ScalarExpr::Position(position) if *position < self.len() => {
249                (Some(*position), None)
250            }
251            _ => return None,
252        };
253        let (physical, collation) = if let Some(position) = logical {
254            (
255                self.physical_slot(position),
256                self.column_collation(position),
257            )
258        } else {
259            let identity = alias?;
260            let slot = *self.index.aliases.get(&identity)?;
261            (
262                (slot != super::NULL_SLOT).then_some(slot),
263                self.alias_collation(&identity),
264            )
265        };
266        Some(super::ProjectedSlot::BoundInput {
267            physical,
268            collation,
269        })
270    }
271
272    /// Attach already-selected column collations to an owned schema. The width and collatability must match its declared types; catalog name resolution belongs to the caller's SQL analysis.
273    pub fn with_column_collations(
274        mut self,
275        collations: impl IntoIterator<Item = Option<u32>>,
276    ) -> Self {
277        let mut width = 0;
278        let index = std::sync::Arc::make_mut(&mut self.index);
279        for (position, oid) in collations.into_iter().enumerate() {
280            assert!(
281                position < index.columns.len(),
282                "row schema column/collation width mismatch"
283            );
284            let ty = index.cold.columns[position].as_ref();
285            assert!(
286                oid.is_none_or(
287                    |oid| oid == 0 || ty.is_some_and(crate::schema::composites::type_is_collatable)
288                ),
289                "collation requires a collatable column type"
290            );
291            index.cold.collations.column(position, oid, ty);
292            width += 1;
293        }
294        assert_eq!(
295            width,
296            index.columns.len(),
297            "row schema column/collation width mismatch"
298        );
299        index.cold.collations.compact();
300        self
301    }
302
303    /// Select a collation for an existing static binding without adding a physical slot or wildcard output.
304    pub fn with_virtual_collation(
305        mut self,
306        identity: &ColumnIdentity,
307        oid: u32,
308    ) -> SchemaLayoutResult<Self> {
309        let ty = self
310            .index
311            .cold
312            .binding_only
313            .get(identity)
314            .and_then(Option::as_ref);
315        if ty.is_none_or(|ty| !crate::schema::composites::type_is_collatable(ty)) {
316            return Err(SchemaLayoutError(
317                "collation metadata requires an existing collatable virtual binding".into(),
318            ));
319        }
320        let index = std::sync::Arc::make_mut(&mut self.index);
321        index.cold.collations.virtual_column(
322            identity,
323            Some(oid),
324            index
325                .cold
326                .binding_only
327                .get(identity)
328                .and_then(Option::as_ref),
329        );
330        index.cold.collations.compact();
331        Ok(self)
332    }
333
334    pub fn column_collation(&self, position: usize) -> Option<u32> {
335        self.index
336            .cold
337            .collations
338            .0
339            .as_ref()
340            .and_then(|bindings| bindings.columns.get(&position).copied())
341            .or_else(|| type_default(self.column_type(position)))
342    }
343
344    pub fn internal_collation(&self, column: InternalColumnRef) -> Option<u32> {
345        self.index
346            .cold
347            .collations
348            .0
349            .as_ref()
350            .and_then(|bindings| bindings.internal.get(&column).copied())
351            .or_else(|| type_default(self.internal_type(column)))
352    }
353
354    pub fn collation_of(&self, name: &str) -> Option<u32> {
355        if self.column_is_ambiguous(name) {
356            return None;
357        }
358        self.index
359            .unqualified
360            .get(name)
361            .and_then(|position| self.column_collation(*position))
362            .or_else(|| self.hidden_collation(&ColumnIdentity::unqualified(name)))
363    }
364
365    pub fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
366        let identity = ColumnIdentity::qualified(qualifier, name);
367        if self.index.ambiguous_qualified.contains(&identity) {
368            return None;
369        }
370        self.index
371            .qualified
372            .get(&identity)
373            .and_then(|position| self.column_collation(*position))
374            .or_else(|| self.hidden_collation(&identity))
375    }
376
377    fn hidden_collation(&self, identity: &ColumnIdentity) -> Option<u32> {
378        self.alias_collation(identity)
379            .or_else(|| self.virtual_collation(identity))
380    }
381
382    pub(super) fn virtual_collation(&self, identity: &ColumnIdentity) -> Option<u32> {
383        self.index
384            .cold
385            .collations
386            .0
387            .as_ref()
388            .and_then(|bindings| bindings.virtual_columns.get(identity).copied())
389            .or_else(|| {
390                type_default(
391                    self.index
392                        .cold
393                        .binding_only
394                        .get(identity)
395                        .and_then(Option::as_ref),
396                )
397            })
398    }
399
400    pub(super) fn alias_collation(&self, identity: &ColumnIdentity) -> Option<u32> {
401        self.index
402            .cold
403            .collations
404            .0
405            .as_ref()
406            .and_then(|bindings| bindings.aliases.get(identity).copied())
407            .or_else(|| {
408                type_default(
409                    self.index
410                        .cold
411                        .aliases
412                        .get(identity)
413                        .and_then(Option::as_ref),
414                )
415            })
416    }
417
418    pub(super) fn inherited_column_collation(&self, position: usize) -> Option<u32> {
419        self.column_type(position)
420            .filter(|ty| crate::schema::composites::type_is_collatable(ty))
421            .and_then(|_| self.column_collation(position))
422    }
423
424    pub(super) fn inherited_physical_collation(&self, physical: usize) -> Option<u32> {
425        if physical == super::NULL_SLOT {
426            return None;
427        }
428        self.index
429            .slots
430            .iter()
431            .position(|slot| *slot == physical)
432            .and_then(|position| self.inherited_column_collation(position))
433            .or_else(|| {
434                self.index.aliases.iter().find_map(|(identity, slot)| {
435                    (*slot == physical
436                        && self
437                            .index
438                            .cold
439                            .aliases
440                            .get(identity)
441                            .and_then(Option::as_ref)
442                            .is_some_and(crate::schema::composites::type_is_collatable))
443                    .then(|| self.alias_collation(identity))
444                    .flatten()
445                })
446            })
447            .or_else(|| {
448                self.index
449                    .executor_attributes
450                    .iter()
451                    .find_map(|(column, slot)| {
452                        (*slot == physical
453                            && self
454                                .internal_type(*column)
455                                .is_some_and(crate::schema::composites::type_is_collatable))
456                        .then(|| self.internal_collation(*column))
457                        .flatten()
458                    })
459            })
460    }
461
462    /// Physical spill metadata excludes static name-binding-only identities, like the existing spill type layout. Type defaults need no extra record payload.
463    pub fn collation_overrides(&self) -> impl Iterator<Item = (CollationBinding<'_>, u32)> {
464        self.index.cold.collations.0.iter().flat_map(|bindings| {
465            bindings
466                .columns
467                .iter()
468                .map(|(column, oid)| (CollationBinding::Column(*column), *oid))
469                .chain(
470                    bindings
471                        .aliases
472                        .iter()
473                        .map(|(identity, oid)| (CollationBinding::Alias(identity), *oid)),
474                )
475                .chain(
476                    bindings
477                        .internal
478                        .iter()
479                        .map(|(column, oid)| (CollationBinding::Internal(*column), *oid)),
480                )
481        })
482    }
483
484    /// Restore one selected collation only for a binding that exists in this layout. Invalid spill metadata cannot invent columns or attach a collation to a noncollatable type.
485    pub fn with_collation_override(
486        mut self,
487        binding: CollationBinding<'_>,
488        oid: u32,
489    ) -> SchemaLayoutResult<Self> {
490        let ty = match binding {
491            CollationBinding::Column(position) => self.column_type(position),
492            CollationBinding::Alias(identity) => self
493                .index
494                .cold
495                .aliases
496                .get(identity)
497                .and_then(Option::as_ref),
498            CollationBinding::Internal(column) => self.internal_type(column),
499        };
500        if ty.is_none_or(|ty| !crate::schema::composites::type_is_collatable(ty)) {
501            return Err(SchemaLayoutError(
502                "collation metadata requires an existing collatable binding".into(),
503            ));
504        }
505        let value = override_value(Some(oid), ty);
506        let index = std::sync::Arc::make_mut(&mut self.index);
507        match binding {
508            CollationBinding::Column(position) => {
509                index.cold.collations.column(
510                    position,
511                    value,
512                    index.cold.columns[position].as_ref(),
513                );
514            }
515            CollationBinding::Alias(identity) => index.cold.collations.alias(
516                identity,
517                value,
518                index.cold.aliases.get(identity).and_then(Option::as_ref),
519            ),
520            CollationBinding::Internal(column) => index.cold.collations.internal(
521                column,
522                value,
523                index
524                    .cold
525                    .executor_attribute_types
526                    .get(&column)
527                    .and_then(Option::as_ref),
528            ),
529        }
530        index.cold.collations.compact();
531        Ok(self)
532    }
533}
534
535#[cfg(test)]
536mod tests;