Skip to main content

uqa_sql/expr/
numeric_operator.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scalar numeric operators share typed SQL overloads and existing arithmetic kernels.
8
9use crate::ast::{ColumnType, Expr, FunctionBinding, NumericOperator};
10use crate::type_resolution::numeric_operator_types_with_control;
11use crate::{RowSchema, SQLError};
12use uqa_core::{
13    memory::{Produced, ProductionControl, ProductionVec},
14    Value,
15};
16
17use super::{eval, EvalContext, Result};
18
19#[cfg(test)]
20mod tests;
21
22pub fn eval_numeric_operator(
23    operator: NumericOperator,
24    arguments: &[Value],
25    types: &[Option<ColumnType>],
26) -> Result<Value> {
27    eval_numeric_operator_with_control(
28        operator,
29        arguments,
30        types,
31        &ProductionControl::uncontrolled(),
32    )
33    .map(|value| {
34        value
35            .into_uncontrolled()
36            .expect("ordinary numeric result has no reservation")
37    })
38}
39
40/// Evaluate the existing selected numeric overload while casts, type names and intermediate values remain owned by the original allowance.
41pub fn eval_numeric_operator_with_control(
42    operator: NumericOperator,
43    arguments: &[Value],
44    types: &[Option<ColumnType>],
45    control: &ProductionControl<'_>,
46) -> Result<Produced<Value>> {
47    eval_numeric_operator_with_resolution(operator, arguments, types, control)
48        .map(|(value, _)| value)
49}
50
51mod resolved;
52pub use resolved::ResolvedNumericOperator;
53
54/// Evaluate before retaining an immutable builtin numeric selection. Unknown, domain and other catalog-defined operands preserve their original conversion path.
55pub fn eval_numeric_operator_with_resolution(
56    operator: NumericOperator,
57    arguments: &[Value],
58    types: &[Option<ColumnType>],
59    control: &ProductionControl<'_>,
60) -> Result<(Produced<Value>, Option<ResolvedNumericOperator>)> {
61    control.check()?;
62    if arguments.len() != types.len() {
63        return Err(SQLError::Internal(
64            "operator operand/type count differs".into(),
65        ));
66    }
67    let selected = numeric_operator_types_with_control(operator, types, control)?;
68    if let Some(resolved) = ResolvedNumericOperator::from_selection(operator, types, &selected) {
69        return resolved
70            .evaluate(arguments, control)
71            .map(|value| (value, Some(resolved)));
72    }
73    let mut converted = ProductionVec::new(*control);
74    converted.reserve(arguments.len())?;
75    for ((value, source), target) in arguments.iter().zip(types).zip(&selected.arguments) {
76        let target = target.sql_name_with_control(control)?;
77        let source = source
78            .as_ref()
79            .map(|ty| ty.sql_name_with_control(control))
80            .transpose()?;
81        converted.push_produced(super::cast_value_from_with_control(
82            value,
83            &target,
84            source.as_deref().map(String::as_str),
85            control,
86        )?)?;
87    }
88    let arguments = converted.finish()?;
89    if arguments.iter().any(|value| matches!(value, Value::Null)) {
90        return Ok((
91            control.finish(Value::Null, control.empty_reservation())?,
92            None,
93        ));
94    }
95    let value = evaluate_converted(operator, &arguments, control)?;
96    let target = selected.result.sql_name_with_control(control)?;
97    super::cast_value_from_with_control(&value, &target, None, control).map(|value| (value, None))
98}
99
100fn evaluate_converted(
101    operator: NumericOperator,
102    arguments: &[Value],
103    control: &ProductionControl<'_>,
104) -> Result<Produced<Value>> {
105    if arguments.iter().any(|value| matches!(value, Value::Null)) {
106        return Ok(control.finish(Value::Null, control.empty_reservation())?);
107    }
108    if operator == NumericOperator::Plus {
109        return Ok(control.copy_value(&arguments[0])?);
110    }
111    let name = match operator {
112        NumericOperator::Modulo => "mod",
113        NumericOperator::Power => "power",
114        NumericOperator::SquareRoot => "sqrt",
115        NumericOperator::CubeRoot => "cbrt",
116        NumericOperator::Absolute => "abs",
117        NumericOperator::Plus => unreachable!("unary plus copied its selected operand"),
118    };
119    super::scalar_core::eval_core_functions_with_control(name, arguments, control)
120        .or_else(|| super::scalar_math::eval_math_functions_with_control(name, arguments, control))
121        .expect("numeric syntax selects an existing numeric function")
122}
123
124pub(super) fn eval_ast_operator(
125    operator: NumericOperator,
126    binding: &FunctionBinding,
127    arguments: &[Expr],
128    context: &EvalContext<'_>,
129) -> Result<Value> {
130    let values = arguments
131        .iter()
132        .map(|arg| eval(arg, context))
133        .collect::<Result<Vec<_>>>()?;
134    let types = if binding.argument_types.is_empty() {
135        arguments
136            .iter()
137            .zip(&values)
138            .map(|(arg, value)| {
139                let scalar = crate::plan::ExpressionPlan::lower(arg.clone()).scalar;
140                let ty = crate::common_context_expression_type(
141                    &scalar,
142                    &RowSchema::default(),
143                    context.params,
144                    None,
145                )?;
146                Ok(ty.or_else(|| {
147                    (!matches!(arg, Expr::Literal(Value::Str(_) | Value::Null)))
148                        .then(|| crate::type_resolution::value_type(value))
149                        .flatten()
150                }))
151            })
152            .collect::<Result<Vec<_>>>()?
153    } else {
154        binding
155            .argument_types
156            .iter()
157            .map(|name| ColumnType::from_sql_name(name).map(Some))
158            .collect::<Result<Vec<_>>>()?
159    };
160    eval_numeric_operator(operator, &values, &types)
161}
162
163pub(super) fn eval_bound_operator_with_control(
164    operator: NumericOperator,
165    binding: &FunctionBinding,
166    arguments: &[Value],
167    control: &ProductionControl<'_>,
168) -> Result<Produced<Value>> {
169    control.check()?;
170    let mut types = ProductionVec::new(*control);
171    if binding.argument_types.is_empty() {
172        types.reserve(arguments.len())?;
173        for value in arguments {
174            let ty = crate::type_resolution::value_type_with_control(value, control)?;
175            let (ty, memory) = ty.map_or_else(
176                || (None, control.empty_reservation()),
177                |ty| {
178                    let (ty, memory) = ty.into_parts();
179                    (Some(ty), memory)
180                },
181            );
182            types.push_produced(control.finish(ty, memory)?)?;
183        }
184    } else {
185        types.reserve(binding.argument_types.len())?;
186        for name in &binding.argument_types {
187            let (ty, memory) = ColumnType::from_sql_name_with_control(name, control)?.into_parts();
188            types.push_produced(control.finish(Some(ty), memory)?)?;
189        }
190    }
191    let types = types.finish()?;
192    eval_numeric_operator_with_control(operator, arguments, &types, control)
193}
194
195#[cfg(test)]
196mod production_tests;