Skip to main content

uqa_sql/plan/
retained.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Shared immutable CTE declarations retain the admission of their copied payloads.
8
9use super::CtePlan;
10use crate::SQLError;
11use std::sync::Arc;
12use uqa_core::memory::{Produced, ProductionControl};
13
14#[derive(Debug, Clone)]
15pub struct RetainedCtePlan(Arc<Produced<CtePlan>>);
16
17impl RetainedCtePlan {
18    pub fn capture(plan: &CtePlan, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
19        Self::from_produced(plan.clone_with_control(control)?, control)
20    }
21
22    /// Retain an admitted declaration after preparation has attached shared analysis metadata. The Arc payload is admitted separately; reference-count bookkeeping follows the common shared-owner contract.
23    pub fn from_produced(
24        plan: Produced<CtePlan>,
25        control: &ProductionControl<'_>,
26    ) -> Result<Self, SQLError> {
27        let wrapper = control.reserve(size_of::<Produced<CtePlan>>())?;
28        let (plan, memory) = plan.into_parts();
29        let output = control.finish(plan, control.combine(memory, wrapper))?;
30        Ok(Self(Arc::new(output)))
31    }
32}
33
34impl From<CtePlan> for RetainedCtePlan {
35    fn from(plan: CtePlan) -> Self {
36        Self(Arc::new(
37            ProductionControl::uncontrolled()
38                .finish(plan, None)
39                .expect("uncontrolled CTE ownership"),
40        ))
41    }
42}
43
44impl AsRef<CtePlan> for RetainedCtePlan {
45    fn as_ref(&self) -> &CtePlan {
46        &self.0
47    }
48}
49
50impl std::ops::Deref for RetainedCtePlan {
51    type Target = CtePlan;
52    fn deref(&self) -> &CtePlan {
53        self.as_ref()
54    }
55}