Skip to main content

uqa_sql/binding/statements/
cache.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Reusable SQL analysis keeps parameter types and converted immutable inputs, never invocation values or optimizer choices.
8
9use super::{analyze_reusable_inputs, StatementAnalysisContext};
10use crate::{plan::UnifiedPlan, ColumnType, SQLError, SQLParam};
11use std::sync::Arc;
12use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
13
14struct ParameterShape {
15    declared: bool,
16    resolved: Option<ColumnType>,
17}
18
19fn parameter_shapes(
20    params: &[SQLParam],
21    control: &ProductionControl<'_>,
22) -> Result<Option<Produced<Vec<ParameterShape>>>, SQLError> {
23    let mut shapes = ProductionVec::new(*control);
24    shapes.reserve(params.len())?;
25    for parameter in params {
26        let resolved = match crate::type_resolution::parameter_type_with_control(parameter, control)
27        {
28            Ok(resolved) => resolved,
29            Err(error)
30                if error.sqlstate() == Some("53200")
31                    || matches!(error.primary(), SQLError::Cancelled(_)) =>
32            {
33                return Err(error)
34            }
35            Err(_) => return Ok(None),
36        };
37        let (resolved, memory) = match resolved {
38            Some(resolved) => {
39                let (ty, memory) = resolved.into_parts();
40                (Some(ty), memory)
41            }
42            None => (None, control.empty_reservation()),
43        };
44        shapes.push_produced(control.finish(
45            ParameterShape {
46                declared: parameter.declared_scalar_type().is_some(),
47                resolved,
48            },
49            memory,
50        )?)?;
51    }
52    Ok(Some(shapes.finish()?))
53}
54
55/// Analyzed syntax with immutable input conversions and no optimized access paths. A caller must validate the original statement, catalog, namespace, authority and parser settings in the selected statement snapshot before offering this entry for reuse. Parameter values remain supplied by each execution; their inferred types and explicit declarations must still match.
56#[derive(Clone)]
57pub struct AnalyzedStatement(Arc<Produced<AnalyzedStorage>>);
58
59struct AnalyzedStorage {
60    plan: UnifiedPlan,
61    parameters: Vec<ParameterShape>,
62}
63
64impl AnalyzedStatement {
65    pub fn plan_for(&self, params: &[SQLParam]) -> Option<&UnifiedPlan> {
66        (params.len() == self.0.parameters.len()
67            && params
68                .iter()
69                .zip(&self.0.parameters)
70                .all(|(parameter, shape)| {
71                    parameter.declared_scalar_type().is_some() == shape.declared
72                        && crate::type_resolution::parameter_type_matches(
73                            parameter,
74                            shape.resolved.as_ref(),
75                        )
76                }))
77        .then_some(&self.0.plan)
78    }
79
80    /// Retain complete analyzed syntax and parameter declarations under the invoking request's allowance. All destinations are admitted before allocation; copying a published handle shares its immutable storage and lease.
81    pub fn capture_with_control(
82        plan: &UnifiedPlan,
83        params: &[SQLParam],
84        control: &ProductionControl<'_>,
85    ) -> Result<Option<Self>, SQLError> {
86        Self::capture_ref_with_control(plan.into(), params, control)
87    }
88
89    pub fn capture_ref_with_control(
90        plan: crate::plan::PlanRef<'_>,
91        params: &[SQLParam],
92        control: &ProductionControl<'_>,
93    ) -> Result<Option<Self>, SQLError> {
94        let Some(parameters) = parameter_shapes(params, control)? else {
95            return Ok(None);
96        };
97        let plan = plan.clone_with_control(control)?;
98        let (plan, memory) = plan.into_parts();
99        let (parameters, parameter_memory) = parameters.into_parts();
100        let storage = control.finish(
101            AnalyzedStorage { plan, parameters },
102            control.combine(memory, parameter_memory),
103        )?;
104        Ok(Some(Self(storage.into_shared(control)?)))
105    }
106
107    pub fn reserved_bytes(&self) -> usize {
108        self.0.reserved_bytes()
109    }
110
111    pub fn ptr_eq(&self, other: &Self) -> bool {
112        Arc::ptr_eq(&self.0, &other.0)
113    }
114}
115
116/// Analyze under the current caller's scope, then retain only inputs whose conversion lifetime spans ordinary messages. A parameter whose shape cannot be captured disables reuse without changing the original analysis's result or diagnostic order.
117pub fn analyze_for_statement_reuse(
118    context: &StatementAnalysisContext<'_>,
119    mut plan: UnifiedPlan,
120    params: &[SQLParam],
121) -> Result<(UnifiedPlan, Option<AnalyzedStatement>), SQLError> {
122    let (_, reusable) = analyze_reusable_inputs(context, &mut plan, params)?;
123    let retained = if reusable {
124        AnalyzedStatement::capture_with_control(&plan, params, &ProductionControl::uncontrolled())?
125    } else {
126        None
127    };
128    Ok((plan, retained))
129}