Skip to main content

uqa_sql/routines/
body_validation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The body checks of `PostgreSQL`'s SQL-language validator, `fmgr_sql_validator`, which also hold when a body runs: each statement is analyzed against the catalog before it runs, a reference to a parameter the routine lacks is an error, a `CALL` of a procedure with output arguments is rejected, and the final statement is checked against the declared result.
8
9use 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;
29mod production;
30pub use production::routine_parameter_values_with_control;
31pub use production::{
32    reject_output_argument_call_with_control, reject_undefined_parameters_with_control,
33};
34
35/// The catalog `CREATE FUNCTION` validates a SQL body against.
36pub struct SQLBodyValidationContext<'a> {
37    pub compilation: RoutineCompilationContext<'a>,
38    pub overloads: RoutineOverloadContext<'a>,
39}
40
41/// Whether a SQL body can be analyzed without the argument types of a call: `PostgreSQL` only parses the body of a routine with polymorphic arguments until a call supplies them.
42#[must_use]
43pub fn sql_body_is_analyzable(def: &CreateFunction) -> bool {
44    !def.identity_params()
45        .any(|parameter| routine_polymorphic_type(&parameter.type_name).is_some())
46}
47
48/// Validate a compiled SQL body as `CREATE FUNCTION` does: analyze each statement in order against the catalog, without running any of them, and when `check_result` holds, check the final statement against the declared result.
49pub fn validate_sql_function_body(
50    context: &SQLBodyValidationContext<'_>,
51    def: &CreateFunction,
52    body: &CompiledFunctionBody,
53    check_result: bool,
54) -> Result<(), SQLError> {
55    validate_body(context, def, body, check_result).map_err(|error| def.source_body_error(error))
56}
57
58fn validate_body(
59    context: &SQLBodyValidationContext<'_>,
60    def: &CreateFunction,
61    body: &CompiledFunctionBody,
62    check_result: bool,
63) -> Result<(), SQLError> {
64    let CompiledFunctionBody::SQL(plans) = body else {
65        return Ok(());
66    };
67    if !sql_body_is_analyzable(def) {
68        return Ok(());
69    }
70    let params = routine_parameter_values(context.compilation.types, def);
71    let scope = context.compilation.catalog.binding_snapshot()?;
72    // A SQL-standard body resolved its parameter names when it was compiled.
73    let parameters = matches!(def.body, FunctionBody::Source(_))
74        .then(|| sql_body_parameter_scope(def, &params))
75        .transpose()?;
76    let mut last = None;
77    for plan in plans {
78        let mut statement = plan.clone();
79        // Statement inputs are analyzed before the name-lowering pass derives its
80        // output schema, so a later bad name cannot hide an earlier input error.
81        let query_result = if matches!(&statement, UnifiedPlan::Command(command) if matches!(command.as_ref(), CommandPlan::Call { .. }))
82        {
83            None
84        } else {
85            Some(crate::binding::analyze_routine_body_inputs(
86                context.compilation.routines,
87                &statement,
88                &params,
89                &scope.context(),
90                context.compilation.catalog,
91                parameters.as_ref(),
92            )?)
93        };
94        if let Some(parameters) = &parameters {
95            bind_routine_parameter_references(
96                context.compilation.routines,
97                &mut statement,
98                &params,
99                &scope.context(),
100                parameters,
101            )?;
102        }
103        last = Some(match query_result {
104            Some(result) => result,
105            None => analyze_body_statement(context, &statement, &params, &scope, true)?,
106        });
107    }
108    if check_result {
109        check_sql_function_result(context.compilation.types, def, last.as_ref())?;
110    }
111    Ok(())
112}
113
114pub(super) fn analyze_body_statement(
115    context: &SQLBodyValidationContext<'_>,
116    plan: &UnifiedPlan,
117    params: &[SQLParam],
118    scope: &dyn StatementBindingScope,
119    reject_output_arguments: bool,
120) -> Result<AnalyzedResult, SQLError> {
121    if let UnifiedPlan::Command(command) = plan {
122        if let CommandPlan::Call { name, args } = command.as_ref() {
123            let binding = scope.binding_context()?;
124            let call = ProcedureCallAnalysis::new(args)?;
125            let infer = |argument: &ExpressionPlan, target: Option<&ColumnType>| {
126                crate::binding::analyze_routine_body_argument(
127                    context.compilation.routines,
128                    argument,
129                    params,
130                    &binding,
131                    context.compilation.catalog,
132                    target,
133                )
134            };
135            let resolved = call.resolve(name, &context.overloads, &mut |argument| {
136                infer(argument, None)
137            })?;
138            let (arguments, _) = crate::ir::analyze_expression_call_arguments(args)?;
139            for (argument, target) in arguments.iter().zip(&resolved.invocation.argument_targets) {
140                if matches!(
141                    argument.value,
142                    ScalarExpr::Literal(Value::Str(_) | Value::Null)
143                ) {
144                    let target = context
145                        .compilation
146                        .types
147                        .resolve_catalog_column_type_name(target)?;
148                    infer(
149                        &ExpressionPlan {
150                            scalar: argument.value.clone(),
151                            subqueries: Vec::new(),
152                        },
153                        Some(&target),
154                    )?;
155                }
156            }
157            if reject_output_arguments && resolved.function.def.output_params().next().is_some() {
158                return Err(output_argument_call_error());
159            }
160            return Ok(AnalyzedResult::Command);
161        }
162    }
163    crate::binding::analyze_routine_body_inputs(
164        context.compilation.routines,
165        plan,
166        params,
167        &scope.binding_context()?,
168        context.compilation.catalog,
169        None,
170    )
171}
172
173/// Resolve the procedure a `CALL` names and reject one with output arguments, which `PostgreSQL` does not support in SQL functions.
174pub fn reject_output_argument_call(
175    overloads: &RoutineOverloadContext<'_>,
176    types: &dyn RoutineTypeCatalog,
177    name: &str,
178    arguments: &[ExpressionPlan],
179    infer: &mut dyn FnMut(&ExpressionPlan) -> Result<Option<ColumnType>, SQLError>,
180) -> Result<(), SQLError> {
181    if ProcedureCallAnalysis::new(arguments)?
182        .result_schema(name, overloads, types, infer)?
183        .is_some()
184    {
185        return Err(output_argument_call_error());
186    }
187    Ok(())
188}
189
190fn output_argument_call_error() -> SQLError {
191    SQLError::Routine {
192        sqlstate: "0A000".into(),
193        message: "calling procedures with output arguments is not supported in SQL functions"
194            .into(),
195    }
196}
197
198/// Reject a reference to a parameter the routine does not declare, as `PostgreSQL`'s parser reports it.
199pub fn reject_undefined_parameters(
200    plan: &mut UnifiedPlan,
201    declared: usize,
202) -> Result<(), SQLError> {
203    let mut undefined = None;
204    plan.rewrite_scalar_expressions(&mut |expression| {
205        if let ScalarExpr::Param(index) = expression {
206            if *index > declared && undefined.is_none() {
207                undefined = Some(*index);
208            }
209        }
210    });
211    match undefined {
212        Some(index) => Err(SQLError::Routine {
213            sqlstate: "42P02".into(),
214            message: format!("there is no parameter ${index}"),
215        }),
216        None => Ok(()),
217    }
218}
219
220/// Typed placeholders for the parameters the body names, against which analysis types references to them.
221#[must_use]
222pub fn routine_parameter_values(
223    types: &dyn RoutineTypeCatalog,
224    def: &CreateFunction,
225) -> Vec<SQLParam> {
226    routine_parameter_values_with_control(
227        types,
228        def,
229        &uqa_core::memory::ProductionControl::uncontrolled(),
230    )
231    .expect("ordinary routine parameter types")
232    .into_uncontrolled()
233    .expect("ordinary routine parameters have no reservation")
234}