Skip to main content

uqa_sql/routines/
invocation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Routine invocation metadata, concrete signatures, and anonymous-record assignment rules.
8pub mod descriptions;
9mod output;
10use crate::{
11    assignment::routines::RoutineValueContext,
12    ast::{ColumnType, CreateFunction, FunctionReturns, RoutineInvocationBinding},
13    expr::value_type_name,
14    routines::declaration::RoutineTypeCatalog,
15    SQLError,
16};
17pub use output::call_output_schema_with_control;
18use uqa_core::Value;
19pub fn output_column_names(def: &CreateFunction) -> Vec<String> {
20    def.output_params()
21        .enumerate()
22        .map(|(idx, p)| {
23            if p.name.is_empty() {
24                format!("column{}", idx + 1)
25            } else {
26                p.name.clone()
27            }
28        })
29        .collect()
30}
31
32pub fn call_signature(name: &str, args: &[(Option<String>, Value)]) -> String {
33    let types = args
34        .iter()
35        .map(|(arg_name, value)| match arg_name {
36            Some(arg_name) => format!("{arg_name} => {}", value_type_name(value)),
37            None => value_type_name(value).to_string(),
38        })
39        .collect::<Vec<_>>()
40        .join(", ");
41    format!("{name}({types})")
42}
43
44pub fn routine_resolution_error(
45    kind: &str,
46    name: &str,
47    args: &[(Option<String>, Value)],
48    suffix: &str,
49) -> SQLError {
50    SQLError::Routine {
51        sqlstate: if suffix == "is not unique" {
52            "42725".into()
53        } else {
54            "42883".into()
55        },
56        message: format!("{kind} {} {suffix}", call_signature(name, args)),
57    }
58}
59
60pub fn runtime_argument_types(
61    args: &[(Option<String>, Value)],
62) -> Result<Vec<Option<ColumnType>>, SQLError> {
63    args.iter()
64        .map(|(_, value)| {
65            if matches!(value, Value::Null) {
66                Ok(None)
67            } else {
68                ColumnType::from_sql_name(value_type_name(value)).map(Some)
69            }
70        })
71        .collect()
72}
73
74pub fn specialized_definition(
75    definition: &CreateFunction,
76    invocation: &RoutineInvocationBinding,
77) -> Result<Option<CreateFunction>, SQLError> {
78    specialized_definition_with_control(
79        definition,
80        invocation,
81        &uqa_core::memory::ProductionControl::uncontrolled(),
82    )
83    .map(|definition| {
84        definition.map(|definition| {
85            definition
86                .into_uncontrolled()
87                .expect("ordinary specialized definition")
88        })
89    })
90}
91
92/// Construct a concrete declaration with every replacement type selected before destination allocation. Unchanged declarations retain their caller's original owner.
93pub fn specialized_definition_with_control(
94    definition: &CreateFunction,
95    invocation: &RoutineInvocationBinding,
96    control: &uqa_core::memory::ProductionControl<'_>,
97) -> Result<Option<uqa_core::memory::Produced<CreateFunction>>, SQLError> {
98    control.check()?;
99    validate_specialized_definition(definition, invocation)?;
100    let parameters_match = definition
101        .params
102        .iter()
103        .zip(&invocation.parameter_types)
104        .all(|(parameter, type_name)| parameter.type_name == *type_name);
105    let return_type_matches = match (&invocation.return_type, &definition.returns) {
106        (Some(concrete), FunctionReturns::Scalar { type_name })
107        | (Some(concrete), FunctionReturns::SetOf { type_name }) => concrete == type_name,
108        (None, _) | (Some(_), FunctionReturns::None | FunctionReturns::Table) => true,
109    };
110    if parameters_match && return_type_matches {
111        return Ok(None);
112    }
113    if control.budget().is_some() {
114        return crate::plan::copy::copy_specialized_function(definition, invocation, control)
115            .map(Some);
116    }
117    let mut specialized = definition.clone();
118    for (parameter, type_name) in specialized
119        .params
120        .iter_mut()
121        .zip(&invocation.parameter_types)
122    {
123        parameter.type_name.clone_from(type_name);
124    }
125    if let Some(return_type) = &invocation.return_type {
126        match &mut specialized.returns {
127            FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name } => {
128                type_name.clone_from(return_type);
129            }
130            FunctionReturns::None | FunctionReturns::Table => {}
131        }
132    }
133    Ok(Some(control.finish(specialized, None)?))
134}
135
136pub(crate) fn validate_specialized_definition(
137    definition: &CreateFunction,
138    invocation: &RoutineInvocationBinding,
139) -> Result<(), SQLError> {
140    if invocation.parameter_types.len() != definition.params.len() {
141        return Err(SQLError::Internal(format!(
142            "routine `{}` has {} concrete parameter types for {} parameters",
143            definition.name,
144            invocation.parameter_types.len(),
145            definition.params.len()
146        )));
147    }
148    Ok(())
149}
150
151pub fn runtime_record_column_type(value: &Value) -> Option<crate::ast::ColumnType> {
152    if matches!(value, Value::Null) {
153        return None;
154    }
155    crate::ast::ColumnType::from_sql_name(crate::expr::value_type_name(value)).ok()
156}
157
158pub fn coerce_anonymous_record_value(
159    context: &dyn RoutineValueContext,
160    value: &Value,
161    type_name: &str,
162) -> Result<Value, SQLError> {
163    let target = context
164        .catalog_column_type(type_name)
165        .or_else(|| crate::ast::ColumnType::from_sql_name(type_name).ok());
166    let Some(target) = target else {
167        return crate::assignment::routines::coerce_routine_value(context, value, type_name);
168    };
169    crate::assignment::conversion::convert_value_to_column_type_with_context(
170        context,
171        value.clone(),
172        &target,
173    )
174    .map_err(|error| match error {
175        SQLError::TypeMismatch(message) if message.starts_with("value too long for type ") => {
176            SQLError::Routine {
177                sqlstate: "22001".into(),
178                message,
179            }
180        }
181        other => other,
182    })
183}
184
185pub fn anonymous_record_shape_error() -> SQLError {
186    SQLError::Routine {
187        sqlstate: "42P13".into(),
188        message: "return type mismatch in function declared to return record".into(),
189    }
190}
191pub fn call_output_schema(
192    catalog: &dyn RoutineTypeCatalog,
193    definition: &crate::ast::CreateFunction,
194    parameter_types: &[String],
195) -> Result<Option<crate::RowSchema>, SQLError> {
196    call_output_schema_with_control(
197        catalog,
198        definition,
199        parameter_types,
200        &uqa_core::memory::ProductionControl::uncontrolled(),
201    )
202}