Skip to main content

uqa_sql/expr/value_catalog/
records.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Borrowed record fields retain the statement's descriptor for SQL consumers.
8
9use super::{Arc, SQLValueCatalog};
10use crate::{
11    catalog::type_metadata::pg_type_oid, expr::composites::CompositeTypeDescriptor, ColumnType,
12    SQLError,
13};
14use uqa_core::{RecordFieldType, Value};
15
16enum Fields<'a> {
17    Named(&'a uqa_core::RecordValue),
18    Anonymous(&'a uqa_core::RowValue),
19}
20
21/// Record values and declared field identities from one pinned catalog generation. Constructing the view does not read or copy any field value.
22pub struct SQLRecordFields<'a> {
23    fields: Fields<'a>,
24    descriptor: Option<Arc<CompositeTypeDescriptor>>,
25}
26
27impl<'a> SQLRecordFields<'a> {
28    pub fn new(value: &'a Value, catalog: Option<&dyn SQLValueCatalog>) -> Result<Self, SQLError> {
29        let (fields, oid) = match value {
30            Value::Record(record) => (Fields::Named(record), record.type_oid()),
31            Value::Row(row) => (Fields::Anonymous(row), None),
32            _ => {
33                return Err(SQLError::Internal(
34                    "record field view requires a record value".into(),
35                ))
36            }
37        };
38        let descriptor = oid
39            .map(|oid| {
40                catalog
41                    .ok_or_else(|| {
42                        SQLError::Internal("named record comparison has no catalog".into())
43                    })?
44                    .value_composite_type(oid)?
45                    .ok_or_else(|| SQLError::Routine {
46                        sqlstate: "42704".into(),
47                        message: format!("type with OID {oid} does not exist"),
48                    })
49            })
50            .transpose()?;
51        Ok(Self { fields, descriptor })
52    }
53
54    pub fn value(&self, index: usize) -> Option<&'a Value> {
55        match self.fields {
56            Fields::Named(fields) => fields.get(index).map(|(_, value)| value),
57            Fields::Anonymous(fields) => fields.get(index),
58        }
59    }
60
61    pub fn declared_field_type(&self, index: usize) -> Option<&ColumnType> {
62        self.descriptor
63            .as_ref()?
64            .attributes
65            .get(index)
66            .map(|attribute| &attribute.ty)
67    }
68
69    /// Observe a retained field selection without evaluating the field. Named fields use the pinned descriptor; anonymous fields distinguish explicit zero from absent legacy metadata.
70    pub fn field_collation_oid(&self, index: usize) -> Option<u32> {
71        if let Some(descriptor) = &self.descriptor {
72            return descriptor
73                .attributes
74                .get(index)
75                .map(|attribute| attribute.collation_oid());
76        }
77        match self.fields {
78            Fields::Anonymous(fields) => fields.field_types()?.get(index)?.collation_oid,
79            Fields::Named(_) => None,
80        }
81    }
82
83    pub fn field_type_oid(&self, index: usize) -> Option<u32> {
84        if let Some(ty) = self.declared_field_type(index) {
85            return Some(pg_type_oid(ty) as u32);
86        }
87        match self.fields {
88            Fields::Anonymous(fields) => fields
89                .field_types()?
90                .get(index)
91                .map(|RecordFieldType { oid, .. }| *oid),
92            Fields::Named(_) => None,
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::expr::{composites::CompositeAttribute, enums::EnumTypeLabels};
101    use std::cell::RefCell;
102
103    struct Catalog(RefCell<Arc<CompositeTypeDescriptor>>);
104
105    impl SQLValueCatalog for Catalog {
106        fn value_composite_type(
107            &self,
108            _: u32,
109        ) -> Result<Option<Arc<CompositeTypeDescriptor>>, SQLError> {
110            Ok(Some(self.0.borrow().clone()))
111        }
112        fn enum_type_labels(&self, _: u32) -> Result<Option<Arc<EnumTypeLabels>>, SQLError> {
113            Ok(None)
114        }
115        fn enum_label_uncommitted(&self, _: u32) -> bool {
116            false
117        }
118        fn enum_type_name(&self, _: u32) -> Result<Option<String>, SQLError> {
119            Ok(None)
120        }
121        fn has_enum_types(&self) -> bool {
122            false
123        }
124    }
125
126    #[test]
127    fn field_collations_keep_named_generations_and_anonymous_zero() {
128        let descriptor = |collation_oid| {
129            Arc::new(CompositeTypeDescriptor {
130                dropped: Vec::new(),
131                type_oid: 20_001,
132                relation_oid: 20_002,
133                attributes: vec![CompositeAttribute {
134                    name: "v".into(),
135                    ty: ColumnType::Text,
136                    collation_oid,
137                    number: 1,
138                }],
139            })
140        };
141        let catalog = Catalog(RefCell::new(descriptor(Some(950))));
142        let value = Value::Record(uqa_core::RecordValue::from_parts(
143            vec![("v".into(), Value::Null)],
144            Some(20_001),
145        ));
146        let original = SQLRecordFields::new(&value, Some(&catalog)).unwrap();
147        *catalog.0.borrow_mut() = descriptor(Some(963));
148        let changed = SQLRecordFields::new(&value, Some(&catalog)).unwrap();
149        assert_eq!(original.field_collation_oid(0), Some(950));
150        assert_eq!(changed.field_collation_oid(0), Some(963));
151        assert_eq!(original.field_collation_oid(1), None);
152        *catalog.0.borrow_mut() = descriptor(None);
153        assert_eq!(
154            SQLRecordFields::new(&value, Some(&catalog))
155                .unwrap()
156                .field_collation_oid(0),
157            Some(100)
158        );
159
160        let anonymous = Value::Row(
161            uqa_core::RowValue::typed(
162                vec![Value::Null; 3],
163                [None, Some(0), Some(950)]
164                    .into_iter()
165                    .map(|collation_oid| RecordFieldType {
166                        oid: 25,
167                        type_modifier: -1,
168                        collation_oid,
169                    })
170                    .collect(),
171            )
172            .unwrap(),
173        );
174        let fields = SQLRecordFields::new(&anonymous, None).unwrap();
175        assert_eq!(fields.field_collation_oid(0), None);
176        assert_eq!(fields.field_collation_oid(1), Some(0));
177        assert_eq!(fields.field_collation_oid(2), Some(950));
178    }
179}