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}
21pub type StatementAnalysisOperation<'a> =
22    &'a mut dyn FnMut(&dyn StatementBindingScope) -> Result<(), SQLError>;
23
24/// Retain a fresh catalog, namespace and transition scope for each statement analysis.
25pub trait StatementAnalysisScopes {
26    fn with_scope(&self, analyze: StatementAnalysisOperation<'_>) -> Result<(), SQLError>;
27}
28
29/// A nested command retains its enclosing CTE bindings while the session supplies fresh statement metadata and admission.
30pub struct InheritedStatementAnalysisScopes<'a> {
31    pub current: &'a dyn StatementAnalysisScopes,
32    pub parent: &'a dyn StatementBindingScope,
33}
34
35impl StatementAnalysisScopes for InheritedStatementAnalysisScopes<'_> {
36    fn with_scope(&self, analyze: StatementAnalysisOperation<'_>) -> Result<(), SQLError> {
37        self.current.with_scope(&mut |scope| {
38            let mut binding = super::snapshot::BindingSnapshot::from(scope.binding_context()?);
39            let parent = super::snapshot::BindingSnapshot::from(self.parent.binding_context()?);
40            binding.inherit_cte_bindings(&parent);
41            analyze(&binding)
42        })
43    }
44}
45pub struct StatementAnalysisContext<'a> {
46    pub scopes: &'a dyn StatementAnalysisScopes,
47    pub routines: &'a dyn RoutineResolution,
48    pub aliases: &'a dyn crate::schema::dependencies::oid_alias::OidAliasInput,
49}
50
51/// 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.
52#[derive(Debug, Clone, PartialEq)]
53pub enum AnalyzedResult {
54    Rows(Vec<Option<crate::ColumnType>>),
55    /// An analyzed output whose anonymous records retain their field descriptors.
56    Schema(RowSchema),
57    Command,
58}
59
60impl AnalyzedResult {
61    pub fn column_types(&self) -> Option<&[Option<crate::ColumnType>]> {
62        match self {
63            Self::Rows(types) => Some(types),
64            Self::Schema(schema) => Some(schema.column_types()),
65            Self::Command => None,
66        }
67    }
68
69    pub fn record_fields(&self, column: usize) -> Option<&crate::schema::RecordFields> {
70        match self {
71            Self::Schema(schema) => schema.record_fields(column),
72            _ => None,
73        }
74    }
75}
76
77impl StatementBindingScope for super::snapshot::BindingSnapshot {
78    fn binding_context(&self) -> Result<BindingContext<'_>, SQLError> {
79        Ok(self.context())
80    }
81}
82
83pub fn analyze_executable_plan(
84    context: &StatementAnalysisContext<'_>,
85    plan: &mut UnifiedPlan,
86    params: &[SQLParam],
87) -> Result<AnalyzedResult, SQLError> {
88    analyze_executable_plan_for_cache(context, plan, params).map(|(result, _)| result)
89}
90
91mod procedural;
92pub use procedural::{analyze_procedural_plan, ProceduralPlanAnalysis};
93mod cache;
94pub use cache::{analyze_for_statement_reuse, AnalyzedStatement};
95
96/// Analyze once and report whether the converted inputs can be reused by a later
97/// ordinary message. Prepared definitions use their separate creation lifetime.
98pub fn analyze_executable_plan_for_cache(
99    context: &StatementAnalysisContext<'_>,
100    plan: &mut UnifiedPlan,
101    params: &[SQLParam],
102) -> Result<(AnalyzedResult, bool), SQLError> {
103    analyze_reusable_inputs(context, plan, params)
104        .map(|(result, reusable)| (result, reusable && params.is_empty()))
105}
106
107fn analyze_reusable_inputs(
108    context: &StatementAnalysisContext<'_>,
109    plan: &mut UnifiedPlan,
110    params: &[SQLParam],
111) -> Result<(AnalyzedResult, bool), SQLError> {
112    let mut result = None;
113    let mut reusable = true;
114    context.scopes.with_scope(&mut |scope| {
115        result = Some(match plan {
116            UnifiedPlan::Command(command) => match command.as_mut() {
117                // The explained statement retains a scope of its own.
118                CommandPlan::Explain { .. } => {
119                    let mut explained = None;
120                    context.scopes.with_scope(&mut |scope| {
121                        explained = Some(analyze_plan_result_inner(
122                            context.routines,
123                            context.aliases,
124                            plan,
125                            params,
126                            scope,
127                            &mut reusable,
128                        )?);
129                        Ok(())
130                    })?;
131                    explained.ok_or_else(|| {
132                        SQLError::Internal("EXPLAIN analysis scope did not run".into())
133                    })?
134                }
135                _ => analyze_plan_result_inner(
136                    context.routines,
137                    context.aliases,
138                    plan,
139                    params,
140                    scope,
141                    &mut reusable,
142                )?,
143            },
144            UnifiedPlan::Query(_) => analyze_plan_result_inner(
145                context.routines,
146                context.aliases,
147                plan,
148                params,
149                scope,
150                &mut reusable,
151            )?,
152        });
153        Ok(())
154    })?;
155    result
156        .map(|result| (result, reusable))
157        .ok_or_else(|| SQLError::Internal("statement analysis scope did not run".into()))
158}
159
160/// Analyze a statement in one binding scope, retain input-function results in its
161/// executable tree and derive its result without running statement expressions.
162pub fn analyze_plan_result(
163    routines: &dyn RoutineResolution,
164    aliases: &dyn crate::schema::dependencies::oid_alias::OidAliasInput,
165    plan: &mut UnifiedPlan,
166    params: &[SQLParam],
167    scope: &dyn StatementBindingScope,
168) -> Result<AnalyzedResult, SQLError> {
169    analyze_plan_result_inner(routines, aliases, plan, params, scope, &mut true)
170}
171
172fn analyze_plan_result_inner(
173    routines: &dyn RoutineResolution,
174    aliases: &dyn crate::schema::dependencies::oid_alias::OidAliasInput,
175    plan: &mut UnifiedPlan,
176    params: &[SQLParam],
177    scope: &dyn StatementBindingScope,
178    reusable: &mut bool,
179) -> Result<AnalyzedResult, SQLError> {
180    if let UnifiedPlan::Command(command) = plan {
181        if let CommandPlan::Explain {
182            body,
183            options,
184            unbound_parameters,
185        } = command.as_mut()
186        {
187            if params.is_empty() && options.infers_unbound_parameters()? {
188                let (parameters, body_reusable) = super::preparation::read_generic_explain_inputs(
189                    routines,
190                    body,
191                    &scope.binding_context()?,
192                    aliases,
193                )?;
194                *unbound_parameters = Some(parameters);
195                *reusable &= body_reusable;
196            } else {
197                *unbound_parameters = None;
198                analyze_plan_result_inner(routines, aliases, body, params, scope, reusable)?;
199            }
200            return options.result_schema().map(AnalyzedResult::Schema);
201        }
202    }
203    let binding = scope.binding_context()?;
204    let analysis =
205        super::preparation::read_executable_inputs(routines, plan, params, &binding, aliases)?;
206    *reusable &= analysis.reusable;
207    Ok(analysis.result)
208}
209
210pub fn analyze_command_parameters(
211    routines: &dyn RoutineResolution,
212    command: &CommandPlan,
213    params: &[SQLParam],
214    scope: &dyn StatementBindingScope,
215) -> Result<(), SQLError> {
216    let declared = parameter_input_types(params)?;
217    super::infer_prepared_parameter_types(
218        routines,
219        &UnifiedPlan::Command(Box::new(command.clone())),
220        &declared,
221        &scope.binding_context()?,
222    )?;
223    Ok(())
224}
225
226pub(super) fn parameter_input_types(
227    params: &[SQLParam],
228) -> Result<Vec<Option<crate::ColumnType>>, SQLError> {
229    let schema = RowSchema::default();
230    (1..=params.len())
231        .map(|index| match &params[index - 1] {
232            SQLParam::Scalar(Value::Str(_) | Value::Null) => Ok(None),
233            _ => crate::scalar_type(&ScalarExpr::Param(index), &schema, params),
234        })
235        .collect()
236}
237
238#[cfg(test)]
239mod tests;