Skip to main content

uqa_sql/expr/composites/
ownership.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! A descriptor's admitted payload and its lease share one immutable lifetime.
8
9use super::{CompositeTypeCatalog, CompositeTypeDescriptor};
10use crate::SQLError;
11use std::sync::Arc;
12use uqa_core::memory::{Produced, ProductionControl};
13
14#[derive(Debug, Clone)]
15enum DescriptorOwner {
16    Retained(Arc<CompositeTypeDescriptor>),
17    Produced(Arc<Produced<CompositeTypeDescriptor>>),
18}
19
20/// A descriptor read shares either an existing immutable catalog generation or the newly admitted producer result. A produced descriptor cannot be extracted as a raw Arc that would discard its lease.
21#[derive(Debug, Clone)]
22pub struct OwnedCompositeTypeDescriptor(DescriptorOwner);
23
24impl OwnedCompositeTypeDescriptor {
25    /// Share metadata that an existing catalog owner already retains, without copying its attributes.
26    pub fn retained(descriptor: Arc<CompositeTypeDescriptor>) -> Self {
27        Self(DescriptorOwner::Retained(descriptor))
28    }
29
30    pub fn from_produced(
31        descriptor: Produced<CompositeTypeDescriptor>,
32        control: &ProductionControl<'_>,
33    ) -> Result<Self, SQLError> {
34        Ok(Self(DescriptorOwner::Produced(
35            descriptor.into_shared(control)?,
36        )))
37    }
38
39    /// The new payload charged to this producer; preexisting immutable catalog metadata is retained by its original owner.
40    pub fn reserved_bytes(&self) -> usize {
41        match &self.0 {
42            DescriptorOwner::Retained(_) => 0,
43            DescriptorOwner::Produced(descriptor) => descriptor.reserved_bytes(),
44        }
45    }
46}
47
48impl std::ops::Deref for OwnedCompositeTypeDescriptor {
49    type Target = CompositeTypeDescriptor;
50    fn deref(&self) -> &Self::Target {
51        match &self.0 {
52            DescriptorOwner::Retained(descriptor) => descriptor,
53            DescriptorOwner::Produced(descriptor) => descriptor,
54        }
55    }
56}
57
58pub fn descriptor_with_control(
59    catalog: Option<&dyn CompositeTypeCatalog>,
60    type_oid: u32,
61    control: &ProductionControl<'_>,
62) -> Result<OwnedCompositeTypeDescriptor, SQLError> {
63    control.check()?;
64    let catalog = catalog
65        .ok_or_else(|| SQLError::Internal("composite type catalog is unavailable".into()))?;
66    catalog
67        .composite_type_with_control(type_oid, control)?
68        .ok_or_else(|| SQLError::Routine {
69            sqlstate: "42704".into(),
70            message: format!("type with OID {type_oid} does not exist"),
71        })
72}
73
74#[cfg(test)]
75mod tests;