Skip to main content

uqa_sql/schema/
type_lookup.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scalar type lookup borrows declared columns without constructing physical row indexes.
8
9use super::RowSchema;
10use crate::ast::{ColumnDef, ColumnType, InternalColumnRef};
11
12/// Borrowed schema operations used by scalar type propagation and binding. Physical schemas retain their complete alias, ambiguity, open-column and executor-attribute behavior; declared column slices supply an unqualified positional namespace without allocating another schema generation.
13pub trait ScalarTypeSchema {
14    /// Reuse an already analyzed expression occurrence in this scope. `Some(None)` preserves an observed unknown type; `None` asks the caller to infer the expression normally. Borrowed observations must not outlive their original expressions or parameter environment.
15    fn observed_expression_type(&self, _: &crate::ScalarExpr) -> Option<Option<&ColumnType>> {
16        None
17    }
18
19    fn has_unqualified_column(&self, name: &str) -> bool;
20    fn column_is_ambiguous(&self, name: &str) -> bool;
21    fn type_of(&self, name: &str) -> Option<&ColumnType>;
22    fn column_type(&self, position: usize) -> Option<&ColumnType>;
23    fn internal_type(&self, column: InternalColumnRef) -> Option<&ColumnType>;
24    fn has_qualifier(&self, qualifier: &str) -> bool;
25    /// The named composite identity of a relation's whole row, when the caller retains it. Query-only scopes may expose an anonymous record instead.
26    fn whole_row_type(&self, _qualifier: &str) -> Option<&ColumnType> {
27        None
28    }
29    fn has_qualified_column(&self, qualifier: &str, name: &str) -> bool;
30    fn qualified_column_is_ambiguous(&self, qualifier: &str, name: &str) -> bool;
31    fn qualified_type(&self, qualifier: &str, name: &str) -> Option<&ColumnType>;
32    fn columns_are_open(&self, qualifier: Option<&str>) -> bool;
33
34    /// Observe the analyzed result selection or a direct input reference without repeating type input, evaluation or collation derivation.
35    fn input_collation(&self, expression: &crate::ScalarExpr) -> Option<u32> {
36        match expression {
37            crate::ScalarExpr::TypedLiteral { collation_oid, .. } => *collation_oid,
38            crate::ScalarExpr::Collated { collation, .. } => Some(collation.oid()),
39            crate::ScalarExpr::Func {
40                binding: Some(binding),
41                ..
42            } => match binding.dispatch {
43                Some(crate::ast::FunctionDispatch::Collate { oid }) => oid,
44                _ => None,
45            },
46            crate::ScalarExpr::Column(name) => self.collation_of(name),
47            crate::ScalarExpr::QualifiedColumn { qualifier, column } => {
48                self.qualified_collation(qualifier, column)
49            }
50            crate::ScalarExpr::Position(position) => self.column_collation(*position),
51            crate::ScalarExpr::InternalColumn(column) => self.internal_collation(*column),
52            _ => None,
53        }
54    }
55
56    fn column_collation(&self, position: usize) -> Option<u32> {
57        self.column_type(position).map(default_collation)
58    }
59    fn collation_of(&self, name: &str) -> Option<u32> {
60        self.type_of(name).map(default_collation)
61    }
62    fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
63        self.qualified_type(qualifier, name).map(default_collation)
64    }
65    fn internal_collation(&self, column: InternalColumnRef) -> Option<u32> {
66        self.internal_type(column).map(default_collation)
67    }
68
69    /// Preserve the physical outer-row interface used by existing custom scalar-subquery resolvers. Declared column views have no query arena or physical outer row.
70    fn physical_schema(&self) -> Option<&RowSchema>;
71}
72
73fn default_collation(ty: &ColumnType) -> u32 {
74    u32::try_from(crate::catalog::type_metadata::pg_type_collation_oid(ty))
75        .expect("type collation identity")
76}
77
78impl ScalarTypeSchema for RowSchema {
79    fn column_collation(&self, position: usize) -> Option<u32> {
80        Self::column_collation(self, position)
81    }
82    fn collation_of(&self, name: &str) -> Option<u32> {
83        Self::collation_of(self, name)
84    }
85    fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
86        Self::qualified_collation(self, qualifier, name)
87    }
88    fn internal_collation(&self, column: InternalColumnRef) -> Option<u32> {
89        Self::internal_collation(self, column)
90    }
91
92    fn has_unqualified_column(&self, name: &str) -> bool {
93        Self::has_unqualified_column(self, name)
94    }
95    fn column_is_ambiguous(&self, name: &str) -> bool {
96        Self::column_is_ambiguous(self, name)
97    }
98    fn type_of(&self, name: &str) -> Option<&ColumnType> {
99        Self::type_of(self, name)
100    }
101    fn column_type(&self, position: usize) -> Option<&ColumnType> {
102        Self::column_type(self, position)
103    }
104    fn internal_type(&self, column: InternalColumnRef) -> Option<&ColumnType> {
105        Self::internal_type(self, column)
106    }
107    fn has_qualifier(&self, qualifier: &str) -> bool {
108        Self::has_qualifier(self, qualifier)
109    }
110    fn whole_row_type(&self, qualifier: &str) -> Option<&ColumnType> {
111        self.index.cold.row_types.get(qualifier)
112    }
113    fn has_qualified_column(&self, qualifier: &str, name: &str) -> bool {
114        Self::has_qualified_column(self, qualifier, name)
115    }
116    fn qualified_column_is_ambiguous(&self, qualifier: &str, name: &str) -> bool {
117        Self::qualified_column_is_ambiguous(self, qualifier, name)
118    }
119    fn qualified_type(&self, qualifier: &str, name: &str) -> Option<&ColumnType> {
120        Self::qualified_type(self, qualifier, name)
121    }
122    fn columns_are_open(&self, qualifier: Option<&str>) -> bool {
123        Self::columns_are_open(self, qualifier)
124    }
125    fn physical_schema(&self) -> Option<&RowSchema> {
126        Some(self)
127    }
128}
129
130/// Zero-allocation view matching `RowSchema::with_types` for the supplied unqualified column definitions. Names and declared types, including domains and nested arrays, stay borrowed from their existing owner. Duplicate exact names remain ambiguous; dots in an identifier do not create a relation qualifier.
131#[derive(Clone, Copy)]
132pub struct ColumnTypeSchema<'a> {
133    columns: &'a [ColumnDef],
134    relation: Option<(&'a str, &'a ColumnType)>,
135}
136
137impl<'a> ColumnTypeSchema<'a> {
138    pub fn new(columns: &'a [ColumnDef]) -> Self {
139        Self {
140            columns,
141            relation: None,
142        }
143    }
144
145    /// Retain the declaring relation's actual row type without copying its columns or representing system attributes as user columns.
146    pub fn with_relation(
147        columns: &'a [ColumnDef],
148        name: &'a str,
149        row_type: &'a ColumnType,
150    ) -> Result<Self, crate::SQLError> {
151        if !matches!(row_type, ColumnType::Composite(_)) {
152            return Err(crate::SQLError::Internal(
153                "a relation scope requires its named composite row type".into(),
154            ));
155        }
156        Ok(Self {
157            columns,
158            relation: Some((name, row_type)),
159        })
160    }
161
162    pub(crate) fn system_column_type(&self, name: &str) -> Option<&ColumnType> {
163        (self.relation.is_some() && name == "tableoid").then_some(&ColumnType::Oid)
164    }
165
166    /// Original declarations, including stable attribute numbers and selected collations, borrowed from the same catalog generation as type lookup.
167    pub fn columns(&self) -> &'a [ColumnDef] {
168        self.columns
169    }
170}
171
172impl ScalarTypeSchema for ColumnTypeSchema<'_> {
173    fn column_collation(&self, position: usize) -> Option<u32> {
174        self.columns.get(position).map(|column| {
175            column
176                .collation_oid
177                .unwrap_or_else(|| default_collation(&column.ty))
178        })
179    }
180    fn collation_of(&self, name: &str) -> Option<u32> {
181        let mut matching = self
182            .columns
183            .iter()
184            .enumerate()
185            .filter(|(_, column)| column.name == name);
186        let Some((position, _)) = matching.next() else {
187            return self.system_column_type(name).map(default_collation);
188        };
189        matching
190            .next()
191            .is_none()
192            .then(|| self.column_collation(position))
193            .flatten()
194    }
195
196    fn has_unqualified_column(&self, name: &str) -> bool {
197        self.columns.iter().any(|column| column.name == name)
198            || self.system_column_type(name).is_some()
199    }
200    fn column_is_ambiguous(&self, name: &str) -> bool {
201        self.columns
202            .iter()
203            .filter(|column| column.name == name)
204            .nth(1)
205            .is_some()
206    }
207    fn type_of(&self, name: &str) -> Option<&ColumnType> {
208        let mut matching = self.columns.iter().filter(|column| column.name == name);
209        let Some(first) = matching.next() else {
210            return self.system_column_type(name);
211        };
212        matching.next().is_none().then_some(&first.ty)
213    }
214    fn column_type(&self, position: usize) -> Option<&ColumnType> {
215        self.columns.get(position).map(|column| &column.ty)
216    }
217    fn internal_type(&self, _: InternalColumnRef) -> Option<&ColumnType> {
218        None
219    }
220    fn has_qualifier(&self, qualifier: &str) -> bool {
221        self.whole_row_type(qualifier).is_some()
222    }
223    fn whole_row_type(&self, qualifier: &str) -> Option<&ColumnType> {
224        let (name, row_type) = self.relation?;
225        let ColumnType::Composite(reference) = row_type else {
226            unreachable!("relation scope validates its row type");
227        };
228        (qualifier == name || qualifier == reference.name).then_some(row_type)
229    }
230    fn has_qualified_column(&self, qualifier: &str, name: &str) -> bool {
231        self.has_qualifier(qualifier) && self.has_unqualified_column(name)
232    }
233    fn qualified_column_is_ambiguous(&self, qualifier: &str, name: &str) -> bool {
234        self.has_qualifier(qualifier) && self.column_is_ambiguous(name)
235    }
236    fn qualified_type(&self, qualifier: &str, name: &str) -> Option<&ColumnType> {
237        self.has_qualifier(qualifier)
238            .then(|| self.type_of(name))
239            .flatten()
240    }
241    fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
242        self.has_qualifier(qualifier)
243            .then(|| self.collation_of(name))
244            .flatten()
245    }
246    fn columns_are_open(&self, _: Option<&str>) -> bool {
247        false
248    }
249    fn physical_schema(&self) -> Option<&RowSchema> {
250        None
251    }
252}
253
254#[cfg(test)]
255mod tests;