Skip to main content

uqa_sql/schema/
relation_types.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Whole-row namespaces survive empty rows independently of named type identity.
8
9use super::{Arc, ColumnIdentity, ColumnType, RowSchema, SchemaMap};
10use crate::SQLError;
11
12mod production;
13
14/// Absent namespaces allocate no map; copies of a retained scope share its identities.
15#[derive(Debug, Default, Clone, PartialEq, Eq)]
16pub(super) struct RelationRowTypes(Option<Arc<RelationRows>>);
17
18#[derive(Debug, Default, Clone, PartialEq, Eq)]
19struct RelationRows {
20    types: SchemaMap<Box<str>, Option<ColumnType>>,
21    /// The complete local row denotes this one source. A join or an outer-only namespace has no such identity.
22    source: Option<Box<str>>,
23    _memory: super::production::lease::SchemaMemory,
24}
25
26impl RelationRowTypes {
27    pub(super) fn get(&self, qualifier: &str) -> Option<&ColumnType> {
28        self.0.as_ref()?.types.get(qualifier)?.as_ref()
29    }
30
31    pub(super) fn contains(&self, qualifier: &str) -> bool {
32        self.0
33            .as_ref()
34            .is_some_and(|rows| rows.types.contains_key(qualifier))
35    }
36
37    pub(super) fn anonymous(qualifier: &str) -> Self {
38        let mut result = Self::default();
39        result.insert(qualifier, None);
40        Arc::make_mut(result.0.as_mut().unwrap()).source = Some(qualifier.into());
41        result
42    }
43
44    pub(super) fn qualifiers(&self) -> impl Iterator<Item = &str> {
45        self.0
46            .iter()
47            .flat_map(|rows| rows.types.keys().map(std::convert::AsRef::as_ref))
48    }
49
50    fn insert(&mut self, qualifier: &str, ty: Option<ColumnType>) {
51        let rows = self
52            .0
53            .get_or_insert_with(|| Arc::new(RelationRows::default()));
54        Arc::make_mut(rows).types.insert(qualifier.into(), ty);
55    }
56
57    /// An alias of one retained relation keeps that relation's named type. A boundary over several relations produces an anonymous row.
58    pub(super) fn requalified(&self, input: &RowSchema, qualifier: &str) -> Self {
59        let anonymous = || {
60            if input.is_empty() {
61                Self::anonymous(qualifier)
62            } else {
63                Self::default()
64            }
65        };
66        let Some(rows) = self.0.as_ref() else {
67            return anonymous();
68        };
69        let Some(source) = rows.source.as_deref() else {
70            return anonymous();
71        };
72        if input
73            .identities()
74            .iter()
75            .enumerate()
76            .any(|(position, column)| {
77                input.wildcard_position_visible(position) && column.qualifier() != Some(source)
78            })
79        {
80            return anonymous();
81        }
82        let mut result = Self::default();
83        result.insert(qualifier, rows.types[source].clone());
84        Arc::make_mut(result.0.as_mut().unwrap()).source = Some(qualifier.into());
85        result
86    }
87
88    pub(super) fn joined(left: &RowSchema, right: &RowSchema) -> Self {
89        if left.index.cold.row_types.0.is_none() && right.index.cold.row_types.0.is_none() {
90            return Self::default();
91        }
92        let mut result = Self::default();
93        for (source, other) in [(left, right), (right, left)] {
94            if let Some(rows) = &source.index.cold.row_types.0 {
95                for (qualifier, ty) in &rows.types {
96                    if !other.has_qualifier(qualifier) {
97                        result.insert(qualifier, ty.clone());
98                    }
99                }
100            }
101        }
102        result
103    }
104
105    pub(super) fn with_outer(input: &RowSchema, outer: &RowSchema) -> Self {
106        let mut result = input.index.cold.row_types.clone();
107        if let Some(rows) = &outer.index.cold.row_types.0 {
108            for (qualifier, ty) in &rows.types {
109                if !input.has_qualifier(qualifier) {
110                    result.insert(qualifier, ty.clone());
111                }
112            }
113        }
114        result
115    }
116}
117
118impl RowSchema {
119    pub(super) fn relation_qualifiers(&self) -> impl Iterator<Item = &str> {
120        self.index
121            .qualified
122            .keys()
123            .chain(self.index.aliases.keys())
124            .filter_map(ColumnIdentity::qualifier)
125            .chain(self.index.cold.row_types.qualifiers())
126            .chain(self.whole_row_presences().map(|(qualifier, _)| qualifier))
127    }
128
129    /// Retain a relation's actual named composite identity without adding an ordinary column or a physical value slot. The existing source namespace must belong to that relation; a zero-column relation acquires its namespace here.
130    pub fn with_relation_row_type(
131        mut self,
132        qualifier: &str,
133        ty: ColumnType,
134    ) -> Result<Self, SQLError> {
135        if !matches!(ty, ColumnType::Composite(_))
136            || (!self.is_empty() && !self.has_qualifier(qualifier))
137        {
138            return Err(SQLError::Internal(
139                "a relation row type requires its named composite and source namespace".into(),
140            ));
141        }
142        let rows = &mut Arc::make_mut(&mut self.index).cold.row_types;
143        rows.insert(qualifier, Some(ty));
144        let rows = Arc::make_mut(rows.0.as_mut().unwrap());
145        rows.source = (rows.types.len() == 1).then(|| qualifier.into());
146        Ok(self)
147    }
148}
149
150#[cfg(test)]
151mod tests;