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::RetainedLiteral(literal) => literal.collation_oid,
38            crate::ScalarExpr::TypedLiteral { collation_oid, .. } => *collation_oid,
39            crate::ScalarExpr::Collated { collation, .. } => Some(collation.oid()),
40            crate::ScalarExpr::Func {
41                binding: Some(binding),
42                ..
43            } => match binding.dispatch {
44                Some(crate::ast::FunctionDispatch::Collate { oid }) => oid,
45                _ => None,
46            },
47            crate::ScalarExpr::Column(name) => self.collation_of(name),
48            crate::ScalarExpr::QualifiedColumn { qualifier, column } => {
49                self.qualified_collation(qualifier, column)
50            }
51            crate::ScalarExpr::Position(position) => self.column_collation(*position),
52            crate::ScalarExpr::InternalColumn(column) => self.internal_collation(*column),
53            _ => None,
54        }
55    }
56
57    fn column_collation(&self, position: usize) -> Option<u32> {
58        self.column_type(position).map(default_collation)
59    }
60    fn collation_of(&self, name: &str) -> Option<u32> {
61        self.type_of(name).map(default_collation)
62    }
63    fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
64        self.qualified_type(qualifier, name).map(default_collation)
65    }
66    fn internal_collation(&self, column: InternalColumnRef) -> Option<u32> {
67        self.internal_type(column).map(default_collation)
68    }
69
70    /// Preserve the physical outer-row interface used by existing custom scalar-subquery resolvers. Declared column views have no query arena or physical outer row.
71    fn physical_schema(&self) -> Option<&RowSchema>;
72}
73
74fn default_collation(ty: &ColumnType) -> u32 {
75    u32::try_from(crate::catalog::type_metadata::pg_type_collation_oid(ty))
76        .expect("type collation identity")
77}
78
79impl ScalarTypeSchema for RowSchema {
80    fn column_collation(&self, position: usize) -> Option<u32> {
81        Self::column_collation(self, position)
82    }
83    fn collation_of(&self, name: &str) -> Option<u32> {
84        Self::collation_of(self, name)
85    }
86    fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
87        Self::qualified_collation(self, qualifier, name)
88    }
89    fn internal_collation(&self, column: InternalColumnRef) -> Option<u32> {
90        Self::internal_collation(self, column)
91    }
92
93    fn has_unqualified_column(&self, name: &str) -> bool {
94        Self::has_unqualified_column(self, name)
95    }
96    fn column_is_ambiguous(&self, name: &str) -> bool {
97        Self::column_is_ambiguous(self, name)
98    }
99    fn type_of(&self, name: &str) -> Option<&ColumnType> {
100        Self::type_of(self, name)
101    }
102    fn column_type(&self, position: usize) -> Option<&ColumnType> {
103        Self::column_type(self, position)
104    }
105    fn internal_type(&self, column: InternalColumnRef) -> Option<&ColumnType> {
106        Self::internal_type(self, column)
107    }
108    fn has_qualifier(&self, qualifier: &str) -> bool {
109        Self::has_qualifier(self, qualifier)
110    }
111    fn whole_row_type(&self, qualifier: &str) -> Option<&ColumnType> {
112        self.index.cold.row_types.get(qualifier)
113    }
114    fn has_qualified_column(&self, qualifier: &str, name: &str) -> bool {
115        Self::has_qualified_column(self, qualifier, name)
116    }
117    fn qualified_column_is_ambiguous(&self, qualifier: &str, name: &str) -> bool {
118        Self::qualified_column_is_ambiguous(self, qualifier, name)
119    }
120    fn qualified_type(&self, qualifier: &str, name: &str) -> Option<&ColumnType> {
121        Self::qualified_type(self, qualifier, name)
122    }
123    fn columns_are_open(&self, qualifier: Option<&str>) -> bool {
124        Self::columns_are_open(self, qualifier)
125    }
126    fn physical_schema(&self) -> Option<&RowSchema> {
127        Some(self)
128    }
129}
130
131/// 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.
132#[derive(Clone, Copy)]
133pub struct ColumnTypeSchema<'a> {
134    columns: &'a [ColumnDef],
135    relation: Option<(&'a str, &'a ColumnType)>,
136}
137
138impl<'a> ColumnTypeSchema<'a> {
139    pub fn new(columns: &'a [ColumnDef]) -> Self {
140        Self {
141            columns,
142            relation: None,
143        }
144    }
145
146    /// Retain the declaring relation's actual row type without copying its columns or representing system attributes as user columns.
147    pub fn with_relation(
148        columns: &'a [ColumnDef],
149        name: &'a str,
150        row_type: &'a ColumnType,
151    ) -> Result<Self, crate::SQLError> {
152        if !matches!(row_type, ColumnType::Composite(_)) {
153            return Err(crate::SQLError::Internal(
154                "a relation scope requires its named composite row type".into(),
155            ));
156        }
157        Ok(Self {
158            columns,
159            relation: Some((name, row_type)),
160        })
161    }
162
163    pub(crate) fn system_column_type(&self, name: &str) -> Option<&ColumnType> {
164        (self.relation.is_some() && name == "tableoid").then_some(&ColumnType::Oid)
165    }
166
167    /// Original declarations, including stable attribute numbers and selected collations, borrowed from the same catalog generation as type lookup.
168    pub fn columns(&self) -> &'a [ColumnDef] {
169        self.columns
170    }
171}
172
173impl ScalarTypeSchema for ColumnTypeSchema<'_> {
174    fn column_collation(&self, position: usize) -> Option<u32> {
175        self.columns.get(position).map(|column| {
176            column
177                .collation_oid
178                .unwrap_or_else(|| default_collation(&column.ty))
179        })
180    }
181    fn collation_of(&self, name: &str) -> Option<u32> {
182        let mut matching = self
183            .columns
184            .iter()
185            .enumerate()
186            .filter(|(_, column)| column.name == name);
187        let Some((position, _)) = matching.next() else {
188            return self.system_column_type(name).map(default_collation);
189        };
190        matching
191            .next()
192            .is_none()
193            .then(|| self.column_collation(position))
194            .flatten()
195    }
196
197    fn has_unqualified_column(&self, name: &str) -> bool {
198        self.columns.iter().any(|column| column.name == name)
199            || self.system_column_type(name).is_some()
200    }
201    fn column_is_ambiguous(&self, name: &str) -> bool {
202        self.columns
203            .iter()
204            .filter(|column| column.name == name)
205            .nth(1)
206            .is_some()
207    }
208    fn type_of(&self, name: &str) -> Option<&ColumnType> {
209        let mut matching = self.columns.iter().filter(|column| column.name == name);
210        let Some(first) = matching.next() else {
211            return self.system_column_type(name);
212        };
213        matching.next().is_none().then_some(&first.ty)
214    }
215    fn column_type(&self, position: usize) -> Option<&ColumnType> {
216        self.columns.get(position).map(|column| &column.ty)
217    }
218    fn internal_type(&self, _: InternalColumnRef) -> Option<&ColumnType> {
219        None
220    }
221    fn has_qualifier(&self, qualifier: &str) -> bool {
222        self.whole_row_type(qualifier).is_some()
223    }
224    fn whole_row_type(&self, qualifier: &str) -> Option<&ColumnType> {
225        let (name, row_type) = self.relation?;
226        let ColumnType::Composite(reference) = row_type else {
227            unreachable!("relation scope validates its row type");
228        };
229        (qualifier == name || qualifier == reference.name).then_some(row_type)
230    }
231    fn has_qualified_column(&self, qualifier: &str, name: &str) -> bool {
232        self.has_qualifier(qualifier) && self.has_unqualified_column(name)
233    }
234    fn qualified_column_is_ambiguous(&self, qualifier: &str, name: &str) -> bool {
235        self.has_qualifier(qualifier) && self.column_is_ambiguous(name)
236    }
237    fn qualified_type(&self, qualifier: &str, name: &str) -> Option<&ColumnType> {
238        self.has_qualifier(qualifier)
239            .then(|| self.type_of(name))
240            .flatten()
241    }
242    fn qualified_collation(&self, qualifier: &str, name: &str) -> Option<u32> {
243        self.has_qualifier(qualifier)
244            .then(|| self.collation_of(name))
245            .flatten()
246    }
247    fn columns_are_open(&self, _: Option<&str>) -> bool {
248        false
249    }
250    fn physical_schema(&self) -> Option<&RowSchema> {
251        None
252    }
253}
254
255#[cfg(test)]
256mod tests;