Skip to main content

uqa_sql/expr/
evaluator.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! AST scalar evaluation orchestration.
8
9use uqa_core::{ArrayValue, Value};
10
11use crate::ast::{Expr, FunctionResolutionError};
12use crate::error::{Result, SQLError};
13use crate::params::SQLParam;
14
15use super::binary::{compare_nullable, eval_binary, truthy, values_equal, values_equal_nullable};
16use super::builtin::eval_bound_builtin_function_call;
17use super::call_arguments::evaluate_call_args;
18use super::call_dispatch::eval_function_call;
19use super::casting::negate_value;
20use super::context::{cast_value_with_type_resolution, EvalContext};
21
22/// Evaluate a value-producing AST expression against one row and parameter context.
23#[expect(
24    clippy::too_many_lines,
25    reason = "builtin dispatch preserves arity, NULL, and error precedence"
26)]
27pub fn eval(expr: &Expr, ctx: &EvalContext<'_>) -> Result<Value> {
28    match expr {
29        Expr::Default => Err(SQLError::Internal(
30            "DEFAULT reached scalar expression evaluation without a mutation target".into(),
31        )),
32        Expr::Literal(v) => Ok(v.clone()),
33        Expr::Param(i) => match i.checked_sub(1).and_then(|index| ctx.params.get(index)) {
34            Some(SQLParam::Scalar(v) | SQLParam::TypedScalar { value: v, .. }) => Ok(v.clone()),
35            Some(SQLParam::Vector(v)) => Ok(Value::List(
36                v.iter().map(|x| Value::Float(f64::from(*x))).collect(),
37            )),
38            Some(SQLParam::Tensor(vectors)) => Ok(Value::List(
39                vectors
40                    .iter()
41                    .map(|vector| {
42                        Value::List(vector.iter().map(|x| Value::Float(f64::from(*x))).collect())
43                    })
44                    .collect(),
45            )),
46            None => Err(SQLError::MissingParam(*i)),
47        },
48        Expr::Column(name) => {
49            // Plain column refs match either an unqualified key or the
50            // suffix of a qualified `table.col` key, so the same row
51            // shape works for single-table SELECTs and JOIN tuples.
52            if ctx.row_lookup()?.column_is_ambiguous(name) {
53                return Err(SQLError::AmbiguousColumn(name.clone()));
54            }
55            Ok(ctx
56                .row_lookup()?
57                .column(name)
58                .cloned()
59                .unwrap_or(Value::Null))
60        }
61        Expr::QualifiedColumn { qualifier, column } => {
62            if ctx
63                .row_lookup()?
64                .qualified_column_is_ambiguous(qualifier, column)
65            {
66                return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
67            }
68            Ok(ctx
69                .row_lookup()?
70                .qualified_column(qualifier, column)
71                .cloned()
72                .unwrap_or(Value::Null))
73        }
74        Expr::InternalColumn(column) => ctx
75            .row_lookup()?
76            .internal_column(*column)
77            .cloned()
78            .ok_or_else(|| {
79                SQLError::Internal(format!(
80                    "internal relation attribute {column:?} is unavailable"
81                ))
82            }),
83        Expr::Array(elements) => {
84            let mut out = Vec::with_capacity(elements.len());
85            for e in elements {
86                out.push(eval(e, ctx)?);
87            }
88            ArrayValue::try_new(out).map(Value::Array).ok_or_else(|| {
89                SQLError::TypeMismatch(
90                    "multidimensional arrays must have matching dimensions".into(),
91                )
92            })
93        }
94        Expr::Row(elements) => {
95            let mut out = Vec::with_capacity(elements.len());
96            for element in elements {
97                out.push(eval(element, ctx)?);
98            }
99            Ok(Value::Row(out))
100        }
101        Expr::Star | Expr::QualifiedStar(_) => {
102            Err(SQLError::Internal("`*` cannot be evaluated".into()))
103        }
104        Expr::Func {
105            name,
106            binding,
107            args,
108            ..
109        } => {
110            let call_args = evaluate_call_args(args, ctx)?;
111            if let Some(binding) = binding {
112                if let Some(FunctionResolutionError::UndefinedFunction { signature }) =
113                    binding.resolution_error.as_ref()
114                {
115                    return Err(SQLError::Routine {
116                        sqlstate: "42883".into(),
117                        message: format!("function {signature} does not exist"),
118                    });
119                }
120                if binding.builtin {
121                    return eval_bound_builtin_function_call(binding, call_args, ctx);
122                }
123                let engine = ctx.engine.ok_or_else(|| {
124                    SQLError::Unsupported(
125                        "bound user function requires a logical engine session".into(),
126                    )
127                })?;
128                engine
129                    .call_bound_user_function(binding, &call_args)
130                    .unwrap_or_else(|| Err(SQLError::UnknownFunction(binding.name.clone())))
131            } else {
132                eval_function_call(name, call_args, ctx)
133            }
134        }
135        Expr::WindowCall { name, .. } => Err(SQLError::Unsupported(format!(
136            "window function `{name}` must be evaluated by the window-aware executor"
137        ))),
138        Expr::Case {
139            base,
140            when,
141            else_branch,
142        } => {
143            let base_value = match base {
144                Some(b) => Some(eval(b, ctx)?),
145                None => None,
146            };
147            for (cond, result) in when {
148                let matched = match &base_value {
149                    Some(bv) => values_equal(bv, &eval(cond, ctx)?),
150                    None => truthy(&eval(cond, ctx)?),
151                };
152                if matched {
153                    return eval(result, ctx);
154                }
155            }
156            match else_branch {
157                Some(e) => eval(e, ctx),
158                None => Ok(Value::Null),
159            }
160        }
161        Expr::Cast { expr, ty } => {
162            let source_ty = explicit_expr_type(expr);
163            let v = eval(expr, ctx)?;
164            cast_value_with_type_resolution(&v, source_ty, ty, ctx.engine)
165        }
166        Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
167            Err(SQLError::Unsupported(
168                "query-valued expressions must be lowered to physical ScalarExpr/QueryPlan slots"
169                    .into(),
170            ))
171        }
172        Expr::Binary { op, lhs, rhs } => eval_binary(*op, lhs, rhs, ctx),
173        Expr::UnaryMinus(inner) => {
174            let source_ty = explicit_expr_type(inner);
175            let value = eval(inner, ctx)?;
176            negate_value(&value, source_ty)
177        }
178        Expr::Not(inner) => {
179            // SQL three-valued logic: NOT NULL -> NULL.
180            let v = eval(inner, ctx)?;
181            if matches!(v, Value::Null) {
182                return Ok(Value::Null);
183            }
184            Ok(Value::Bool(!truthy(&v)))
185        }
186        Expr::And(items) => {
187            // Kleene AND: FALSE dominates, otherwise NULL taints.
188            let mut saw_null = false;
189            for item in items {
190                let v = eval(item, ctx)?;
191                if matches!(v, Value::Null) {
192                    saw_null = true;
193                } else if !truthy(&v) {
194                    return Ok(Value::Bool(false));
195                }
196            }
197            if saw_null {
198                return Ok(Value::Null);
199            }
200            Ok(Value::Bool(true))
201        }
202        Expr::Or(items) => {
203            // Kleene OR: TRUE dominates, otherwise NULL taints.
204            let mut saw_null = false;
205            for item in items {
206                let v = eval(item, ctx)?;
207                if matches!(v, Value::Null) {
208                    saw_null = true;
209                } else if truthy(&v) {
210                    return Ok(Value::Bool(true));
211                }
212            }
213            if saw_null {
214                return Ok(Value::Null);
215            }
216            Ok(Value::Bool(false))
217        }
218        Expr::IsNull { expr, negated } => {
219            let v = eval(expr, ctx)?;
220            let is_null = matches!(v, Value::Null);
221            Ok(Value::Bool(if *negated { !is_null } else { is_null }))
222        }
223        Expr::Between { expr, low, high } => {
224            let v = eval(expr, ctx)?;
225            let lo = eval(low, ctx)?;
226            let hi = eval(high, ctx)?;
227            eval_between(&v, &lo, &hi)
228        }
229        Expr::InList {
230            expr,
231            list,
232            negated,
233        } => {
234            // Three-valued IN: found -> TRUE, a NULL comparand (or a
235            // NULL needle) downgrades a miss to NULL.
236            let v = eval(expr, ctx)?;
237            let mut saw_null = matches!(v, Value::Null);
238            for item in list {
239                let candidate = eval(item, ctx)?;
240                match values_equal_nullable(&v, &candidate) {
241                    Some(true) => return Ok(Value::Bool(!*negated)),
242                    Some(false) => {}
243                    None => saw_null = true,
244                }
245            }
246            if saw_null {
247                return Ok(Value::Null);
248            }
249            Ok(Value::Bool(*negated))
250        }
251    }
252}
253
254fn explicit_expr_type(expr: &Expr) -> Option<&str> {
255    match expr {
256        Expr::Cast { ty, .. } => Some(ty),
257        Expr::Literal(Value::Int(value)) if i32::try_from(*value).is_ok() => Some("integer"),
258        Expr::Literal(Value::Int(_)) => Some("bigint"),
259        Expr::Literal(Value::Bytes(_)) => Some("bytea"),
260        _ => None,
261    }
262}
263
264/// `expr BETWEEN low AND high` under three-valued logic: a definite
265/// FALSE on either bound wins over a NULL on the other.
266pub(super) fn eval_between(v: &Value, lo: &Value, hi: &Value) -> Result<Value> {
267    let ge = compare_nullable(v, lo)?.map(|ord| ord.is_ge());
268    let le = compare_nullable(v, hi)?.map(|ord| ord.is_le());
269    Ok(match (ge, le) {
270        (Some(false), _) | (_, Some(false)) => Value::Bool(false),
271        (Some(true), Some(true)) => Value::Bool(true),
272        _ => Value::Null,
273    })
274}