1use super::{
10 body_parameters::{sql_body_parameter_scope, sql_body_parameters},
11 call::ProcedureCallAnalysis,
12 compilation::RoutineCompilationContext,
13 declaration::RoutineTypeCatalog,
14 resolution::RoutineOverloadContext,
15 result_check::check_sql_function_result,
16 CompiledFunctionBody,
17};
18use crate::{
19 ast::{ColumnType, CreateFunction, FunctionBody},
20 binding::{
21 bind_routine_parameter_references,
22 statements::{AnalyzedResult, StatementBindingScope},
23 },
24 plan::{CommandPlan, ExpressionPlan, UnifiedPlan},
25 type_resolution::routine_polymorphic_type,
26 SQLError, SQLParam, ScalarExpr,
27};
28use uqa_core::Value;
29
30pub struct SQLBodyValidationContext<'a> {
32 pub compilation: RoutineCompilationContext<'a>,
33 pub overloads: RoutineOverloadContext<'a>,
34}
35
36#[must_use]
38pub fn sql_body_is_analyzable(def: &CreateFunction) -> bool {
39 !def.identity_params()
40 .any(|parameter| routine_polymorphic_type(¶meter.type_name).is_some())
41}
42
43pub fn validate_sql_function_body(
45 context: &SQLBodyValidationContext<'_>,
46 def: &CreateFunction,
47 body: &CompiledFunctionBody,
48 check_result: bool,
49) -> Result<(), SQLError> {
50 validate_body(context, def, body, check_result).map_err(|error| def.source_body_error(error))
51}
52
53fn validate_body(
54 context: &SQLBodyValidationContext<'_>,
55 def: &CreateFunction,
56 body: &CompiledFunctionBody,
57 check_result: bool,
58) -> Result<(), SQLError> {
59 let CompiledFunctionBody::SQL(plans) = body else {
60 return Ok(());
61 };
62 if !sql_body_is_analyzable(def) {
63 return Ok(());
64 }
65 let params = routine_parameter_values(context.compilation.types, def);
66 let scope = context.compilation.catalog.binding_snapshot()?;
67 let parameters = matches!(def.body, FunctionBody::Source(_))
69 .then(|| sql_body_parameter_scope(def, ¶ms))
70 .transpose()?;
71 let mut last = None;
72 for plan in plans {
73 let mut statement = plan.clone();
74 let query_result = if matches!(&statement, UnifiedPlan::Command(command) if matches!(command.as_ref(), CommandPlan::Call { .. }))
77 {
78 None
79 } else {
80 Some(crate::binding::analyze_routine_body_inputs(
81 context.compilation.routines,
82 &statement,
83 ¶ms,
84 &scope.context(),
85 context.compilation.catalog,
86 parameters.as_ref(),
87 )?)
88 };
89 if let Some(parameters) = ¶meters {
90 bind_routine_parameter_references(
91 context.compilation.routines,
92 &mut statement,
93 ¶ms,
94 &scope.context(),
95 parameters,
96 )?;
97 }
98 last = Some(match query_result {
99 Some(result) => result,
100 None => analyze_body_statement(context, &statement, ¶ms, &scope, true)?,
101 });
102 }
103 if check_result {
104 check_sql_function_result(context.compilation.types, def, last.as_ref())?;
105 }
106 Ok(())
107}
108
109pub(super) fn analyze_body_statement(
110 context: &SQLBodyValidationContext<'_>,
111 plan: &UnifiedPlan,
112 params: &[SQLParam],
113 scope: &dyn StatementBindingScope,
114 reject_output_arguments: bool,
115) -> Result<AnalyzedResult, SQLError> {
116 if let UnifiedPlan::Command(command) = plan {
117 if let CommandPlan::Call { name, args } = command.as_ref() {
118 let binding = scope.binding_context()?;
119 let call = ProcedureCallAnalysis::new(args)?;
120 let infer = |argument: &ExpressionPlan, target: Option<&ColumnType>| {
121 crate::binding::analyze_routine_body_argument(
122 context.compilation.routines,
123 argument,
124 params,
125 &binding,
126 context.compilation.catalog,
127 target,
128 )
129 };
130 let resolved = call.resolve(name, &context.overloads, &mut |argument| {
131 infer(argument, None)
132 })?;
133 let (arguments, _) = crate::ir::analyze_expression_call_arguments(args)?;
134 for (argument, target) in arguments.iter().zip(&resolved.invocation.argument_targets) {
135 if matches!(
136 argument.value,
137 ScalarExpr::Literal(Value::Str(_) | Value::Null)
138 ) {
139 let target = context
140 .compilation
141 .types
142 .resolve_catalog_column_type_name(target)?;
143 infer(
144 &ExpressionPlan {
145 scalar: argument.value.clone(),
146 subqueries: Vec::new(),
147 },
148 Some(&target),
149 )?;
150 }
151 }
152 if reject_output_arguments && resolved.function.def.output_params().next().is_some() {
153 return Err(output_argument_call_error());
154 }
155 return Ok(AnalyzedResult::Command);
156 }
157 }
158 crate::binding::analyze_routine_body_inputs(
159 context.compilation.routines,
160 plan,
161 params,
162 &scope.binding_context()?,
163 context.compilation.catalog,
164 None,
165 )
166}
167
168pub fn reject_output_argument_call(
170 overloads: &RoutineOverloadContext<'_>,
171 types: &dyn RoutineTypeCatalog,
172 name: &str,
173 arguments: &[ExpressionPlan],
174 infer: &mut dyn FnMut(&ExpressionPlan) -> Result<Option<ColumnType>, SQLError>,
175) -> Result<(), SQLError> {
176 if ProcedureCallAnalysis::new(arguments)?
177 .result_schema(name, overloads, types, infer)?
178 .is_some()
179 {
180 return Err(output_argument_call_error());
181 }
182 Ok(())
183}
184
185fn output_argument_call_error() -> SQLError {
186 SQLError::Routine {
187 sqlstate: "0A000".into(),
188 message: "calling procedures with output arguments is not supported in SQL functions"
189 .into(),
190 }
191}
192
193pub fn reject_undefined_parameters(
195 plan: &mut UnifiedPlan,
196 declared: usize,
197) -> Result<(), SQLError> {
198 let mut undefined = None;
199 plan.rewrite_scalar_expressions(&mut |expression| {
200 if let ScalarExpr::Param(index) = expression {
201 if *index > declared && undefined.is_none() {
202 undefined = Some(*index);
203 }
204 }
205 });
206 match undefined {
207 Some(index) => Err(SQLError::Routine {
208 sqlstate: "42P02".into(),
209 message: format!("there is no parameter ${index}"),
210 }),
211 None => Ok(()),
212 }
213}
214
215#[must_use]
217pub fn routine_parameter_values(
218 types: &dyn RoutineTypeCatalog,
219 def: &CreateFunction,
220) -> Vec<SQLParam> {
221 sql_body_parameters(def)
222 .map(|parameter| {
223 match types
224 .resolve_catalog_column_type(¶meter.type_name)
225 .or_else(|| ColumnType::from_sql_name(¶meter.type_name).ok())
226 {
227 Some(ty) => SQLParam::typed_scalar(Value::Null, ty),
228 None => SQLParam::scalar(Value::Null),
229 }
230 })
231 .collect()
232}