1use uqa_core::{ArrayValue, Value};
10
11use crate::ast::Expr;
12use crate::error::{Result, SQLError};
13
14use super::binary::{
15 compare_nullable_with_control, eval_binary, truthy, values_equal, values_equal_nullable,
16};
17use super::builtin::eval_bound_builtin_function_call;
18use super::call_arguments::evaluate_call_args;
19use super::call_dispatch::eval_function_call;
20use super::casting::negate_value;
21use super::context::{cast_value_with_type_resolution, EvalContext};
22
23#[expect(
25 clippy::too_many_lines,
26 reason = "builtin dispatch preserves arity, NULL, and error precedence"
27)]
28pub fn eval(expr: &Expr, ctx: &EvalContext<'_>) -> Result<Value> {
29 match expr {
30 Expr::Default => Err(SQLError::Internal(
31 "DEFAULT reached scalar expression evaluation without a mutation target".into(),
32 )),
33 Expr::Literal(v) => Ok(v.clone()),
34 Expr::TypedLiteral { value, ty } => 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 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 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 mut out = Vec::with_capacity(elements.len());
83 for e in elements {
84 out.push(eval(e, ctx)?);
85 }
86 ArrayValue::try_new(out).map(Value::Array).ok_or_else(|| {
87 SQLError::TypeMismatch(
88 "multidimensional arrays must have matching dimensions".into(),
89 )
90 })
91 }
92 Expr::CompositeRow { items, binding } => {
93 let control = uqa_core::memory::ProductionControl::uncontrolled();
94 Ok(super::composites::constructor::evaluate_with_control(
95 binding,
96 items.len(),
97 ctx.engine,
98 &control,
99 |index| {
100 control
101 .finish(eval(&items[index], ctx)?, None)
102 .map_err(Into::into)
103 },
104 )?
105 .into_uncontrolled()
106 .expect("ordinary composite constructor"))
107 }
108 Expr::Row(elements) => {
109 let mut out = Vec::with_capacity(elements.len());
110 let mut fields = Vec::with_capacity(elements.len());
111 for element in elements {
112 let scalar = crate::plan::ExpressionPlan::lower(element.clone()).scalar;
113 if let Some(field) = crate::type_resolution::scalar_record_field_type_with_control(
114 &scalar,
115 &crate::RowSchema::default(),
116 ctx.params,
117 ctx.engine,
118 &uqa_core::memory::ProductionControl::uncontrolled(),
119 )? {
120 fields.push(field);
121 }
122 out.push(eval(element, ctx)?);
123 }
124 let row = if fields.len() == out.len() {
125 uqa_core::RowValue::typed(out, fields)?
126 } else {
127 uqa_core::RowValue::new(out)
128 };
129 Ok(Value::Row(row))
130 }
131 Expr::Star | Expr::QualifiedStar(_) => {
132 Err(SQLError::Internal("`*` cannot be evaluated".into()))
133 }
134 Expr::Func {
135 name,
136 binding,
137 args,
138 ..
139 } => {
140 if let Some(binding) = binding {
141 if let Some(error) = &binding.resolution_error {
142 return Err(error.sql_error());
143 }
144 if let Some(hook) = ctx.engine {
145 hook.require_builtin_execute(binding)?;
146 }
147 if let Some(crate::ast::FunctionDispatch::NumericOperator(operator)) =
148 binding.dispatch
149 {
150 return super::numeric_operator::eval_ast_operator(
151 operator, binding, args, ctx,
152 );
153 }
154 }
155 if name.eq_ignore_ascii_case("coalesce")
156 && binding.as_ref().is_none_or(|binding| binding.builtin)
157 {
158 for argument in args {
159 let value = eval(argument, ctx)?;
160 if !matches!(value, Value::Null) {
161 return Ok(value);
162 }
163 }
164 return Ok(Value::Null);
165 }
166 let call_args = evaluate_call_args(args, ctx)?;
167 if let Some(binding) = binding {
168 if binding.builtin {
169 return eval_bound_builtin_function_call(binding, call_args, ctx);
170 }
171 let engine = ctx.engine.ok_or_else(|| {
172 SQLError::Unsupported(
173 "bound user function requires a logical engine session".into(),
174 )
175 })?;
176 engine
177 .call_bound_user_function(binding, &call_args)
178 .unwrap_or_else(|| Err(SQLError::UnknownFunction(binding.name.clone())))
179 } else {
180 eval_function_call(name, call_args, ctx)
181 }
182 }
183 Expr::WindowCall { name, .. } => Err(SQLError::Unsupported(format!(
184 "window function `{name}` must be evaluated by the window-aware executor"
185 ))),
186 Expr::Case {
187 base,
188 when,
189 else_branch,
190 } => {
191 let base_value = match base {
192 Some(b) => Some(eval(b, ctx)?),
193 None => None,
194 };
195 for (cond, result) in when {
196 let matched = match &base_value {
197 Some(bv) => values_equal(bv, &eval(cond, ctx)?)?,
198 None => truthy(&eval(cond, ctx)?),
199 };
200 if matched {
201 return eval(result, ctx);
202 }
203 }
204 match else_branch {
205 Some(e) => eval(e, ctx),
206 None => Ok(Value::Null),
207 }
208 }
209 Expr::Cast { expr, ty, .. } => {
210 let source_ty = explicit_expr_type(expr);
211 let v = eval(expr, ctx)?;
212 cast_value_with_type_resolution(&v, source_ty, ty, ctx.engine)
213 }
214 Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
215 Err(SQLError::Unsupported(
216 "query-valued expressions must be lowered to physical ScalarExpr/QueryPlan slots"
217 .into(),
218 ))
219 }
220 Expr::Binary { op, lhs, rhs } => eval_binary(*op, lhs, rhs, ctx),
221 Expr::UnaryMinus(inner) => {
222 let source_ty = explicit_expr_type(inner);
223 let value = eval(inner, ctx)?;
224 negate_value(&value, source_ty)
225 }
226 Expr::Not(inner) => {
227 let v = eval(inner, ctx)?;
229 if matches!(v, Value::Null) {
230 return Ok(Value::Null);
231 }
232 Ok(Value::Bool(!truthy(&v)))
233 }
234 Expr::And(items) => {
235 let mut saw_null = false;
237 for item in items {
238 let v = eval(item, ctx)?;
239 if matches!(v, Value::Null) {
240 saw_null = true;
241 } else if !truthy(&v) {
242 return Ok(Value::Bool(false));
243 }
244 }
245 if saw_null {
246 return Ok(Value::Null);
247 }
248 Ok(Value::Bool(true))
249 }
250 Expr::Or(items) => {
251 let mut saw_null = false;
253 for item in items {
254 let v = eval(item, ctx)?;
255 if matches!(v, Value::Null) {
256 saw_null = true;
257 } else if truthy(&v) {
258 return Ok(Value::Bool(true));
259 }
260 }
261 if saw_null {
262 return Ok(Value::Null);
263 }
264 Ok(Value::Bool(false))
265 }
266 Expr::IsNull { expr, negated } => {
267 let v = eval(expr, ctx)?;
268 let is_null = matches!(v, Value::Null);
269 Ok(Value::Bool(if *negated { !is_null } else { is_null }))
270 }
271 Expr::Between { expr, low, high } => {
272 let v = eval(expr, ctx)?;
273 let lo = eval(low, ctx)?;
274 let hi = eval(high, ctx)?;
275 eval_between(&v, &lo, &hi)
276 }
277 Expr::InList {
278 expr,
279 list,
280 negated,
281 } => {
282 let v = eval(expr, ctx)?;
285 let mut saw_null = matches!(v, Value::Null);
286 for item in list {
287 let candidate = eval(item, ctx)?;
288 match values_equal_nullable(&v, &candidate)? {
289 Some(true) => return Ok(Value::Bool(!*negated)),
290 Some(false) => {}
291 None => saw_null = true,
292 }
293 }
294 if saw_null {
295 return Ok(Value::Null);
296 }
297 Ok(Value::Bool(*negated))
298 }
299 }
300}
301
302fn explicit_expr_type(expr: &Expr) -> Option<&str> {
303 match expr {
304 Expr::Cast { ty, .. }
305 | Expr::TypedLiteral { ty, .. }
306 | Expr::CompositeRow {
307 binding: crate::ast::CompositeRowBinding { ty, .. },
308 ..
309 } => Some(ty),
310 Expr::Literal(Value::Int(value)) if i32::try_from(*value).is_ok() => Some("integer"),
311 Expr::Literal(Value::Int(_)) => Some("bigint"),
312 Expr::Literal(Value::Bytes(_)) => Some("bytea"),
313 _ => None,
314 }
315}
316
317pub(super) fn eval_between(v: &Value, lo: &Value, hi: &Value) -> Result<Value> {
320 eval_between_with_control(
321 v,
322 lo,
323 hi,
324 &uqa_core::memory::ProductionControl::uncontrolled(),
325 )
326}
327
328pub(super) fn eval_between_with_control(
329 v: &Value,
330 lo: &Value,
331 hi: &Value,
332 control: &uqa_core::memory::ProductionControl<'_>,
333) -> Result<Value> {
334 let ge = compare_nullable_with_control(v, lo, control)?.map(|ord| ord.is_ge());
335 let le = compare_nullable_with_control(v, hi, control)?.map(|ord| ord.is_le());
336 Ok(match (ge, le) {
337 (Some(false), _) | (_, Some(false)) => Value::Bool(false),
338 (Some(true), Some(true)) => Value::Bool(true),
339 _ => Value::Null,
340 })
341}