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::{BinaryOp, Expr};
12use crate::error::{Result, SQLError};
13
14use super::binary::{eval_binary, eval_comparison_truth_with_engine, truthy};
15use super::builtin::eval_bound_builtin_function_call;
16use super::call_arguments::evaluate_call_args;
17use super::call_dispatch::eval_function_call;
18use super::casting::negate_value;
19use super::context::{cast_value_with_type_resolution, EvalContext};
20
21/// Evaluate a value-producing AST expression against one row and parameter context.
22#[expect(
23    clippy::too_many_lines,
24    reason = "builtin dispatch preserves arity, NULL, and error precedence"
25)]
26pub fn eval(expr: &Expr, ctx: &EvalContext<'_>) -> Result<Value> {
27    match expr {
28        Expr::Default => Err(SQLError::Internal(
29            "DEFAULT reached scalar expression evaluation without a mutation target".into(),
30        )),
31        Expr::Literal(v) => Ok(v.clone()),
32        Expr::TypedLiteral { value, ty, .. } => {
33            Ok(super::composites::literal::evaluate_with_control(
34                value,
35                ty,
36                ctx.engine,
37                &uqa_core::memory::ProductionControl::uncontrolled(),
38            )?
39            .into_uncontrolled()
40            .expect("ordinary constant result"))
41        }
42        Expr::Param(i) => match i.checked_sub(1).and_then(|index| ctx.params.get(index)) {
43            Some(parameter) => parameter.to_value(),
44            None => Err(SQLError::MissingParam(*i)),
45        },
46        Expr::Column(name) => {
47            // Plain column refs match either an unqualified key or the
48            // suffix of a qualified `table.col` key, so the same row
49            // shape works for single-table SELECTs and JOIN tuples.
50            if ctx.row_lookup()?.column_is_ambiguous(name) {
51                return Err(SQLError::AmbiguousColumn(name.clone()));
52            }
53            Ok(ctx
54                .row_lookup()?
55                .column(name)
56                .cloned()
57                .unwrap_or(Value::Null))
58        }
59        Expr::QualifiedColumn { qualifier, column } => {
60            if ctx
61                .row_lookup()?
62                .qualified_column_is_ambiguous(qualifier, column)
63            {
64                return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
65            }
66            Ok(ctx
67                .row_lookup()?
68                .qualified_column(qualifier, column)
69                .cloned()
70                .unwrap_or(Value::Null))
71        }
72        Expr::InternalColumn(column) => ctx
73            .row_lookup()?
74            .internal_column(*column)
75            .cloned()
76            .ok_or_else(|| {
77                SQLError::Internal(format!(
78                    "internal relation attribute {column:?} is unavailable"
79                ))
80            }),
81        Expr::Array(elements) => {
82            let scalar = crate::plan::ExpressionPlan::lower(Expr::Array(elements.clone())).scalar;
83            let crate::ScalarExpr::Array(items) = scalar else {
84                unreachable!("array lowering")
85            };
86            let element_oid = crate::type_resolution::scalar_array_element_oid_with_control(
87                &items,
88                &crate::RowSchema::default(),
89                ctx.params,
90                ctx.engine,
91                &uqa_core::memory::ProductionControl::uncontrolled(),
92            )?;
93            let mut out = Vec::with_capacity(elements.len());
94            for e in elements {
95                out.push(eval(e, ctx)?);
96            }
97            ArrayValue::try_new(out)
98                .map(|array| Value::Array(array.with_element_type_oid(element_oid)))
99                .ok_or_else(|| {
100                    SQLError::TypeMismatch(
101                        "multidimensional arrays must have matching dimensions".into(),
102                    )
103                })
104        }
105        Expr::CompositeRow { items, binding } => {
106            let control = uqa_core::memory::ProductionControl::uncontrolled();
107            Ok(super::composites::constructor::evaluate_with_control(
108                binding,
109                items.len(),
110                ctx.engine,
111                &control,
112                |index| {
113                    control
114                        .finish(eval(&items[index], ctx)?, None)
115                        .map_err(Into::into)
116                },
117            )?
118            .into_uncontrolled()
119            .expect("ordinary composite constructor"))
120        }
121        Expr::Row(elements) => {
122            let mut out = Vec::with_capacity(elements.len());
123            let mut fields = Vec::with_capacity(elements.len());
124            for element in elements {
125                let scalar = crate::plan::ExpressionPlan::lower(element.clone()).scalar;
126                if let Some(field) = crate::type_resolution::scalar_record_field_type_with_control(
127                    &scalar,
128                    &crate::RowSchema::default(),
129                    ctx.params,
130                    ctx.engine,
131                    &uqa_core::memory::ProductionControl::uncontrolled(),
132                )? {
133                    fields.push(field);
134                }
135                out.push(eval(element, ctx)?);
136            }
137            let row = if fields.len() == out.len() {
138                uqa_core::RowValue::typed(out, fields)?
139            } else {
140                uqa_core::RowValue::new(out)
141            };
142            Ok(Value::Row(row))
143        }
144        Expr::Star | Expr::QualifiedStar(_) => {
145            Err(SQLError::Internal("`*` cannot be evaluated".into()))
146        }
147        Expr::Func {
148            name,
149            binding,
150            args,
151            ..
152        } => {
153            if let Some(binding) = binding {
154                if let Some(error) = &binding.resolution_error {
155                    return Err(error.sql_error());
156                }
157                if let Some(clause) = crate::catalog::collations::expression::ast_clause(expr)? {
158                    // Analysis retains the selected collation for consumers; evaluating the clause only evaluates its operand.
159                    return eval(clause.argument, ctx);
160                }
161                if let Some(hook) = ctx.engine {
162                    hook.require_builtin_execute(binding)?;
163                }
164                if let Some(dispatch) = binding.dispatch {
165                    if let Some(result) =
166                        super::eval_distinct_boolean(dispatch, args.len(), |index| {
167                            eval(&args[index], ctx)
168                        })
169                    {
170                        return result;
171                    }
172                }
173                if let Some(crate::ast::FunctionDispatch::NumericOperator(operator)) =
174                    binding.dispatch
175                {
176                    return super::numeric_operator::eval_ast_operator(
177                        operator, binding, args, ctx,
178                    );
179                }
180            }
181            if name.eq_ignore_ascii_case("coalesce")
182                && binding.as_ref().is_none_or(|binding| binding.builtin)
183            {
184                for argument in args {
185                    let value = eval(argument, ctx)?;
186                    if !matches!(value, Value::Null) {
187                        return Ok(value);
188                    }
189                }
190                return Ok(Value::Null);
191            }
192            if binding.as_ref().is_some_and(|binding| {
193                binding.builtin
194                    && binding.dispatch == Some(crate::ast::FunctionDispatch::BetweenSymmetric)
195            }) {
196                let [value, low, high] = args.as_slice() else {
197                    return Err(SQLError::TypeMismatch(
198                        "BETWEEN SYMMETRIC takes 3 args".into(),
199                    ));
200                };
201                let forward = eval_between(value, low, high, ctx, 0)?;
202                if forward == Value::Bool(true) {
203                    return Ok(forward);
204                }
205                let backward = eval_between(value, high, low, ctx, 2)?;
206                return Ok(match (forward, backward) {
207                    (_, Value::Bool(true)) => Value::Bool(true),
208                    (Value::Null, _) | (_, Value::Null) => Value::Null,
209                    _ => Value::Bool(false),
210                });
211            }
212            if let Some(access) = binding
213                .as_ref()
214                .and_then(|binding| binding.dispatch)
215                .and_then(|dispatch| {
216                    crate::ast::ArrayAccess::from_dispatch(dispatch, args.len(), |index| {
217                        matches!(args[index], Expr::Literal(Value::Null))
218                    })
219                })
220            {
221                let control = uqa_core::memory::ProductionControl::uncontrolled();
222                return Ok(
223                    super::eval_array_access_with_control(access?, &control, |index| {
224                        Ok(control.finish(eval(&args[index], ctx)?, None)?)
225                    })?
226                    .into_uncontrolled()
227                    .expect("ordinary array access"),
228                );
229            }
230            // A set-returning built-in cannot produce the one value this expression needs; `PostgreSQL` rejects it before evaluating its arguments.
231            if let Some(binding) = binding.as_ref().filter(|binding| binding.builtin) {
232                if crate::semantics::sets::static_setness::builtin_call_returns_set(
233                    name,
234                    Some(binding),
235                ) {
236                    return Err(crate::semantics::sets::placement::set_valued_call_error());
237                }
238            }
239            let call_args = evaluate_call_args(args, ctx)?;
240            if let Some(binding) = binding {
241                if binding.builtin {
242                    return eval_bound_builtin_function_call(binding, call_args, ctx);
243                }
244                let engine = ctx.engine.ok_or_else(|| {
245                    SQLError::Unsupported(
246                        "bound user function requires a logical engine session".into(),
247                    )
248                })?;
249                engine
250                    .call_bound_user_function(binding, &call_args)
251                    .unwrap_or_else(|| Err(SQLError::UnknownFunction(binding.name.clone())))
252            } else {
253                eval_function_call(name, call_args, ctx)
254            }
255        }
256        Expr::WindowCall { name, .. } => Err(SQLError::Unsupported(format!(
257            "window function `{name}` must be evaluated by the window-aware executor"
258        ))),
259        Expr::Case {
260            base,
261            when,
262            else_branch,
263        } => {
264            let base_value = match base {
265                Some(b) => Some(eval(b, ctx)?),
266                None => None,
267            };
268            for (cond, result) in when {
269                let matched = match &base_value {
270                    Some(bv) => {
271                        super::eval_value_comparison_truth_with_engine(
272                            BinaryOp::Equal,
273                            bv,
274                            &eval(cond, ctx)?,
275                            &uqa_core::memory::ProductionControl::uncontrolled(),
276                            ctx.engine,
277                            ctx.enum_comparison_state_at(0),
278                        )? == Some(true)
279                    }
280                    None => truthy(&eval(cond, ctx)?),
281                };
282                if matched {
283                    return eval(result, ctx);
284                }
285            }
286            match else_branch {
287                Some(e) => eval(e, ctx),
288                None => Ok(Value::Null),
289            }
290        }
291        Expr::Cast { expr, ty, .. } => {
292            let source_ty = explicit_expr_type(expr);
293            let v = eval(expr, ctx)?;
294            cast_value_with_type_resolution(&v, source_ty, ty, ctx.engine)
295        }
296        Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
297            Err(SQLError::Unsupported(
298                "query-valued expressions must be lowered to physical ScalarExpr/QueryPlan slots"
299                    .into(),
300            ))
301        }
302        Expr::Binary { op, lhs, rhs } => eval_binary(*op, lhs, rhs, ctx),
303        Expr::UnaryMinus(inner) => {
304            let source_ty = explicit_expr_type(inner);
305            let value = eval(inner, ctx)?;
306            negate_value(&value, source_ty)
307        }
308        Expr::Not(inner) => {
309            // SQL three-valued logic: NOT NULL -> NULL.
310            let v = eval(inner, ctx)?;
311            if matches!(v, Value::Null) {
312                return Ok(Value::Null);
313            }
314            Ok(Value::Bool(!truthy(&v)))
315        }
316        Expr::And(items) => {
317            // Kleene AND: FALSE dominates, otherwise NULL taints.
318            let mut saw_null = false;
319            for item in items {
320                let v = eval(item, ctx)?;
321                if matches!(v, Value::Null) {
322                    saw_null = true;
323                } else if !truthy(&v) {
324                    return Ok(Value::Bool(false));
325                }
326            }
327            if saw_null {
328                return Ok(Value::Null);
329            }
330            Ok(Value::Bool(true))
331        }
332        Expr::Or(items) => {
333            // Kleene OR: TRUE dominates, otherwise NULL taints.
334            let mut saw_null = false;
335            for item in items {
336                let v = eval(item, ctx)?;
337                if matches!(v, Value::Null) {
338                    saw_null = true;
339                } else if truthy(&v) {
340                    return Ok(Value::Bool(true));
341                }
342            }
343            if saw_null {
344                return Ok(Value::Null);
345            }
346            Ok(Value::Bool(false))
347        }
348        Expr::IsNull { expr, negated } => {
349            let v = eval(expr, ctx)?;
350            Ok(Value::Bool(uqa_core::sql_null_test(Some(&v), *negated)))
351        }
352        Expr::Between { expr, low, high } => eval_between(expr, low, high, ctx, 0),
353        Expr::InList {
354            expr,
355            list,
356            negated,
357        } => {
358            // Three-valued IN: found -> TRUE, a NULL comparand (or a
359            // NULL needle) downgrades a miss to NULL.
360            let v = eval(expr, ctx)?;
361            let mut saw_null = matches!(v, Value::Null);
362            for item in list {
363                let candidate = eval(item, ctx)?;
364                match compare(BinaryOp::Equal, &v, &candidate, ctx, 0)? {
365                    Some(true) => return Ok(Value::Bool(!*negated)),
366                    Some(false) => {}
367                    None => saw_null = true,
368                }
369            }
370            if saw_null {
371                return Ok(Value::Null);
372            }
373            Ok(Value::Bool(*negated))
374        }
375    }
376}
377
378fn explicit_expr_type(expr: &Expr) -> Option<&str> {
379    match expr {
380        Expr::Cast { ty, .. }
381        | Expr::TypedLiteral { ty, .. }
382        | Expr::CompositeRow {
383            binding: crate::ast::CompositeRowBinding { ty, .. },
384            ..
385        } => Some(ty),
386        Expr::Literal(Value::Int(value)) if i32::try_from(*value).is_ok() => Some("integer"),
387        Expr::Literal(Value::Int(_)) => Some("bigint"),
388        Expr::Literal(Value::Bytes(_)) => Some("bytea"),
389        Expr::Literal(Value::BitString(_)) => Some("bit"),
390        _ => None,
391    }
392}
393
394/// Evaluate `PostgreSQL`'s two comparisons in order, including repeated value
395/// evaluation and the short circuit after a false lower-bound comparison.
396fn eval_between(
397    expression: &Expr,
398    low: &Expr,
399    high: &Expr,
400    context: &EvalContext<'_>,
401    slot: usize,
402) -> Result<Value> {
403    let ge = compare(
404        BinaryOp::GreaterEqual,
405        &eval(expression, context)?,
406        &eval(low, context)?,
407        context,
408        slot,
409    )?;
410    if ge == Some(false) {
411        return Ok(Value::Bool(false));
412    }
413    let le = compare(
414        BinaryOp::LessEqual,
415        &eval(expression, context)?,
416        &eval(high, context)?,
417        context,
418        slot + 1,
419    )?;
420    Ok(match (ge, le) {
421        (_, Some(false)) => Value::Bool(false),
422        (Some(true), Some(true)) => Value::Bool(true),
423        _ => Value::Null,
424    })
425}
426
427fn compare(
428    op: BinaryOp,
429    left: &Value,
430    right: &Value,
431    context: &EvalContext<'_>,
432    slot: usize,
433) -> Result<Option<bool>> {
434    eval_comparison_truth_with_engine(
435        op,
436        left,
437        right,
438        &uqa_core::memory::ProductionControl::uncontrolled(),
439        context.engine,
440        context.enum_comparison_state_at(slot),
441    )
442}