Skip to main content

uqa_sql/expr/
composites.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Composite type values through the statement's catalog: attribute metadata, `record_in` input and the coercion of rows and records to a composite type.
8//!
9//! Logical composite fields use [`Value::Record`]; admitted input and retained tuples use [`Value::Datum`] so later catalog changes interpret their original physical layout. Anonymous row constructors are [`Value::Row`] until a coercion gives them a composite type.
10
11use std::sync::Arc;
12
13use uqa_core::Value;
14
15use super::{EngineHook, Result, SQLError};
16use crate::ast::ColumnType;
17
18#[cfg(test)]
19mod assignment_tests;
20mod changes;
21pub mod constants;
22pub mod constructor;
23pub(crate) mod datum;
24mod descriptor;
25pub(super) mod fields;
26mod input;
27pub mod literal;
28pub(crate) mod retained;
29mod retention;
30pub use changes::{apply_attribute_change, type_contains_composite, AttributeChange};
31pub use input::parse_record_fields;
32pub use retained::CompositeConstantSource;
33pub use retention::{flatten_value_with_control, retain_value_with_control};
34
35/// Classify an admitted physical value without reading its payload or invoking input.
36pub fn datum_is_composite(
37    datum: &uqa_core::DatumValue,
38    engine: &dyn super::EngineHook,
39) -> Result<bool> {
40    if datum.record_fields().is_some() {
41        return Ok(true);
42    }
43    let ty = engine
44        .resolve_type_oid(datum.type_oid())
45        .map_err(SQLError::Internal)?;
46    let mut ty = ty.as_ref();
47    while let Some(ColumnType::Domain { base, .. }) = ty {
48        ty = Some(base);
49    }
50    Ok(matches!(
51        ty,
52        Some(ColumnType::Composite(_) | ColumnType::Record)
53    ))
54}
55
56/// One live attribute of a composite type in attribute-number order.
57#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
58pub struct CompositeAttribute {
59    pub name: String,
60    pub ty: ColumnType,
61    /// Selected declaration identity; absent metadata uses the attribute type's default.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub collation_oid: Option<u32>,
64    /// `pg_attribute.attnum`, which dropped attributes keep occupying.
65    pub number: i16,
66}
67
68impl CompositeAttribute {
69    #[must_use]
70    pub fn collation_oid(&self) -> u32 {
71        self.collation_oid.unwrap_or_else(|| {
72            u32::try_from(crate::catalog::type_metadata::pg_type_collation_oid(
73                &self.ty,
74            ))
75            .expect("type collation identity")
76        })
77    }
78}
79
80/// The live attributes of one composite type in the statement's catalog generation.
81#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
82pub struct CompositeTypeDescriptor {
83    /// Physical slots left by removed attributes, without retaining a type dependency.
84    #[serde(default, skip_serializing_if = "Vec::is_empty")]
85    pub dropped: Vec<DroppedCompositeAttribute>,
86    pub type_oid: u32,
87    pub relation_oid: u32,
88    pub attributes: Vec<CompositeAttribute>,
89}
90
91/// Width and alignment remain necessary when a retained tuple contains a removed field.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
93pub struct DroppedCompositeAttribute {
94    pub number: i16,
95    pub length: i64,
96    pub alignment: u8,
97}
98
99impl DroppedCompositeAttribute {
100    pub fn from_type(number: i16, ty: &ColumnType) -> Self {
101        Self {
102            number,
103            length: crate::catalog::type_metadata::pg_type_len(ty),
104            alignment: crate::catalog::type_metadata::pg_type_align(ty).as_bytes()[0],
105        }
106    }
107}
108
109impl CompositeTypeDescriptor {
110    /// Number of physical positions, including trailing dropped attributes.
111    pub fn physical_width(&self) -> i16 {
112        self.attributes
113            .iter()
114            .map(|attribute| attribute.number)
115            .chain(self.dropped.iter().map(|attribute| attribute.number))
116            .max()
117            .unwrap_or(0)
118    }
119
120    pub fn attribute(&self, name: &str) -> Option<(usize, &CompositeAttribute)> {
121        self.attributes
122            .iter()
123            .enumerate()
124            .find(|(_, attribute)| attribute.name == name)
125    }
126}
127
128/// Catalog access for composite values, supplied by the statement's execution context and by catalog-aware binding.
129pub trait CompositeTypeCatalog {
130    /// The attributes of one composite type, or `None` when the catalog has no such type.
131    fn composite_type(&self, type_oid: u32) -> Result<Option<Arc<CompositeTypeDescriptor>>>;
132}
133
134/// The attributes of a composite type the statement's catalog must contain.
135pub fn descriptor(
136    catalog: Option<&dyn CompositeTypeCatalog>,
137    type_oid: u32,
138) -> Result<Arc<CompositeTypeDescriptor>> {
139    let catalog = catalog
140        .ok_or_else(|| SQLError::Internal("composite type catalog is unavailable".into()))?;
141    catalog
142        .composite_type(type_oid)?
143        .ok_or_else(|| SQLError::Routine {
144            sqlstate: "42704".into(),
145            message: format!("type with OID {type_oid} does not exist"),
146        })
147}
148
149/// `ExecEvalFieldSelect` checks the current attribute OID against the prepared result type. Call only after evaluating a non-NULL record and checking the dropped marker.
150pub fn validate_field_result(field: &crate::ast::CompositeFieldBinding) -> Result<()> {
151    let Some(current) = &field.changed_type else {
152        return Ok(());
153    };
154    validate_field_type(field, current)
155}
156
157pub(super) fn validate_field_type(
158    field: &crate::ast::CompositeFieldBinding,
159    current: &ColumnType,
160) -> Result<()> {
161    if crate::catalog::type_metadata::pg_type_oid(current)
162        == crate::catalog::type_metadata::pg_type_oid(&field.result_type)
163    {
164        return Ok(());
165    }
166    Err(SQLError::Diagnostic {
167        sqlstate: "42804".into(),
168        message: format!("attribute {} has wrong type", field.number),
169        detail: Some(format!(
170            "Table has type {}, but query expects {}.",
171            current.display_name(),
172            field.result_type.display_name(),
173        )),
174        hint: None,
175    })
176}
177
178fn cannot_cast(source: &str, target: &str, detail: Option<String>) -> SQLError {
179    SQLError::Diagnostic {
180        sqlstate: "42846".into(),
181        message: format!("cannot cast type {source} to {target}"),
182        detail,
183        hint: None,
184    }
185}
186
187fn string_category(ty: &ColumnType) -> bool {
188    match ty {
189        ColumnType::Text
190        | ColumnType::Varchar(_)
191        | ColumnType::Bpchar
192        | ColumnType::Character(_)
193        | ColumnType::Name => true,
194        ColumnType::Domain { base, .. } => string_category(base),
195        _ => false,
196    }
197}
198
199/// Convert one attribute's text with the attribute type's input function and type modifier, which rejects a value too long for its declared length instead of truncating it as an explicit cast does. A NULL field still reaches a domain's input function, which enforces the domain's NOT NULL constraint.
200fn attribute_input(
201    engine: &dyn EngineHook,
202    text: Option<String>,
203    ty: &ColumnType,
204) -> Result<Value> {
205    let value = text.map_or(Value::Null, Value::Str);
206    if matches!(value, Value::Null) && !matches!(ty, ColumnType::Domain { .. }) {
207        return Ok(Value::Null);
208    }
209    if crate::assignment::conversion::type_requires_catalog_resolution(ty) {
210        return super::cast_value_with_type_resolution(
211            &value,
212            Some("unknown"),
213            &ty.catalog_name(),
214            Some(engine),
215        );
216    }
217    crate::assignment::conversion::convert_value_to_column_type(value, ty)
218}
219
220/// `record_in` for a composite type: the fields are split and each is converted in order, so a field's input error precedes a later structural error.
221pub fn composite_from_text(engine: &dyn EngineHook, text: &str, type_oid: u32) -> Result<Value> {
222    let descriptor = descriptor(engine.composite_types(), type_oid)?;
223    let mut fields = Vec::with_capacity(descriptor.attributes.len());
224    parse_record_fields(text, descriptor.attributes.len(), |index, field| {
225        let attribute = &descriptor.attributes[index];
226        fields.push((
227            attribute.name.clone(),
228            attribute_input(engine, field, &attribute.ty)?,
229        ));
230        Ok(())
231    })?;
232    let record = uqa_core::RecordValue::from_parts(fields, Some(type_oid));
233    retention::retain_record(
234        &record,
235        &descriptor,
236        engine.composite_types(),
237        &uqa_core::memory::ProductionControl::uncontrolled(),
238    )?
239    .into_uncontrolled()
240    .map_err(|_| SQLError::Internal("ordinary composite input retention".into()))
241}
242
243/// Coerce the fields of an anonymous row to a composite type position by position, as `coerce_record_to_complex` does. The field count must match the live attributes.
244fn composite_from_fields(
245    engine: &dyn EngineHook,
246    values: &[Value],
247    field_types: Option<&[uqa_core::RecordFieldType]>,
248    descriptor: &CompositeTypeDescriptor,
249    target: &str,
250) -> Result<Value> {
251    if values.len() != descriptor.attributes.len() {
252        let detail = if values.len() < descriptor.attributes.len() {
253            "Input has too few columns."
254        } else {
255            "Input has too many columns."
256        };
257        return Err(cannot_cast("record", target, Some(detail.into())));
258    }
259    let fields = values
260        .iter()
261        .zip(&descriptor.attributes)
262        .enumerate()
263        .map(|(index, (value, attribute))| {
264            let source = field_types
265                .and_then(|types| types.get(index))
266                .filter(|field| field.oid != 705)
267                .map(|field| {
268                    if let Some(ty) = crate::catalog::type_metadata::builtin_scalar_type(field.oid)
269                    {
270                        return Ok(ty.clone());
271                    }
272                    if let Some(element) =
273                        crate::catalog::type_metadata::builtin_array_element(field.oid)
274                    {
275                        return Ok(ColumnType::Array(Box::new(element.clone())));
276                    }
277                    engine
278                        .resolve_type_oid(field.oid)
279                        .map_err(SQLError::Internal)?
280                        .ok_or_else(|| SQLError::Routine {
281                            sqlstate: "42704".into(),
282                            message: format!("type with OID {} does not exist", field.oid),
283                        })
284                })
285                .transpose()?
286                .map(|ty| ty.catalog_name());
287            let converted = super::cast_value_with_type_resolution(
288                value,
289                source.as_deref(),
290                &attribute.ty.catalog_name(),
291                Some(engine),
292            )?;
293            Ok((attribute.name.clone(), converted))
294        })
295        .collect::<Result<Vec<_>>>()?;
296    let record = uqa_core::RecordValue::from_parts(fields, Some(descriptor.type_oid));
297    retention::retain_record(
298        &record,
299        descriptor,
300        engine.composite_types(),
301        &uqa_core::memory::ProductionControl::uncontrolled(),
302    )?
303    .into_uncontrolled()
304    .map_err(|_| SQLError::Internal("ordinary record coercion retention".into()))
305}
306
307/// Cast a value to a composite type: the identity for a value of the same type, `record_in` for unknown literals and string-category sources, and attribute-wise coercion for anonymous rows and records. Returns `None` when the target is not a composite type.
308pub fn cast_to_composite(
309    engine: &dyn EngineHook,
310    value: &Value,
311    source: Option<&ColumnType>,
312    target: &ColumnType,
313) -> Result<Option<Value>> {
314    let ColumnType::Composite(reference) = target else {
315        return Ok(None);
316    };
317    let target_name = || target.display_name();
318    match (value, source) {
319        (Value::Null, _) => Ok(Some(Value::Null)),
320        (Value::Str(text) | Value::FixedChar(text), source)
321            if source.is_none_or(string_category) =>
322        {
323            composite_from_text(engine, text, reference.oid).map(Some)
324        }
325        (Value::Record(fields), Some(ColumnType::Composite(source)))
326            if source.oid == reference.oid =>
327        {
328            Ok(Some(Value::Record(fields.clone().with_type_oid(Some(
329                fields.type_oid().unwrap_or(source.oid),
330            )))))
331        }
332        (Value::Datum(_), Some(ColumnType::Composite(source))) if source.oid == reference.oid => {
333            Ok(Some(value.clone()))
334        }
335        (Value::Record(_) | Value::Row(_), Some(source @ ColumnType::Composite(_))) => {
336            Err(cannot_cast(&source.display_name(), &target_name(), None))
337        }
338        (Value::Row(values), _) => {
339            let descriptor = descriptor(engine.composite_types(), reference.oid)?;
340            composite_from_fields(
341                engine,
342                values,
343                values.field_types(),
344                &descriptor,
345                &target_name(),
346            )
347            .map(Some)
348        }
349        (Value::Record(fields), _) => {
350            let descriptor = descriptor(engine.composite_types(), reference.oid)?;
351            let values = fields
352                .iter()
353                .map(|(_, value)| value.clone())
354                .collect::<Vec<_>>();
355            composite_from_fields(engine, &values, None, &descriptor, &target_name()).map(Some)
356        }
357        (_, source) => Err(cannot_cast(
358            &source.map_or_else(|| "unknown".into(), ColumnType::display_name),
359            &target_name(),
360            None,
361        )),
362    }
363}