1use uqa_core::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
21pub fn eval(expr: &Expr, ctx: &EvalContext<'_>) -> Result<Value> {
23 let value = eval_inner(expr, ctx)?;
24 if matches!(
25 expr,
26 Expr::Literal(_)
27 | Expr::TypedLiteral { .. }
28 | Expr::Param(_)
29 | Expr::Column(_)
30 | Expr::QualifiedColumn { .. }
31 | Expr::InternalColumn(_)
32 | Expr::Func { .. }
33 ) {
34 if let Some(engine) = ctx.engine {
35 let control = uqa_core::memory::ProductionControl::uncontrolled();
36 return super::composites::retain_value_with_control(
37 control.finish(value, None)?,
38 engine.composite_types(),
39 &control,
40 )?
41 .into_uncontrolled()
42 .map_err(|_| SQLError::Internal("ordinary expression retention".into()));
43 }
44 }
45 Ok(value)
46}
47
48#[expect(
49 clippy::too_many_lines,
50 reason = "builtin dispatch preserves arity, NULL, and error precedence"
51)]
52fn eval_inner(expr: &Expr, ctx: &EvalContext<'_>) -> Result<Value> {
53 match expr {
54 Expr::Default => Err(SQLError::Internal(
55 "DEFAULT reached scalar expression evaluation without a mutation target".into(),
56 )),
57 Expr::Literal(v) => Ok(v.clone()),
58 Expr::RetainedLiteral(literal) => eval(&literal.materialize()?, ctx),
59 Expr::TypedLiteral { value, ty, .. } => {
60 Ok(super::composites::literal::evaluate_with_control(
61 value,
62 ty,
63 ctx.engine,
64 &uqa_core::memory::ProductionControl::uncontrolled(),
65 )?
66 .into_uncontrolled()
67 .expect("ordinary constant result"))
68 }
69 Expr::Param(i) => match i.checked_sub(1).and_then(|index| ctx.params.get(index)) {
70 Some(parameter) => parameter.to_value(),
71 None => Err(SQLError::MissingParam(*i)),
72 },
73 Expr::Column(name) => {
74 if ctx.row_lookup()?.column_is_ambiguous(name) {
78 return Err(SQLError::AmbiguousColumn(name.to_string()));
79 }
80 Ok(ctx
81 .row_lookup()?
82 .column(name)
83 .cloned()
84 .unwrap_or(Value::Null))
85 }
86 Expr::QualifiedColumn { qualifier, column } => {
87 if ctx
88 .row_lookup()?
89 .qualified_column_is_ambiguous(qualifier, column)
90 {
91 return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
92 }
93 Ok(ctx
94 .row_lookup()?
95 .qualified_column(qualifier, column)
96 .cloned()
97 .unwrap_or(Value::Null))
98 }
99 Expr::InternalColumn(column) => ctx
100 .row_lookup()?
101 .internal_column(*column)
102 .cloned()
103 .ok_or_else(|| {
104 SQLError::Internal(format!(
105 "internal relation attribute {column:?} is unavailable"
106 ))
107 }),
108 Expr::Array(elements) => {
109 let scalar = crate::plan::ExpressionPlan::lower(Expr::Array(elements.clone())).scalar;
110 let crate::ScalarExpr::Array(items) = scalar else {
111 unreachable!("array lowering")
112 };
113 let control = uqa_core::memory::ProductionControl::uncontrolled();
114 let element_type = crate::type_resolution::scalar_array_input_type_with_control(
115 &items,
116 &crate::RowSchema::default(),
117 ctx.params,
118 ctx.engine,
119 &control,
120 )?;
121 Ok(super::construct_array_with_control(
122 elements.len(),
123 element_type.as_deref(),
124 &control,
125 |index| Ok(control.finish(eval(&elements[index], ctx)?, None)?),
126 )?
127 .into_uncontrolled()
128 .expect("ordinary array constructor"))
129 }
130 Expr::CompositeRow { items, binding } => {
131 let control = uqa_core::memory::ProductionControl::uncontrolled();
132 Ok(super::composites::constructor::evaluate_with_control(
133 binding,
134 items.len(),
135 ctx.engine,
136 &control,
137 |index| {
138 control
139 .finish(eval(&items[index], ctx)?, None)
140 .map_err(Into::into)
141 },
142 )?
143 .into_uncontrolled()
144 .expect("ordinary composite constructor"))
145 }
146 Expr::Row(elements) => {
147 let mut out = Vec::with_capacity(elements.len());
148 let mut fields = Vec::with_capacity(elements.len());
149 for element in elements {
150 let scalar = crate::plan::ExpressionPlan::lower(element.clone()).scalar;
151 if let Some(field) = crate::type_resolution::scalar_record_field_type_with_control(
152 &scalar,
153 &crate::RowSchema::default(),
154 ctx.params,
155 ctx.engine,
156 &uqa_core::memory::ProductionControl::uncontrolled(),
157 )? {
158 fields.push(field);
159 }
160 out.push(eval(element, ctx)?);
161 }
162 let row = if fields.len() == out.len() {
163 uqa_core::RowValue::typed(out, fields)?
164 } else {
165 uqa_core::RowValue::new(out)
166 };
167 Ok(Value::Row(row))
168 }
169 Expr::Star | Expr::QualifiedStar(_) => {
170 Err(SQLError::Internal("`*` cannot be evaluated".into()))
171 }
172 Expr::Func {
173 name,
174 binding,
175 args,
176 ..
177 } => {
178 if let Some(binding) = binding {
179 if let Some(error) = &binding.resolution_error {
180 return Err(error.sql_error());
181 }
182 if let Some(clause) = crate::catalog::collations::expression::ast_clause(expr)? {
183 return eval(clause.argument, ctx);
185 }
186 if let Some(hook) = ctx.engine {
187 hook.require_builtin_execute(binding)?;
188 }
189 if let Some(dispatch) = binding.dispatch {
190 if let Some(result) =
191 super::eval_distinct_boolean(dispatch, args.len(), |index| {
192 eval(&args[index], ctx)
193 })
194 {
195 return result;
196 }
197 }
198 if let Some(crate::ast::FunctionDispatch::NumericOperator(operator)) =
199 binding.dispatch
200 {
201 return super::numeric_operator::eval_ast_operator(
202 operator, binding, args, ctx,
203 );
204 }
205 }
206 if name.eq_ignore_ascii_case("coalesce")
207 && binding.as_ref().is_none_or(|binding| binding.builtin)
208 {
209 for argument in args {
210 let value = eval(argument, ctx)?;
211 if !matches!(value, Value::Null) {
212 return Ok(value);
213 }
214 }
215 return Ok(Value::Null);
216 }
217 if binding.as_ref().is_some_and(|binding| {
218 binding.builtin
219 && binding.dispatch == Some(crate::ast::FunctionDispatch::BetweenSymmetric)
220 }) {
221 let [value, low, high] = args.as_slice() else {
222 return Err(SQLError::TypeMismatch(
223 "BETWEEN SYMMETRIC takes 3 args".into(),
224 ));
225 };
226 let forward = eval_between(value, low, high, ctx, 0)?;
227 if forward == Value::Bool(true) {
228 return Ok(forward);
229 }
230 let backward = eval_between(value, high, low, ctx, 2)?;
231 return Ok(match (forward, backward) {
232 (_, Value::Bool(true)) => Value::Bool(true),
233 (Value::Null, _) | (_, Value::Null) => Value::Null,
234 _ => Value::Bool(false),
235 });
236 }
237 if let Some(assignment) = binding.as_ref().and_then(|binding| binding.assignment()) {
238 let control = uqa_core::memory::ProductionControl::uncontrolled();
239 let catalog = ctx.engine.map(super::EngineValueCatalog);
240 return Ok(crate::assignment::path::evaluate(
241 assignment,
242 args.len(),
243 catalog
244 .as_ref()
245 .map(|catalog| catalog as &dyn super::SQLValueCatalog),
246 &control,
247 |index| Ok(control.finish(eval(&args[index], ctx)?, None)?),
248 )?
249 .into_uncontrolled()
250 .expect("ordinary array assignment"));
251 }
252 if let Some(access) = binding
253 .as_ref()
254 .and_then(|binding| binding.dispatch)
255 .and_then(|dispatch| {
256 crate::ast::ArrayAccess::from_dispatch(dispatch, args.len(), |index| {
257 matches!(args[index], Expr::Literal(Value::Null))
258 })
259 })
260 {
261 let control = uqa_core::memory::ProductionControl::uncontrolled();
262 let catalog = ctx.engine.map(super::EngineValueCatalog);
263 return Ok(super::eval_array_access_with_catalog_and_control(
264 access?,
265 catalog
266 .as_ref()
267 .map(|catalog| catalog as &dyn super::SQLValueCatalog),
268 &control,
269 |index| Ok(control.finish(eval(&args[index], ctx)?, None)?),
270 )?
271 .into_uncontrolled()
272 .expect("ordinary array access"));
273 }
274 if let Some(binding) = binding.as_ref().filter(|binding| binding.builtin) {
276 if crate::semantics::sets::static_setness::builtin_call_returns_set(
277 name,
278 Some(binding),
279 ) {
280 return Err(crate::semantics::sets::placement::set_valued_call_error());
281 }
282 }
283 let call_args = evaluate_call_args(args, ctx)?;
284 if let Some(binding) = binding {
285 if binding.builtin {
286 return eval_bound_builtin_function_call(binding, call_args, ctx);
287 }
288 let engine = ctx.engine.ok_or_else(|| {
289 SQLError::Unsupported(
290 "bound user function requires a logical engine session".into(),
291 )
292 })?;
293 engine
294 .call_bound_user_function(binding, &call_args)
295 .unwrap_or_else(|| Err(SQLError::UnknownFunction(binding.name.clone())))
296 } else {
297 eval_function_call(name, call_args, ctx)
298 }
299 }
300 Expr::WindowCall { name, .. } => Err(SQLError::Unsupported(format!(
301 "window function `{name}` must be evaluated by the window-aware executor"
302 ))),
303 Expr::Case {
304 base,
305 when,
306 else_branch,
307 } => {
308 let base_value = match base {
309 Some(b) => Some(eval(b, ctx)?),
310 None => None,
311 };
312 for (cond, result) in when {
313 let matched = match &base_value {
314 Some(bv) => {
315 super::eval_value_comparison_truth_with_engine(
316 BinaryOp::Equal,
317 bv,
318 &eval(cond, ctx)?,
319 &uqa_core::memory::ProductionControl::uncontrolled(),
320 ctx.engine,
321 ctx.enum_comparison_state_at(0),
322 )? == Some(true)
323 }
324 None => truthy(&eval(cond, ctx)?),
325 };
326 if matched {
327 return eval(result, ctx);
328 }
329 }
330 match else_branch {
331 Some(e) => eval(e, ctx),
332 None => Ok(Value::Null),
333 }
334 }
335 Expr::Cast { expr, ty, .. } => {
336 let source_ty = explicit_expr_type(expr);
337 let v = eval(expr, ctx)?;
338 cast_value_with_type_resolution(&v, source_ty, ty, ctx.engine)
339 }
340 Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
341 Err(SQLError::Unsupported(
342 "query-valued expressions must be lowered to physical ScalarExpr/QueryPlan slots"
343 .into(),
344 ))
345 }
346 Expr::Binary { op, lhs, rhs } => eval_binary(*op, lhs, rhs, ctx),
347 Expr::UnaryMinus(inner) => {
348 let source_ty = explicit_expr_type(inner);
349 let value = eval(inner, ctx)?;
350 negate_value(&value, source_ty)
351 }
352 Expr::Not(inner) => {
353 let v = eval(inner, ctx)?;
355 if matches!(v, Value::Null) {
356 return Ok(Value::Null);
357 }
358 Ok(Value::Bool(!truthy(&v)))
359 }
360 Expr::And(items) => {
361 let mut saw_null = false;
363 for item in items {
364 let v = eval(item, ctx)?;
365 if matches!(v, Value::Null) {
366 saw_null = true;
367 } else if !truthy(&v) {
368 return Ok(Value::Bool(false));
369 }
370 }
371 if saw_null {
372 return Ok(Value::Null);
373 }
374 Ok(Value::Bool(true))
375 }
376 Expr::Or(items) => {
377 let mut saw_null = false;
379 for item in items {
380 let v = eval(item, ctx)?;
381 if matches!(v, Value::Null) {
382 saw_null = true;
383 } else if truthy(&v) {
384 return Ok(Value::Bool(true));
385 }
386 }
387 if saw_null {
388 return Ok(Value::Null);
389 }
390 Ok(Value::Bool(false))
391 }
392 Expr::IsNull { expr, negated } => {
393 let v = eval(expr, ctx)?;
394 Ok(Value::Bool(super::sql_null_test_with_control(
395 &v,
396 *negated,
397 ctx.engine,
398 &uqa_core::memory::ProductionControl::uncontrolled(),
399 )?))
400 }
401 Expr::Between { expr, low, high } => eval_between(expr, low, high, ctx, 0),
402 Expr::InList {
403 expr,
404 list,
405 negated,
406 } => {
407 let v = eval(expr, ctx)?;
410 let mut saw_null = matches!(v, Value::Null);
411 for item in list {
412 let candidate = eval(item, ctx)?;
413 match compare(BinaryOp::Equal, &v, &candidate, ctx, 0)? {
414 Some(true) => return Ok(Value::Bool(!*negated)),
415 Some(false) => {}
416 None => saw_null = true,
417 }
418 }
419 if saw_null {
420 return Ok(Value::Null);
421 }
422 Ok(Value::Bool(*negated))
423 }
424 }
425}
426
427fn explicit_expr_type(expr: &Expr) -> Option<&str> {
428 match expr {
429 Expr::Cast { ty, .. }
430 | Expr::TypedLiteral { ty, .. }
431 | Expr::CompositeRow {
432 binding: crate::ast::CompositeRowBinding { ty, .. },
433 ..
434 } => Some(ty),
435 Expr::RetainedLiteral(literal) => literal.0.declaration.as_deref().or(match literal.0.ty {
436 crate::ast::ColumnType::Bytea => Some("bytea"),
437 crate::ast::ColumnType::Bit(_) => Some("bit"),
438 _ => None,
439 }),
440 Expr::Literal(Value::Int(value)) if i32::try_from(*value).is_ok() => Some("integer"),
441 Expr::Literal(Value::Int(_)) => Some("bigint"),
442 Expr::Literal(Value::Bytes(_)) => Some("bytea"),
443 Expr::Literal(Value::BitString(_)) => Some("bit"),
444 _ => None,
445 }
446}
447
448fn eval_between(
451 expression: &Expr,
452 low: &Expr,
453 high: &Expr,
454 context: &EvalContext<'_>,
455 slot: usize,
456) -> Result<Value> {
457 let ge = compare(
458 BinaryOp::GreaterEqual,
459 &eval(expression, context)?,
460 &eval(low, context)?,
461 context,
462 slot,
463 )?;
464 if ge == Some(false) {
465 return Ok(Value::Bool(false));
466 }
467 let le = compare(
468 BinaryOp::LessEqual,
469 &eval(expression, context)?,
470 &eval(high, context)?,
471 context,
472 slot + 1,
473 )?;
474 Ok(match (ge, le) {
475 (_, Some(false)) => Value::Bool(false),
476 (Some(true), Some(true)) => Value::Bool(true),
477 _ => Value::Null,
478 })
479}
480
481fn compare(
482 op: BinaryOp,
483 left: &Value,
484 right: &Value,
485 context: &EvalContext<'_>,
486 slot: usize,
487) -> Result<Option<bool>> {
488 eval_comparison_truth_with_engine(
489 op,
490 left,
491 right,
492 &uqa_core::memory::ProductionControl::uncontrolled(),
493 context.engine,
494 context.enum_comparison_state_at(slot),
495 )
496}