Skip to main content

uqa_sql/binding/
statements.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Executable statement schemas and mutation parameter analysis.
8
9use super::BindingContext;
10use crate::{
11    plan::{CommandPlan, UnifiedPlan},
12    routines::RoutineResolution,
13    RowSchema, SQLError, SQLParam, ScalarExpr,
14};
15use uqa_core::Value;
16
17/// Borrow binding inputs only when the statement's semantic branch requires them.
18pub trait StatementBindingScope {
19    fn binding_context(&self) -> Result<BindingContext<'_>, SQLError>;
20
21    fn binding_context_with_control(
22        &self,
23        control: &uqa_core::memory::ProductionControl<'_>,
24    ) -> Result<super::production::ControlledBindingContext<'_>, SQLError> {
25        self.binding_context()?.copy_with_control(control)
26    }
27}
28pub type StatementAnalysisOperation<'a> =
29    &'a mut dyn FnMut(&dyn StatementBindingScope) -> Result<(), SQLError>;
30
31pub type ControlledStatementAnalysisOperation<'a> =
32    &'a mut dyn FnMut(super::production::ControlledBindingContext<'_>) -> Result<(), SQLError>;
33
34/// Retain a fresh catalog, namespace and transition scope for each statement analysis.
35pub trait StatementAnalysisScopes {
36    /// Request ownership precedes analysis; optimizer catalog callbacks remain after successful analysis.
37    fn planning_control(&self) -> Result<uqa_core::memory::OwnedProductionControl, SQLError> {
38        Ok(uqa_core::memory::ProductionControl::uncontrolled().capture())
39    }
40
41    fn with_scope(&self, analyze: StatementAnalysisOperation<'_>) -> Result<(), SQLError>;
42
43    /// Native scopes construct their retained inputs under the caller's control; external factories preserve their scope callback.
44    fn with_controlled_scope(
45        &self,
46        control: &uqa_core::memory::ProductionControl<'_>,
47        analyze: ControlledStatementAnalysisOperation<'_>,
48    ) -> Result<(), SQLError> {
49        control.check()?;
50        self.with_scope(&mut |scope| analyze(scope.binding_context_with_control(control)?))
51    }
52}
53
54/// A nested command retains its enclosing CTE bindings while the session supplies fresh statement metadata and admission.
55pub struct InheritedStatementAnalysisScopes<'a> {
56    pub current: &'a dyn StatementAnalysisScopes,
57    pub parent: &'a dyn StatementBindingScope,
58}
59
60impl StatementAnalysisScopes for InheritedStatementAnalysisScopes<'_> {
61    fn planning_control(&self) -> Result<uqa_core::memory::OwnedProductionControl, SQLError> {
62        self.current.planning_control()
63    }
64
65    fn with_controlled_scope(
66        &self,
67        control: &uqa_core::memory::ProductionControl<'_>,
68        analyze: ControlledStatementAnalysisOperation<'_>,
69    ) -> Result<(), SQLError> {
70        self.current
71            .with_controlled_scope(control, &mut |mut binding| {
72                let parent = self.parent.binding_context_with_control(control)?;
73                binding.ctes = parent.ctes;
74                binding.deferred_ctes = parent.deferred_ctes;
75                binding.non_returning_ctes = parent.non_returning_ctes;
76                analyze(binding)
77            })
78    }
79
80    fn with_scope(&self, analyze: StatementAnalysisOperation<'_>) -> Result<(), SQLError> {
81        self.current.with_scope(&mut |scope| {
82            let mut binding = super::snapshot::BindingSnapshot::from(scope.binding_context()?);
83            let parent = super::snapshot::BindingSnapshot::from(self.parent.binding_context()?);
84            binding.inherit_cte_bindings(&parent);
85            analyze(&binding)
86        })
87    }
88}
89pub struct StatementAnalysisContext<'a> {
90    pub scopes: &'a dyn StatementAnalysisScopes,
91    pub routines: &'a dyn RoutineResolution,
92    pub aliases: &'a dyn crate::schema::dependencies::oid_alias::OidAliasInput,
93}
94
95/// The result a statement's analysis derives: the column types of a query or of a data-modifying statement's `RETURNING` list, `None` where analysis derives no type, or no result for any other statement.
96#[derive(Debug, Clone, PartialEq)]
97pub enum AnalyzedResult {
98    Rows(Vec<Option<crate::ColumnType>>),
99    /// An analyzed output whose anonymous records retain their field descriptors.
100    Schema(RowSchema),
101    Command,
102}
103
104impl AnalyzedResult {
105    pub fn column_types(&self) -> Option<&[Option<crate::ColumnType>]> {
106        match self {
107            Self::Rows(types) => Some(types),
108            Self::Schema(schema) => Some(schema.column_types()),
109            Self::Command => None,
110        }
111    }
112
113    pub fn record_fields(&self, column: usize) -> Option<&crate::schema::RecordFields> {
114        match self {
115            Self::Schema(schema) => schema.record_fields(column),
116            _ => None,
117        }
118    }
119}
120
121impl StatementBindingScope for super::snapshot::BindingSnapshot {
122    fn binding_context(&self) -> Result<BindingContext<'_>, SQLError> {
123        Ok(self.context())
124    }
125}
126
127pub fn analyze_executable_plan(
128    context: &StatementAnalysisContext<'_>,
129    plan: &mut UnifiedPlan,
130    params: &[SQLParam],
131) -> Result<AnalyzedResult, SQLError> {
132    analyze_executable_plan_for_cache(context, plan, params).map(|(result, _)| result)
133}
134
135mod procedural;
136mod production;
137pub use procedural::{
138    analyze_procedural_plan, analyze_procedural_plan_owned, OwnedProceduralPlanAnalysis,
139    ProceduralPlanAnalysis,
140};
141pub use production::analyze_reusable_inputs_owned;
142mod cache;
143pub use cache::{analyze_for_statement_reuse, AnalyzedStatement};
144
145/// Analyze once and report whether the converted inputs can be reused by a later
146/// ordinary message. Prepared definitions use their separate creation lifetime.
147pub fn analyze_executable_plan_for_cache(
148    context: &StatementAnalysisContext<'_>,
149    plan: &mut UnifiedPlan,
150    params: &[SQLParam],
151) -> Result<(AnalyzedResult, bool), SQLError> {
152    analyze_reusable_inputs(context, plan, params)
153        .map(|(result, reusable)| (result, reusable && params.is_empty()))
154}
155
156/// Analyze in the selected scope and report whether immutable input conversions can survive ordinary messages. Callers capture optimizer resources only after successful analysis, then retain reusable syntax through `AnalyzedStatement`.
157pub fn analyze_reusable_inputs(
158    context: &StatementAnalysisContext<'_>,
159    plan: &mut UnifiedPlan,
160    params: &[SQLParam],
161) -> Result<(AnalyzedResult, bool), SQLError> {
162    let mut result = None;
163    let mut reusable = true;
164    context.scopes.with_scope(&mut |scope| {
165        result = Some(match plan {
166            UnifiedPlan::Command(command) => match command.as_mut() {
167                // The explained statement retains a scope of its own.
168                CommandPlan::Explain { .. } => {
169                    let mut explained = None;
170                    context.scopes.with_scope(&mut |scope| {
171                        explained = Some(analyze_plan_result_inner(
172                            context.routines,
173                            context.aliases,
174                            plan,
175                            params,
176                            scope,
177                            &mut reusable,
178                        )?);
179                        Ok(())
180                    })?;
181                    explained.ok_or_else(|| {
182                        SQLError::Internal("EXPLAIN analysis scope did not run".into())
183                    })?
184                }
185                _ => analyze_plan_result_inner(
186                    context.routines,
187                    context.aliases,
188                    plan,
189                    params,
190                    scope,
191                    &mut reusable,
192                )?,
193            },
194            UnifiedPlan::Query(_) => analyze_plan_result_inner(
195                context.routines,
196                context.aliases,
197                plan,
198                params,
199                scope,
200                &mut reusable,
201            )?,
202        });
203        Ok(())
204    })?;
205    result
206        .map(|result| (result, reusable))
207        .ok_or_else(|| SQLError::Internal("statement analysis scope did not run".into()))
208}
209
210/// Analyze a statement in one binding scope, retain input-function results in its
211/// executable tree and derive its result without running statement expressions.
212pub fn analyze_plan_result(
213    routines: &dyn RoutineResolution,
214    aliases: &dyn crate::schema::dependencies::oid_alias::OidAliasInput,
215    plan: &mut UnifiedPlan,
216    params: &[SQLParam],
217    scope: &dyn StatementBindingScope,
218) -> Result<AnalyzedResult, SQLError> {
219    analyze_plan_result_inner(routines, aliases, plan, params, scope, &mut true)
220}
221
222fn analyze_plan_result_inner(
223    routines: &dyn RoutineResolution,
224    aliases: &dyn crate::schema::dependencies::oid_alias::OidAliasInput,
225    plan: &mut UnifiedPlan,
226    params: &[SQLParam],
227    scope: &dyn StatementBindingScope,
228    reusable: &mut bool,
229) -> Result<AnalyzedResult, SQLError> {
230    if let UnifiedPlan::Command(command) = plan {
231        if let CommandPlan::Explain {
232            body,
233            options,
234            unbound_parameters,
235        } = command.as_mut()
236        {
237            if params.is_empty() && options.infers_unbound_parameters()? {
238                let (parameters, body_reusable) = super::preparation::read_generic_explain_inputs(
239                    routines,
240                    body,
241                    &scope.binding_context()?,
242                    aliases,
243                )?;
244                *unbound_parameters = Some(parameters);
245                *reusable &= body_reusable;
246            } else {
247                *unbound_parameters = None;
248                analyze_plan_result_inner(routines, aliases, body, params, scope, reusable)?;
249            }
250            return options.result_schema().map(AnalyzedResult::Schema);
251        }
252    }
253    let binding = scope.binding_context()?;
254    let analysis =
255        super::preparation::read_executable_inputs(routines, plan, params, &binding, aliases)?;
256    *reusable &= analysis.reusable;
257    Ok(analysis.result)
258}
259
260pub fn analyze_command_parameters(
261    routines: &dyn RoutineResolution,
262    command: &CommandPlan,
263    params: &[SQLParam],
264    scope: &dyn StatementBindingScope,
265) -> Result<(), SQLError> {
266    let declared = parameter_input_types(params)?;
267    super::infer_prepared_parameter_types(
268        routines,
269        &UnifiedPlan::Command(Box::new(command.clone())),
270        &declared,
271        &scope.binding_context()?,
272    )?;
273    Ok(())
274}
275
276pub(super) fn parameter_input_types(
277    params: &[SQLParam],
278) -> Result<Vec<Option<crate::ColumnType>>, SQLError> {
279    let schema = RowSchema::default();
280    (1..=params.len())
281        .map(|index| match &params[index - 1] {
282            SQLParam::Scalar(Value::Str(_) | Value::Null) => Ok(None),
283            _ => crate::scalar_type(&ScalarExpr::Param(index), &schema, params),
284        })
285        .collect()
286}
287
288#[cfg(test)]
289mod tests;