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