Skip to main content

uqa_sql/expr/
value_catalog.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Borrowed catalog identities and comparison support for SQL value consumers.
8
9use super::enums::{EnumTypeComparisonStates, EnumTypeLabels};
10use super::Result;
11use std::sync::Arc;
12use uqa_core::{
13    memory::{Produced, ProductionControl},
14    EnumValue, Value,
15};
16
17mod records;
18pub use records::SQLRecordFields;
19mod record_view;
20pub use record_view::SQLRecordView;
21mod types;
22pub(crate) use types::field_type_with_control;
23pub(crate) use types::type_by_oid_with_control;
24
25pub(crate) struct ValueCompositeCatalog<'a>(pub(crate) Option<&'a dyn SQLValueCatalog>);
26
27impl super::composites::CompositeTypeCatalog for ValueCompositeCatalog<'_> {
28    fn composite_type_with_control(
29        &self,
30        oid: u32,
31        control: &ProductionControl<'_>,
32    ) -> Result<Option<super::composites::OwnedCompositeTypeDescriptor>> {
33        control.check()?;
34        self.0
35            .ok_or_else(|| {
36                crate::SQLError::Internal("composite operator lookup has no catalog".into())
37            })?
38            .value_composite_type_with_control(oid, control)
39    }
40
41    fn composite_type(
42        &self,
43        oid: u32,
44    ) -> Result<Option<Arc<super::composites::CompositeTypeDescriptor>>> {
45        self.0
46            .ok_or_else(|| {
47                crate::SQLError::Internal("composite operator lookup has no catalog".into())
48            })?
49            .value_composite_type(oid)
50    }
51}
52
53/// Type metadata and enum support used to observe already admitted SQL values. Implementations borrow one statement catalog generation and never invoke type input.
54pub trait SQLValueCatalog {
55    /// The selected endpoint layout of a range or multirange in this statement generation. Observation does not execute input, domain checks or a canonical support function.
56    fn value_range_type(
57        &self,
58        _oid: u32,
59    ) -> Result<Option<Arc<super::range::RangeValueDescriptor>>> {
60        Ok(None)
61    }
62
63    /// Compare admitted bounds with the range's captured operator class and collation. Invocation state belongs to the support-function owner; this operation must not perform endpoint input or range canonicalization.
64    fn compare_range_bounds(
65        &self,
66        _range_oid: u32,
67        _left: &Value,
68        _right: &Value,
69        _control: &ProductionControl<'_>,
70    ) -> Result<std::cmp::Ordering> {
71        Err(super::SQLError::Internal(
72            "selected range comparison support is unavailable".into(),
73        ))
74    }
75
76    /// Return an admitted exact equality key for one finite bound under the same selected operation. Keys must coincide exactly when `compare_range_bounds` returns Equal; an ordinary hash is not an exact key. Execution owns this encoding and any selected normalization.
77    fn range_bound_equality_key(
78        &self,
79        _range_oid: u32,
80        _value: &Value,
81        _control: &ProductionControl<'_>,
82    ) -> Result<Produced<Vec<u8>>> {
83        Err(super::SQLError::Internal(
84            "selected range equality-key support is unavailable".into(),
85        ))
86    }
87
88    /// The declared type for a physical OID, including domains, arrays and composites.
89    fn value_type_by_oid(&self, _oid: u32) -> Result<Option<crate::ColumnType>> {
90        Ok(None)
91    }
92
93    /// Native catalogs project the selected descriptor under the consumer's allowance; external adapters retain their returned metadata.
94    fn value_type_by_oid_with_control(
95        &self,
96        oid: u32,
97        control: &ProductionControl<'_>,
98    ) -> Result<Option<Produced<crate::ColumnType>>> {
99        control.check()?;
100        self.value_type_by_oid(oid)?
101            .map(|ty| ty.retain_external_with_control(control).map_err(Into::into))
102            .transpose()
103    }
104
105    /// Whether an admitted physical OID names any current catalog type, including pseudo-types without a value carrier. This lookup does not check input privileges or execute type input.
106    fn value_type_exists(&self, oid: u32) -> Result<bool> {
107        Ok(self.value_type_by_oid(oid)?.is_some())
108    }
109
110    /// Current SQL spelling of an admitted catalog OID alias; `None` retains numeric output.
111    fn value_regtype_output(&self, _ty: &crate::ColumnType, _oid: i64) -> Result<Option<String>> {
112        Ok(None)
113    }
114
115    /// The current descriptor of an admitted composite value.
116    fn value_composite_type(
117        &self,
118        _oid: u32,
119    ) -> Result<Option<Arc<super::composites::CompositeTypeDescriptor>>> {
120        Ok(None)
121    }
122
123    fn value_composite_type_with_control(
124        &self,
125        oid: u32,
126        control: &ProductionControl<'_>,
127    ) -> Result<Option<super::composites::OwnedCompositeTypeDescriptor>> {
128        control.check()?;
129        self.value_composite_type(oid)?
130            .map(|descriptor| {
131                super::composites::OwnedCompositeTypeDescriptor::from_produced(
132                    descriptor.clone_with_control(control)?,
133                    control,
134                )
135            })
136            .transpose()
137    }
138
139    /// The session's comparison support functions, shared by declared type across nested array and record calls. Pure catalog readers do not own runtime state.
140    fn enum_type_comparison_states(&self) -> Option<&EnumTypeComparisonStates> {
141        None
142    }
143
144    /// The labels of one enum type in the statement's catalog generation, or `None` when the catalog has no such type.
145    fn enum_type_labels(&self, type_oid: u32) -> Result<Option<Arc<EnumTypeLabels>>>;
146
147    /// Resolve an already admitted physical label OID across enum types. Output uses the label's actual identity even if a retained tuple now declares another enum type; it does not repeat input safety checks.
148    fn enum_value_by_oid(&self, _label_oid: u32) -> Result<Option<EnumValue>> {
149        Ok(None)
150    }
151
152    /// The actual enum type and zero-based label position of an admitted physical OID in this generation. Positions have declaration/key order and avoid copying label keys for comparison.
153    fn enum_label_position(&self, _label_oid: u32) -> Result<Option<(u32, usize)>> {
154        Ok(None)
155    }
156
157    /// Whether the current transaction added this label to a type that it did not create. `PostgreSQL` rejects such a label until the transaction commits.
158    fn enum_label_uncommitted(&self, label_oid: u32) -> bool;
159
160    /// `format_type_be` of the type, which qualifies a type hidden by the search path.
161    fn enum_type_name(&self, type_oid: u32) -> Result<Option<String>>;
162
163    /// Whether the statement catalog defines any enum type; binding skips enum literal validation otherwise.
164    fn has_enum_types(&self) -> bool;
165}
166
167/// Adapt a scalar context without requiring embedders that only provide domain or composite metadata to implement enum support.
168pub struct EngineValueCatalog<'a>(pub &'a dyn super::EngineHook);
169
170impl SQLValueCatalog for EngineValueCatalog<'_> {
171    fn compare_range_bounds(
172        &self,
173        range_oid: u32,
174        left: &Value,
175        right: &Value,
176        control: &ProductionControl<'_>,
177    ) -> Result<std::cmp::Ordering> {
178        self.0
179            .enum_labels()
180            .ok_or_else(|| {
181                super::SQLError::Internal("selected range comparison support is unavailable".into())
182            })?
183            .compare_range_bounds(range_oid, left, right, control)
184    }
185
186    fn range_bound_equality_key(
187        &self,
188        range_oid: u32,
189        value: &Value,
190        control: &ProductionControl<'_>,
191    ) -> Result<Produced<Vec<u8>>> {
192        self.0
193            .enum_labels()
194            .ok_or_else(|| {
195                super::SQLError::Internal(
196                    "selected range equality-key support is unavailable".into(),
197                )
198            })?
199            .range_bound_equality_key(range_oid, value, control)
200    }
201
202    fn value_range_type(
203        &self,
204        oid: u32,
205    ) -> Result<Option<Arc<super::range::RangeValueDescriptor>>> {
206        self.0
207            .enum_labels()
208            .map(|catalog| catalog.value_range_type(oid))
209            .transpose()
210            .map(Option::flatten)
211    }
212
213    fn value_regtype_output(&self, ty: &crate::ColumnType, oid: i64) -> Result<Option<String>> {
214        self.0
215            .resolve_regtype_output(ty, oid)
216            .map_err(crate::SQLError::Internal)
217    }
218
219    fn value_type_by_oid(&self, oid: u32) -> Result<Option<crate::ColumnType>> {
220        self.0
221            .resolve_type_oid(oid)
222            .map_err(crate::SQLError::Internal)
223    }
224
225    fn value_type_by_oid_with_control(
226        &self,
227        oid: u32,
228        control: &ProductionControl<'_>,
229    ) -> Result<Option<Produced<crate::ColumnType>>> {
230        self.0.resolve_type_oid_with_control(oid, control)
231    }
232
233    fn value_type_exists(&self, oid: u32) -> Result<bool> {
234        self.0
235            .type_oid_exists(oid)
236            .map_err(crate::SQLError::Internal)
237    }
238
239    fn value_composite_type(
240        &self,
241        oid: u32,
242    ) -> Result<Option<Arc<super::composites::CompositeTypeDescriptor>>> {
243        self.0
244            .composite_types()
245            .map(|catalog| catalog.composite_type(oid))
246            .transpose()
247            .map(Option::flatten)
248    }
249
250    fn value_composite_type_with_control(
251        &self,
252        oid: u32,
253        control: &ProductionControl<'_>,
254    ) -> Result<Option<super::composites::OwnedCompositeTypeDescriptor>> {
255        control.check()?;
256        self.0
257            .composite_types()
258            .map(|catalog| catalog.composite_type_with_control(oid, control))
259            .transpose()
260            .map(Option::flatten)
261    }
262
263    fn enum_type_comparison_states(&self) -> Option<&EnumTypeComparisonStates> {
264        self.0.enum_labels()?.enum_type_comparison_states()
265    }
266
267    fn enum_type_labels(&self, oid: u32) -> Result<Option<Arc<EnumTypeLabels>>> {
268        self.0
269            .enum_labels()
270            .map(|catalog| catalog.enum_type_labels(oid))
271            .transpose()
272            .map(Option::flatten)
273    }
274
275    fn enum_value_by_oid(&self, oid: u32) -> Result<Option<EnumValue>> {
276        self.0
277            .enum_labels()
278            .map(|catalog| catalog.enum_value_by_oid(oid))
279            .transpose()
280            .map(Option::flatten)
281    }
282
283    fn enum_label_position(&self, oid: u32) -> Result<Option<(u32, usize)>> {
284        self.0
285            .enum_labels()
286            .map(|catalog| catalog.enum_label_position(oid))
287            .transpose()
288            .map(Option::flatten)
289    }
290
291    fn enum_label_uncommitted(&self, oid: u32) -> bool {
292        self.0
293            .enum_labels()
294            .is_some_and(|catalog| catalog.enum_label_uncommitted(oid))
295    }
296
297    fn enum_type_name(&self, oid: u32) -> Result<Option<String>> {
298        self.0
299            .enum_labels()
300            .map(|catalog| catalog.enum_type_name(oid))
301            .transpose()
302            .map(Option::flatten)
303    }
304
305    fn has_enum_types(&self) -> bool {
306        self.0
307            .enum_labels()
308            .is_some_and(SQLValueCatalog::has_enum_types)
309    }
310}