Skip to main content

uqa_sql/expr/composites/
descriptor.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Retain a descriptor generation under the consumer's memory allowance.
8
9use super::{CompositeAttribute, CompositeTypeDescriptor};
10use uqa_core::{
11    memory::{Produced, ProductionControl, ProductionVec},
12    ValueRetentionError,
13};
14
15mod production;
16
17impl CompositeTypeDescriptor {
18    /// Capture an expanded record's field binding without reading any tuple payload. Dropped physical positions retain their original width and alignment.
19    pub fn expand_record_with_control(
20        &self,
21        value: &uqa_core::Value,
22        control: &ProductionControl<'_>,
23    ) -> Result<Produced<uqa_core::Value>, crate::SQLError> {
24        use crate::catalog::type_metadata::{
25            pg_type_align, pg_type_len, pg_type_modifier, pg_type_oid,
26        };
27        use uqa_core::{RecordDatumField, Value};
28        let Value::Datum(datum) = value else {
29            return Err(crate::SQLError::Internal(
30                "expanded record has no physical tuple".into(),
31            ));
32        };
33        if datum.record_fields().is_some() {
34            return Ok(control.copy_value(value)?);
35        }
36        let mut removed = ProductionVec::new(*control);
37        removed.extend_from_slice(&self.dropped)?;
38        removed
39            .as_mut_slice()
40            .sort_unstable_by_key(|attribute| attribute.number);
41        let mut dropped = removed.iter().peekable();
42        let mut live = self.attributes.iter().peekable();
43        let mut fields = ProductionVec::new(*control);
44        for number in 1..=self.physical_width() {
45            control.check()?;
46            let field = if let Some(attribute) =
47                live.peek().filter(|attribute| attribute.number == number)
48            {
49                let (name, memory) = control.copy_text(&attribute.name)?.into_parts();
50                let field = control.finish(
51                    RecordDatumField {
52                        name,
53                        type_oid: pg_type_oid(&attribute.ty) as u32,
54                        type_modifier: pg_type_modifier(&attribute.ty) as i32,
55                        collation_oid: attribute.collation_oid,
56                        length: pg_type_len(&attribute.ty),
57                        alignment: pg_type_align(&attribute.ty).as_bytes()[0],
58                        dropped: false,
59                    },
60                    memory,
61                )?;
62                live.next();
63                field
64            } else if let Some(attribute) = dropped
65                .peek()
66                .filter(|attribute| attribute.number == number)
67            {
68                let field = control.finish(
69                    RecordDatumField {
70                        name: String::new(),
71                        type_oid: 0,
72                        type_modifier: -1,
73                        collation_oid: None,
74                        length: attribute.length,
75                        alignment: attribute.alignment,
76                        dropped: true,
77                    },
78                    control.empty_reservation(),
79                )?;
80                dropped.next();
81                field
82            } else {
83                return Err(crate::SQLError::Internal(
84                    "expanded record descriptor is missing a physical attribute".into(),
85                ));
86            };
87            fields.push_produced(field)?;
88        }
89        let (datum, memory) = datum
90            .with_record_fields_with_control(fields.finish()?, control)?
91            .into_parts();
92        Ok(control.finish(Value::Datum(datum), memory)?)
93    }
94
95    /// Rebind a copied expanded record from its frozen field identities, without
96    /// observing tuple payloads or replacing them with the named type's new layout.
97    pub fn expanded_with_control(
98        datum: &uqa_core::DatumValue,
99        catalog: Option<&dyn crate::expr::SQLValueCatalog>,
100        control: &ProductionControl<'_>,
101    ) -> Result<Option<Produced<Self>>, crate::SQLError> {
102        let Some(fields) = datum.record_fields() else {
103            return Ok(None);
104        };
105        let mut attributes = ProductionVec::new(*control);
106        let mut dropped = ProductionVec::new(*control);
107        for (index, field) in fields.iter().enumerate() {
108            control.check()?;
109            let number = i16::try_from(index + 1)
110                .map_err(|_| crate::SQLError::Internal("invalid expanded record width".into()))?;
111            if field.dropped {
112                dropped.push_copy(super::DroppedCompositeAttribute {
113                    number,
114                    length: field.length,
115                    alignment: field.alignment,
116                })?;
117            } else {
118                let (ty, type_memory) = crate::expr::value_catalog::field_type_with_control(
119                    field.type_oid,
120                    field.type_modifier,
121                    catalog,
122                    control,
123                )?
124                .into_parts();
125                let (name, name_memory) = control.copy_text(&field.name)?.into_parts();
126                attributes.push_produced(control.finish(
127                    CompositeAttribute {
128                        name,
129                        ty,
130                        number,
131                        collation_oid: field.collation_oid,
132                    },
133                    control.combine(name_memory, type_memory),
134                )?)?;
135            }
136        }
137        let (attributes, memory) = attributes.finish()?.into_parts();
138        let (dropped, dropped_memory) = dropped.finish()?.into_parts();
139        Ok(Some(control.finish(
140            Self {
141                type_oid: datum.type_oid(),
142                relation_oid: 0,
143                attributes,
144                dropped,
145            },
146            control.combine(memory, dropped_memory),
147        )?))
148    }
149
150    pub fn clone_with_control(
151        &self,
152        control: &ProductionControl<'_>,
153    ) -> Result<Produced<Self>, ValueRetentionError> {
154        let mut attributes = ProductionVec::new(*control);
155        attributes.reserve(self.attributes.len())?;
156        for attribute in &self.attributes {
157            let (name, name_memory) = control.copy_text(&attribute.name)?.into_parts();
158            let (ty, type_memory) = attribute.ty.clone_with_control(control)?.into_parts();
159            attributes.push_produced(control.finish(
160                CompositeAttribute {
161                    name,
162                    ty,
163                    number: attribute.number,
164                    collation_oid: attribute.collation_oid,
165                },
166                control.combine(name_memory, type_memory),
167            )?)?;
168        }
169        let mut dropped = ProductionVec::new(*control);
170        dropped.extend_from_slice(&self.dropped)?;
171        let (attributes, memory) = attributes.finish()?.into_parts();
172        let (dropped, dropped_memory) = dropped.finish()?.into_parts();
173        control.finish(
174            Self {
175                attributes,
176                dropped,
177                type_oid: self.type_oid,
178                relation_oid: self.relation_oid,
179            },
180            control.combine(memory, dropped_memory),
181        )
182    }
183}