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