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