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;
29
30/// The catalog `CREATE FUNCTION` validates a SQL body against.
31pub struct SQLBodyValidationContext<'a> {
32    pub compilation: RoutineCompilationContext<'a>,
33    pub overloads: RoutineOverloadContext<'a>,
34}
35
36/// 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.
37#[must_use]
38pub fn sql_body_is_analyzable(def: &CreateFunction) -> bool {
39    !def.identity_params()
40        .any(|parameter| routine_polymorphic_type(&parameter.type_name).is_some())
41}
42
43/// 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.
44pub 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    // A SQL-standard body resolved its parameter names when it was compiled.
68    let parameters = matches!(def.body, FunctionBody::Source(_))
69        .then(|| sql_body_parameter_scope(def, &params))
70        .transpose()?;
71    let mut last = None;
72    for plan in plans {
73        let mut statement = plan.clone();
74        // Statement inputs are analyzed before the name-lowering pass derives its
75        // output schema, so a later bad name cannot hide an earlier input error.
76        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                &params,
84                &scope.context(),
85                context.compilation.catalog,
86                parameters.as_ref(),
87            )?)
88        };
89        if let Some(parameters) = &parameters {
90            bind_routine_parameter_references(
91                context.compilation.routines,
92                &mut statement,
93                &params,
94                &scope.context(),
95                parameters,
96            )?;
97        }
98        last = Some(match query_result {
99            Some(result) => result,
100            None => analyze_body_statement(context, &statement, &params, &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
168/// Resolve the procedure a `CALL` names and reject one with output arguments, which `PostgreSQL` does not support in SQL functions.
169pub 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
193/// Reject a reference to a parameter the routine does not declare, as `PostgreSQL`'s parser reports it.
194pub 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/// Typed placeholders for the parameters the body names, against which analysis types references to them.
216#[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(&parameter.type_name)
225                .or_else(|| ColumnType::from_sql_name(&parameter.type_name).ok())
226            {
227                Some(ty) => SQLParam::typed_scalar(Value::Null, ty),
228                None => SQLParam::scalar(Value::Null),
229            }
230        })
231        .collect()
232}