Skip to main content

uqa_sql/expr/composites/
retained.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Original composite inputs shared by prepared plans and durable expression constants.
8
9use super::{descriptor, CompositeTypeDescriptor};
10use crate::{ColumnType, SQLError};
11use std::{collections::BTreeMap, sync::Arc};
12use uqa_core::Value;
13
14pub(crate) mod owners;
15pub(crate) mod production;
16mod tuple;
17pub(crate) use tuple::{
18    array_payload, array_payload_with_control, record_bytes, record_bytes_with_control,
19};
20
21#[cfg(test)]
22mod tests;
23
24pub(crate) type Descriptors = BTreeMap<u32, Arc<CompositeTypeDescriptor>>;
25
26impl super::CompositeTypeCatalog for Descriptors {
27    fn composite_type(&self, oid: u32) -> Result<Option<Arc<CompositeTypeDescriptor>>, SQLError> {
28        Ok(self.get(&oid).cloned())
29    }
30}
31
32/// The original admitted datum and its field types, retained independently of subsequent descriptor interpretations.
33#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
34pub struct CompositeConstantSource {
35    pub value: Value,
36    pub descriptors: Vec<CompositeTypeDescriptor>,
37}
38
39impl PartialEq for CompositeConstantSource {
40    fn eq(&self, other: &Self) -> bool {
41        self.descriptors == other.descriptors && self.value.has_same_representation(&other.value)
42    }
43}
44
45impl CompositeConstantSource {
46    pub(crate) fn capture(
47        value: &Value,
48        ty: &ColumnType,
49        catalog: Option<&dyn super::CompositeTypeCatalog>,
50        enums: Option<&dyn crate::expr::enums::EnumLabelCatalog>,
51    ) -> Result<Self, SQLError> {
52        let mut descriptors = Descriptors::new();
53        capture_type(ty, catalog, &mut descriptors)?;
54        Ok(Self {
55            value: crate::expr::enums::retain_enum_oids(enums, value)?,
56            descriptors: descriptors
57                .into_values()
58                .map(|value| value.as_ref().clone())
59                .collect(),
60        })
61    }
62
63    pub(crate) fn retain_enum_oids(
64        &mut self,
65        catalog: Option<&dyn crate::expr::enums::EnumLabelCatalog>,
66    ) -> Result<(), SQLError> {
67        if crate::expr::enums::has_missing_enum_oid(&self.value) {
68            self.value = crate::expr::enums::retain_enum_oids(catalog, &self.value)?;
69        }
70        Ok(())
71    }
72
73    pub(crate) fn project_type_change(
74        &self,
75        ty: &ColumnType,
76        target: u32,
77        name: &str,
78        to: &ColumnType,
79        catalog: &dyn super::CompositeTypeCatalog,
80    ) -> Result<Value, SQLError> {
81        let original = self
82            .descriptors
83            .iter()
84            .map(|descriptor| (descriptor.type_oid, Arc::new(descriptor.clone())))
85            .collect::<Descriptors>();
86        let mut current = Descriptors::new();
87        for oid in original.keys() {
88            if let Some(descriptor) = catalog.composite_type(*oid)? {
89                current.insert(*oid, descriptor);
90            }
91        }
92        if let Some(descriptor) = current.get_mut(&target) {
93            if let Some(attribute) = Arc::make_mut(descriptor)
94                .attributes
95                .iter_mut()
96                .find(|attribute| attribute.name == name)
97            {
98                attribute.ty = to.clone();
99            }
100        }
101        project_value(&self.value, ty, &original, &current, true)
102    }
103}
104
105pub(crate) fn capture_type(
106    ty: &ColumnType,
107    catalog: Option<&dyn super::CompositeTypeCatalog>,
108    output: &mut Descriptors,
109) -> Result<(), SQLError> {
110    match ty {
111        ColumnType::Domain { base, .. } | ColumnType::Array(base) => {
112            capture_type(base, catalog, output)
113        }
114        ColumnType::Composite(reference) => capture_descriptor(reference.oid, catalog, output),
115        _ => Ok(()),
116    }
117}
118
119pub(crate) fn capture_descriptor(
120    oid: u32,
121    catalog: Option<&dyn super::CompositeTypeCatalog>,
122    output: &mut Descriptors,
123) -> Result<(), SQLError> {
124    if output.contains_key(&oid) {
125        return Ok(());
126    }
127    let descriptor = descriptor(catalog, oid)?;
128    output.insert(oid, descriptor.clone());
129    for attribute in &descriptor.attributes {
130        capture_type(&attribute.ty, catalog, output)?;
131    }
132    Ok(())
133}
134
135pub(crate) fn project_value(
136    value: &Value,
137    ty: &ColumnType,
138    original: &Descriptors,
139    current: &Descriptors,
140    interpret_datums: bool,
141) -> Result<Value, SQLError> {
142    production::project_value_with_control(
143        value,
144        ty,
145        original,
146        current,
147        interpret_datums,
148        &uqa_core::memory::ProductionControl::uncontrolled(),
149    )
150    .map(|value| {
151        value
152            .into_uncontrolled()
153            .expect("ordinary composite projection")
154    })
155}