Skip to main content

uqa_sql/expr/composites/constructor/
state.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! One admitted name descriptor per prepared composite constructor.
8
9use crate::{expr::composites::CompositeTypeDescriptor, SQLError};
10use std::sync::OnceLock;
11use uqa_core::{
12    memory::{Produced, ProductionControl},
13    RecordDescriptor, ValueRetentionError,
14};
15
16#[derive(Debug, Default)]
17pub struct CompositeConstructorState {
18    descriptor: OnceLock<Produced<RecordDescriptor>>,
19}
20
21impl CompositeConstructorState {
22    pub(super) fn shared(&self, current: &CompositeTypeDescriptor) -> Option<RecordDescriptor> {
23        let saved = self.descriptor.get()?;
24        (saved.type_oid() == Some(current.type_oid)
25            && saved.field_names().iter().map(String::as_str).eq(current
26                .attributes
27                .iter()
28                .map(|attribute| attribute.name.as_str())))
29        .then(|| (**saved).clone())
30    }
31
32    pub(super) fn remember(
33        &self,
34        descriptor: &RecordDescriptor,
35        control: &ProductionControl<'_>,
36    ) -> Result<(), SQLError> {
37        if self.descriptor.get().is_none() {
38            // Cache admission is optional; failure must not reject an already
39            // produced row. Cancellation remains an error, never a cache miss.
40            match control.reserve(descriptor.retained_payload_bytes()?) {
41                Ok(memory) => {
42                    let _ = self
43                        .descriptor
44                        .set(control.finish(descriptor.clone(), memory)?);
45                }
46                Err(ValueRetentionError::Memory(_)) => {}
47                Err(error) => return Err(error.into()),
48            }
49        }
50        Ok(())
51    }
52}