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 bitwise;
52mod resolved;
53pub use resolved::ResolvedNumericOperator;
54
55/// Evaluate before retaining an immutable builtin numeric selection. Unknown, domain and other catalog-defined operands preserve their original conversion path.
56pub fn eval_numeric_operator_with_resolution(
57    operator: NumericOperator,
58    arguments: &[Value],
59    types: &[Option<ColumnType>],
60    control: &ProductionControl<'_>,
61) -> Result<(Produced<Value>, Option<ResolvedNumericOperator>)> {
62    control.check()?;
63    if arguments.len() != types.len() {
64        return Err(SQLError::Internal(
65            "operator operand/type count differs".into(),
66        ));
67    }
68    let selected = numeric_operator_types_with_control(operator, types, control)?;
69    if let Some(resolved) = ResolvedNumericOperator::from_selection(operator, types, &selected) {
70        return resolved
71            .evaluate(arguments, control)
72            .map(|value| (value, Some(resolved)));
73    }
74    let mut converted = ProductionVec::new(*control);
75    converted.reserve(arguments.len())?;
76    for ((value, source), target) in arguments.iter().zip(types).zip(&selected.arguments) {
77        let target = target.sql_name_with_control(control)?;
78        let source = source
79            .as_ref()
80            .map(|ty| ty.sql_name_with_control(control))
81            .transpose()?;
82        converted.push_produced(super::cast_value_from_with_control(
83            value,
84            &target,
85            source.as_deref().map(String::as_str),
86            control,
87        )?)?;
88    }
89    let arguments = converted.finish()?;
90    if arguments.iter().any(|value| matches!(value, Value::Null)) {
91        return Ok((
92            control.finish(Value::Null, control.empty_reservation())?,
93            None,
94        ));
95    }
96    let value = evaluate_converted(operator, &arguments, &selected.result, control)?;
97    let target = selected.result.sql_name_with_control(control)?;
98    super::cast_value_from_with_control(&value, &target, None, control).map(|value| (value, None))
99}
100
101fn evaluate_converted(
102    operator: NumericOperator,
103    arguments: &[Value],
104    result: &ColumnType,
105    control: &ProductionControl<'_>,
106) -> Result<Produced<Value>> {
107    if arguments.iter().any(|value| matches!(value, Value::Null)) {
108        return Ok(control.finish(Value::Null, control.empty_reservation())?);
109    }
110    if operator == NumericOperator::Plus {
111        return Ok(control.copy_value(&arguments[0])?);
112    }
113    let name = match operator {
114        NumericOperator::Modulo => "mod",
115        NumericOperator::Power => "power",
116        NumericOperator::SquareRoot => "sqrt",
117        NumericOperator::CubeRoot => "cbrt",
118        NumericOperator::Absolute => "abs",
119        NumericOperator::Plus => unreachable!("unary plus copied its selected operand"),
120        NumericOperator::BitAnd
121        | NumericOperator::BitOr
122        | NumericOperator::BitXor
123        | NumericOperator::BitNot
124        | NumericOperator::ShiftLeft
125        | NumericOperator::ShiftRight => {
126            return bitwise::evaluate(operator, arguments, result, control)
127        }
128    };
129    super::scalar_core::eval_core_functions_with_control(name, arguments, control)
130        .or_else(|| super::scalar_math::eval_math_functions_with_control(name, arguments, control))
131        .expect("numeric syntax selects an existing numeric function")
132}
133
134pub(super) fn eval_ast_operator(
135    operator: NumericOperator,
136    binding: &FunctionBinding,
137    arguments: &[Expr],
138    context: &EvalContext<'_>,
139) -> Result<Value> {
140    let values = arguments
141        .iter()
142        .map(|arg| eval(arg, context))
143        .collect::<Result<Vec<_>>>()?;
144    let types = if binding.argument_types.is_empty() {
145        arguments
146            .iter()
147            .zip(&values)
148            .map(|(arg, value)| {
149                let scalar = crate::plan::ExpressionPlan::lower(arg.clone()).scalar;
150                let ty = crate::common_context_expression_type(
151                    &scalar,
152                    &RowSchema::default(),
153                    context.params,
154                    None,
155                )?;
156                Ok(ty.or_else(|| {
157                    (!matches!(arg, Expr::Literal(Value::Str(_) | Value::Null)))
158                        .then(|| crate::type_resolution::value_type(value))
159                        .flatten()
160                }))
161            })
162            .collect::<Result<Vec<_>>>()?
163    } else {
164        binding
165            .argument_types
166            .iter()
167            .map(|name| ColumnType::from_sql_name(name).map(Some))
168            .collect::<Result<Vec<_>>>()?
169    };
170    eval_numeric_operator(operator, &values, &types)
171}
172
173pub(super) fn eval_bound_operator_with_control(
174    operator: NumericOperator,
175    binding: &FunctionBinding,
176    arguments: &[Value],
177    control: &ProductionControl<'_>,
178) -> Result<Produced<Value>> {
179    control.check()?;
180    let mut types = ProductionVec::new(*control);
181    if binding.argument_types.is_empty() {
182        types.reserve(arguments.len())?;
183        for value in arguments {
184            let ty = crate::type_resolution::value_type_with_control(value, control)?;
185            let (ty, memory) = ty.map_or_else(
186                || (None, control.empty_reservation()),
187                |ty| {
188                    let (ty, memory) = ty.into_parts();
189                    (Some(ty), memory)
190                },
191            );
192            types.push_produced(control.finish(ty, memory)?)?;
193        }
194    } else {
195        types.reserve(binding.argument_types.len())?;
196        for name in &binding.argument_types {
197            let (ty, memory) = ColumnType::from_sql_name_with_control(name, control)?.into_parts();
198            types.push_produced(control.finish(Some(ty), memory)?)?;
199        }
200    }
201    let types = types.finish()?;
202    eval_numeric_operator_with_control(operator, arguments, &types, control)
203}
204
205#[cfg(test)]
206mod production_tests;