Skip to main content

uqa_sql/routines/
call.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Procedure argument validation, static overload selection, and declared result schemas.
8
9use crate::{
10    assignment::conversion::column_type_name,
11    ast::ColumnType,
12    ir::{analyze_expression_call_arguments, ScalarCallArgument},
13    plan::ExpressionPlan,
14    routines::{
15        declaration::RoutineTypeCatalog,
16        resolution::{RoutineCallKind, RoutineOverloadContext},
17    },
18    RowSchema, SQLError, ScalarExpr,
19};
20use uqa_core::Value;
21
22/// Reject forbidden subqueries before the caller captures its statement catalog scope.
23pub fn validate_call_arguments(arguments: &[ExpressionPlan]) -> Result<(), SQLError> {
24    if arguments
25        .iter()
26        .any(|argument| !argument.subqueries.is_empty())
27    {
28        return Err(SQLError::Unsupported(
29            "cannot use subquery in CALL argument".into(),
30        ));
31    }
32    Ok(())
33}
34
35/// Reject a set-returning call in an argument, as `transformCallStmt` analyzes each argument as a CALL argument expression, before the procedure is resolved.
36pub fn reject_set_call_arguments(
37    routines: &dyn crate::routines::RoutineResolution,
38    arguments: &[ExpressionPlan],
39    params: &[crate::SQLParam],
40) -> Result<(), SQLError> {
41    for argument in arguments {
42        if crate::semantics::sets::validation::expression_may_return_set(
43            routines,
44            routines,
45            &argument.scalar,
46            &RowSchema::default(),
47            params,
48        )? {
49            crate::semantics::sets::placement::SetPlacement::CallArgument.admit(true)?;
50        }
51    }
52    Ok(())
53}
54
55/// Unknown string and NULL literals participate in procedure overload resolution without a concrete type.
56pub fn infer_call_argument_types(
57    arguments: &[ExpressionPlan],
58    decoded: &[ScalarCallArgument<'_>],
59    infer: &mut dyn FnMut(&ExpressionPlan) -> Result<Option<ColumnType>, SQLError>,
60) -> Result<Vec<Option<ColumnType>>, SQLError> {
61    arguments
62        .iter()
63        .zip(decoded)
64        .map(|(argument, call_argument)| {
65            if matches!(
66                call_argument.value,
67                ScalarExpr::Literal(Value::Str(_) | Value::Null)
68            ) {
69                Ok(None)
70            } else {
71                infer(argument)
72            }
73        })
74        .collect()
75}
76
77/// The syntax metadata needed before the caller captures the scope used for result description.
78pub struct ProcedureCallAnalysis<'a> {
79    arguments: &'a [ExpressionPlan],
80    decoded: Vec<ScalarCallArgument<'a>>,
81    names: Vec<Option<String>>,
82    explicit_variadic: bool,
83}
84
85impl<'a> ProcedureCallAnalysis<'a> {
86    pub fn new(arguments: &'a [ExpressionPlan]) -> Result<Self, SQLError> {
87        validate_call_arguments(arguments)?;
88        let (decoded, explicit_variadic) = analyze_expression_call_arguments(arguments)?;
89        let names = decoded
90            .iter()
91            .map(|argument| argument.name.map(str::to_string))
92            .collect();
93        Ok(Self {
94            arguments,
95            decoded,
96            names,
97            explicit_variadic,
98        })
99    }
100
101    pub fn result_schema(
102        &self,
103        name: &str,
104        overloads: &RoutineOverloadContext<'_>,
105        types: &dyn RoutineTypeCatalog,
106        infer: &mut dyn FnMut(&ExpressionPlan) -> Result<Option<ColumnType>, SQLError>,
107    ) -> Result<Option<RowSchema>, SQLError> {
108        let resolved = self.resolve(name, overloads, infer)?;
109        super::invocation::call_output_schema(
110            types,
111            &resolved.function.def,
112            &resolved.invocation.parameter_types,
113        )
114    }
115
116    pub(crate) fn resolve(
117        &self,
118        name: &str,
119        overloads: &RoutineOverloadContext<'_>,
120        infer: &mut dyn FnMut(&ExpressionPlan) -> Result<Option<ColumnType>, SQLError>,
121    ) -> Result<super::StaticFunctionMatch, SQLError> {
122        let argument_types = infer_call_argument_types(self.arguments, &self.decoded, infer)?;
123        self.resolve_types(name, overloads, &argument_types)
124    }
125
126    pub(crate) fn resolve_types(
127        &self,
128        name: &str,
129        overloads: &RoutineOverloadContext<'_>,
130        argument_types: &[Option<ColumnType>],
131    ) -> Result<super::StaticFunctionMatch, SQLError> {
132        let Some(resolved) = overloads.resolve_static_sql_routine_match(
133            name,
134            None,
135            &self.names,
136            argument_types,
137            self.explicit_variadic,
138            RoutineCallKind::Procedure,
139        )?
140        else {
141            let signature = argument_types
142                .iter()
143                .map(|argument| {
144                    argument
145                        .as_ref()
146                        .map_or_else(|| "unknown", column_type_name)
147                })
148                .collect::<Vec<_>>()
149                .join(", ");
150            return Err(SQLError::Diagnostic {
151                sqlstate: "42883".into(),
152                message: format!("procedure {name}({signature}) does not exist"),
153                detail: None,
154                hint: Some(
155                    "No procedure matches the given name and argument types. You might need to add explicit type casts."
156                        .into(),
157                ),
158            });
159        };
160        Ok(resolved)
161    }
162}