1use std::sync::Arc;
64
65use super::runtime::values::runtime_exact_integer_cmp;
66use reddb_rql::ast::{BinOp, Expr, FieldRef, UnaryOp};
67use reddb_types::coerce::coerce_via_catalog;
68use reddb_types::coercion_spine;
69use reddb_types::function_catalog::FUNCTION_CATALOG;
70use reddb_types::operator_catalog::OperatorEntry;
71use reddb_types::{DataType, Value};
72
73pub trait Row {
79 fn get(&self, field: &FieldRef) -> Option<Value>;
84
85 fn try_get(&self, field: &FieldRef) -> Result<Option<Value>, EvalError> {
88 Ok(self.get(field))
89 }
90}
91
92impl<F> Row for F
96where
97 F: Fn(&FieldRef) -> Option<Value>,
98{
99 fn get(&self, field: &FieldRef) -> Option<Value> {
100 self(field)
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
108pub enum EvalError {
109 UnknownColumn(FieldRef),
111 UnboundParameter(usize),
115 OperatorMismatch {
118 op: BinOp,
119 lhs: DataType,
120 rhs: DataType,
121 },
122 UnaryMismatch { op: UnaryOp, operand: DataType },
124 UnknownFunction { name: String, args: Vec<DataType> },
128 ImplicitCastFailed {
133 from: DataType,
134 to: DataType,
135 reason: String,
136 },
137 CastFailed {
139 from: DataType,
140 to: DataType,
141 reason: String,
142 },
143 ArithmeticOverflow { op: BinOp },
145 DivisionByZero,
147 InvalidNumericResult { function: String, reason: String },
150 JsonParseFailed { reason: String },
152 ReadLimitExceeded {
154 required_bytes: usize,
155 limit_bytes: usize,
156 },
157 EmptyInList,
161}
162
163impl std::fmt::Display for EvalError {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 match self {
166 EvalError::UnknownColumn(field) => write!(f, "unknown column: {field:?}"),
167 EvalError::UnboundParameter(idx) => {
168 write!(f, "unbound query parameter: ${idx}")
169 }
170 EvalError::OperatorMismatch { op, lhs, rhs } => {
171 write!(f, "operator {op:?} not defined for ({lhs:?}, {rhs:?})")
172 }
173 EvalError::UnaryMismatch { op, operand } => {
174 write!(f, "unary {op:?} not defined for {operand:?}")
175 }
176 EvalError::UnknownFunction { name, args } => {
177 write!(f, "unknown function: {name}({args:?})")
178 }
179 EvalError::ImplicitCastFailed { from, to, reason } => {
180 write!(f, "implicit cast {from:?} -> {to:?} failed: {reason}")
181 }
182 EvalError::CastFailed { from, to, reason } => {
183 write!(f, "cast {from:?} -> {to:?} failed: {reason}")
184 }
185 EvalError::ArithmeticOverflow { op } => {
186 write!(f, "arithmetic overflow in {op:?}")
187 }
188 EvalError::DivisionByZero => write!(f, "division by zero"),
189 EvalError::InvalidNumericResult { function, reason } => {
190 write!(f, "invalid numeric result in {function}: {reason}")
191 }
192 EvalError::JsonParseFailed { reason } => {
193 write!(f, "JSON_PARSE failed to parse JSON: {reason}")
194 }
195 EvalError::ReadLimitExceeded {
196 required_bytes,
197 limit_bytes,
198 } => write!(
199 f,
200 "read memory limit exceeded: requires {required_bytes} bytes, limit {limit_bytes} bytes"
201 ),
202 EvalError::EmptyInList => write!(f, "IN list is empty"),
203 }
204 }
205}
206
207impl std::error::Error for EvalError {}
208
209pub fn evaluate(expr: &Expr, row: &dyn Row) -> Result<Value, EvalError> {
214 evaluate_with_literal_decoder(expr, row, &|value| Ok(value.clone()))
215}
216
217pub fn evaluate_with_literal_decoder(
220 expr: &Expr,
221 row: &dyn Row,
222 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
223) -> Result<Value, EvalError> {
224 match expr {
225 Expr::Literal { value, .. } => decode_literal(value),
226 Expr::Column { field, .. } => row
227 .try_get(field)?
228 .ok_or_else(|| EvalError::UnknownColumn(field.clone())),
229 Expr::Parameter { index, .. } => Err(EvalError::UnboundParameter(*index)),
230 Expr::UnaryOp { op, operand, .. } => eval_unary(*op, operand, row, decode_literal),
231 Expr::BinaryOp { op, lhs, rhs, .. } => eval_binary(*op, lhs, rhs, row, decode_literal),
232 Expr::Cast { inner, target, .. } => eval_cast(inner, *target, row, decode_literal),
233 Expr::FunctionCall { name, args, .. } => eval_function(name, args, row, decode_literal),
234 Expr::Case {
235 branches, else_, ..
236 } => eval_case(branches, else_.as_deref(), row, decode_literal),
237 Expr::IsNull {
238 operand, negated, ..
239 } => {
240 let v = evaluate_with_literal_decoder(operand, row, decode_literal)?;
241 let is_null = v.is_null();
242 Ok(Value::Boolean(if *negated { !is_null } else { is_null }))
243 }
244 Expr::InList {
245 target,
246 values,
247 negated,
248 ..
249 } => eval_in_list(target, values, *negated, row, decode_literal),
250 Expr::Between {
251 target,
252 low,
253 high,
254 negated,
255 ..
256 } => eval_between(target, low, high, *negated, row, decode_literal),
257 Expr::Subquery { .. } => Err(EvalError::UnknownFunction {
258 name: "SUBQUERY".to_string(),
259 args: Vec::new(),
260 }),
261 Expr::WindowFunctionCall { name, .. } => Err(EvalError::UnknownFunction {
262 name: format!("{name} OVER (...)"),
263 args: Vec::new(),
264 }),
265 }
266}
267
268fn eval_unary(
269 op: UnaryOp,
270 operand: &Expr,
271 row: &dyn Row,
272 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
273) -> Result<Value, EvalError> {
274 let v = evaluate_with_literal_decoder(operand, row, decode_literal)?;
275 if v.is_null() {
276 return Ok(Value::Null);
277 }
278 match op {
279 UnaryOp::Neg => match &v {
280 Value::Integer(n) => n
281 .checked_neg()
282 .map(Value::Integer)
283 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
284 Value::BigInt(n) => n
285 .checked_neg()
286 .map(Value::BigInt)
287 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
288 Value::Float(n) => Ok(Value::Float(-*n)),
289 Value::Decimal(n) => n
290 .checked_neg()
291 .map(Value::Decimal)
292 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
293 other => Err(EvalError::UnaryMismatch {
294 op,
295 operand: other.data_type(),
296 }),
297 },
298 UnaryOp::Not => match &v {
299 Value::Boolean(b) => Ok(Value::Boolean(!b)),
300 other => Err(EvalError::UnaryMismatch {
301 op,
302 operand: other.data_type(),
303 }),
304 },
305 }
306}
307
308fn eval_binary(
309 op: BinOp,
310 lhs: &Expr,
311 rhs: &Expr,
312 row: &dyn Row,
313 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
314) -> Result<Value, EvalError> {
315 let l = evaluate_with_literal_decoder(lhs, row, decode_literal)?;
319 let r = evaluate_with_literal_decoder(rhs, row, decode_literal)?;
320
321 match op {
322 BinOp::And => return three_valued_and(&l, &r),
323 BinOp::Or => return three_valued_or(&l, &r),
324 _ => {}
325 }
326
327 if l.is_null() || r.is_null() {
328 return Ok(Value::Null);
329 }
330
331 if matches!(
334 op,
335 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge
336 ) {
337 if let Some(order) = runtime_exact_integer_cmp(&l, &r) {
338 return Ok(Value::Boolean(match op {
339 BinOp::Eq => order.is_eq(),
340 BinOp::Ne => !order.is_eq(),
341 BinOp::Lt => order.is_lt(),
342 BinOp::Le => !order.is_gt(),
343 BinOp::Gt => order.is_gt(),
344 BinOp::Ge => !order.is_lt(),
345 _ => unreachable!("integer comparison operator was admitted"),
346 }));
347 }
348 }
349
350 let lhs_dt = l.data_type();
351 let rhs_dt = r.data_type();
352 let (entry, coercions) =
353 coercion_spine::resolve_binop(op, lhs_dt, rhs_dt).ok_or(EvalError::OperatorMismatch {
354 op,
355 lhs: lhs_dt,
356 rhs: rhs_dt,
357 })?;
358
359 let l = match coercions.at(0) {
360 Some(target) => apply_implicit_cast(&l, lhs_dt, target)?,
361 None => l,
362 };
363 let r = match coercions.at(1) {
364 Some(target) => apply_implicit_cast(&r, rhs_dt, target)?,
365 None => r,
366 };
367
368 dispatch_binop(op, entry, l, r)
369}
370
371fn dispatch_binop(
372 op: BinOp,
373 entry: &OperatorEntry,
374 l: Value,
375 r: Value,
376) -> Result<Value, EvalError> {
377 match op {
378 BinOp::Add => arith_add(entry, l, r),
379 BinOp::Sub => arith_sub(entry, l, r),
380 BinOp::Mul => arith_mul(entry, l, r),
381 BinOp::Div => arith_div(entry, l, r),
382 BinOp::Mod => arith_mod(entry, l, r),
383 BinOp::Concat => match (&l, &r) {
384 (Value::Text(a), Value::Text(b)) => {
385 let mut s = String::with_capacity(a.len() + b.len());
386 s.push_str(a);
387 s.push_str(b);
388 Ok(Value::Text(Arc::from(s)))
389 }
390 _ => Err(EvalError::OperatorMismatch {
391 op,
392 lhs: l.data_type(),
393 rhs: r.data_type(),
394 }),
395 },
396 BinOp::Eq => Ok(Value::Boolean(values_equal(&l, &r))),
397 BinOp::Ne => Ok(Value::Boolean(!values_equal(&l, &r))),
398 BinOp::Lt => cmp_op(op, l, r, |o| o == std::cmp::Ordering::Less),
399 BinOp::Le => cmp_op(op, l, r, |o| o != std::cmp::Ordering::Greater),
400 BinOp::Gt => cmp_op(op, l, r, |o| o == std::cmp::Ordering::Greater),
401 BinOp::Ge => cmp_op(op, l, r, |o| o != std::cmp::Ordering::Less),
402 BinOp::And | BinOp::Or => unreachable!("handled before dispatch"),
403 }
404}
405
406fn arith_add(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
407 match entry.return_type {
408 DataType::Integer => match (l, r) {
409 (Value::Integer(a), Value::Integer(b)) => a
410 .checked_add(b)
411 .map(Value::Integer)
412 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Add }),
413 _ => unreachable_after_coercion("Add", DataType::Integer),
414 },
415 DataType::BigInt => match (l, r) {
416 (Value::BigInt(a), Value::BigInt(b)) => a
417 .checked_add(b)
418 .map(Value::BigInt)
419 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Add }),
420 _ => unreachable_after_coercion("Add", DataType::BigInt),
421 },
422 DataType::Float => checked_float_binop(BinOp::Add, as_f64(&l) + as_f64(&r)),
423 DataType::Decimal => match (l, r) {
424 (Value::Decimal(a), Value::Decimal(b)) => a
425 .checked_add(b)
426 .map(Value::Decimal)
427 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Add }),
428 _ => unreachable_after_coercion("Add", DataType::Decimal),
429 },
430 other => Err(EvalError::OperatorMismatch {
431 op: BinOp::Add,
432 lhs: other,
433 rhs: other,
434 }),
435 }
436}
437
438fn arith_sub(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
439 match entry.return_type {
440 DataType::Integer => match (l, r) {
441 (Value::Integer(a), Value::Integer(b)) => a
442 .checked_sub(b)
443 .map(Value::Integer)
444 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
445 _ => unreachable_after_coercion("Sub", DataType::Integer),
446 },
447 DataType::BigInt => match (l, r) {
448 (Value::BigInt(a), Value::BigInt(b)) => a
449 .checked_sub(b)
450 .map(Value::BigInt)
451 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
452 _ => unreachable_after_coercion("Sub", DataType::BigInt),
453 },
454 DataType::Float => checked_float_binop(BinOp::Sub, as_f64(&l) - as_f64(&r)),
455 DataType::Decimal => match (l, r) {
456 (Value::Decimal(a), Value::Decimal(b)) => a
457 .checked_sub(b)
458 .map(Value::Decimal)
459 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
460 _ => unreachable_after_coercion("Sub", DataType::Decimal),
461 },
462 other => Err(EvalError::OperatorMismatch {
463 op: BinOp::Sub,
464 lhs: other,
465 rhs: other,
466 }),
467 }
468}
469
470fn arith_mul(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
471 match entry.return_type {
472 DataType::Integer => match (l, r) {
473 (Value::Integer(a), Value::Integer(b)) => a
474 .checked_mul(b)
475 .map(Value::Integer)
476 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mul }),
477 _ => unreachable_after_coercion("Mul", DataType::Integer),
478 },
479 DataType::BigInt => match (l, r) {
480 (Value::BigInt(a), Value::BigInt(b)) => a
481 .checked_mul(b)
482 .map(Value::BigInt)
483 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mul }),
484 _ => unreachable_after_coercion("Mul", DataType::BigInt),
485 },
486 DataType::Float => checked_float_binop(BinOp::Mul, as_f64(&l) * as_f64(&r)),
487 other => Err(EvalError::OperatorMismatch {
488 op: BinOp::Mul,
489 lhs: other,
490 rhs: other,
491 }),
492 }
493}
494
495fn arith_div(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
496 match entry.return_type {
499 DataType::Float => {
500 let denom = as_f64(&r);
501 if denom == 0.0 {
502 return Err(EvalError::DivisionByZero);
503 }
504 checked_float_binop(BinOp::Div, as_f64(&l) / denom)
505 }
506 other => Err(EvalError::OperatorMismatch {
507 op: BinOp::Div,
508 lhs: other,
509 rhs: other,
510 }),
511 }
512}
513
514fn arith_mod(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
515 match entry.return_type {
516 DataType::Integer => match (l, r) {
517 (Value::Integer(_), Value::Integer(0)) => Err(EvalError::DivisionByZero),
518 (Value::Integer(a), Value::Integer(b)) => a
519 .checked_rem(b)
520 .map(Value::Integer)
521 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mod }),
522 _ => unreachable_after_coercion("Mod", DataType::Integer),
523 },
524 DataType::BigInt => match (l, r) {
525 (Value::BigInt(_), Value::BigInt(0)) => Err(EvalError::DivisionByZero),
526 (Value::BigInt(a), Value::BigInt(b)) => a
527 .checked_rem(b)
528 .map(Value::BigInt)
529 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mod }),
530 _ => unreachable_after_coercion("Mod", DataType::BigInt),
531 },
532 other => Err(EvalError::OperatorMismatch {
533 op: BinOp::Mod,
534 lhs: other,
535 rhs: other,
536 }),
537 }
538}
539
540fn unreachable_after_coercion(op: &'static str, expected: DataType) -> Result<Value, EvalError> {
541 Err(EvalError::OperatorMismatch {
542 op: match op {
543 "Add" => BinOp::Add,
544 "Sub" => BinOp::Sub,
545 "Mul" => BinOp::Mul,
546 "Div" => BinOp::Div,
547 "Mod" => BinOp::Mod,
548 _ => BinOp::Add,
549 },
550 lhs: expected,
551 rhs: expected,
552 })
553}
554
555fn checked_float_binop(op: BinOp, value: f64) -> Result<Value, EvalError> {
556 if value.is_finite() {
557 Ok(Value::Float(value))
558 } else {
559 Err(EvalError::InvalidNumericResult {
560 function: format!("{op:?}"),
561 reason: "result is NaN or infinite".to_string(),
562 })
563 }
564}
565
566fn as_f64(v: &Value) -> f64 {
567 match v {
568 Value::Float(x) => *x,
569 Value::Integer(x) => *x as f64,
570 Value::BigInt(x) => *x as f64,
571 Value::UnsignedInteger(x) => *x as f64,
572 Value::Decimal(x) => reddb_types::types::decimal_to_f64(*x),
573 _ => 0.0,
574 }
575}
576
577fn cmp_op<F>(op: BinOp, l: Value, r: Value, pick: F) -> Result<Value, EvalError>
578where
579 F: Fn(std::cmp::Ordering) -> bool,
580{
581 let ord = compare_values(&l, &r).ok_or(EvalError::OperatorMismatch {
582 op,
583 lhs: l.data_type(),
584 rhs: r.data_type(),
585 })?;
586 Ok(Value::Boolean(pick(ord)))
587}
588
589fn compare_values(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
594 if let Some(order) = runtime_exact_integer_cmp(a, b) {
595 return Some(order);
596 }
597 match (a, b) {
598 (Value::Integer(x), Value::Integer(y)) => Some(x.cmp(y)),
599 (Value::BigInt(x), Value::BigInt(y)) => Some(x.cmp(y)),
600 (Value::Float(x), Value::Float(y)) => x.partial_cmp(y),
601 (Value::Text(x), Value::Text(y)) => Some(x.as_ref().cmp(y.as_ref())),
602 (Value::Boolean(x), Value::Boolean(y)) => Some(x.cmp(y)),
603 (Value::Timestamp(x), Value::Timestamp(y)) => Some(x.cmp(y)),
604 (Value::TimestampMs(x), Value::TimestampMs(y)) => Some(x.cmp(y)),
605 (Value::Date(x), Value::Date(y)) => Some(x.cmp(y)),
606 (Value::Time(x), Value::Time(y)) => Some(x.cmp(y)),
607 (Value::Uuid(x), Value::Uuid(y)) => Some(x.cmp(y)),
608 (Value::Decimal(x), Value::Decimal(y)) => Some(x.cmp(y)),
609 (Value::Integer(_) | Value::Float(_) | Value::BigInt(_), _) => {
613 let l = as_f64(a);
614 let r = as_f64(b);
615 l.partial_cmp(&r)
616 }
617 _ => None,
618 }
619}
620
621fn values_equal(a: &Value, b: &Value) -> bool {
622 if let Some(order) = runtime_exact_integer_cmp(a, b) {
623 return order.is_eq();
624 }
625 match (a, b) {
626 (Value::Float(x), Value::Float(y)) => x == y,
627 _ => a == b,
628 }
629}
630
631fn three_valued_and(l: &Value, r: &Value) -> Result<Value, EvalError> {
632 match (l, r) {
633 (Value::Boolean(false), _) | (_, Value::Boolean(false)) => Ok(Value::Boolean(false)),
634 (Value::Boolean(true), Value::Boolean(true)) => Ok(Value::Boolean(true)),
635 (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
636 _ => Err(EvalError::OperatorMismatch {
637 op: BinOp::And,
638 lhs: l.data_type(),
639 rhs: r.data_type(),
640 }),
641 }
642}
643
644fn three_valued_or(l: &Value, r: &Value) -> Result<Value, EvalError> {
645 match (l, r) {
646 (Value::Boolean(true), _) | (_, Value::Boolean(true)) => Ok(Value::Boolean(true)),
647 (Value::Boolean(false), Value::Boolean(false)) => Ok(Value::Boolean(false)),
648 (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
649 _ => Err(EvalError::OperatorMismatch {
650 op: BinOp::Or,
651 lhs: l.data_type(),
652 rhs: r.data_type(),
653 }),
654 }
655}
656
657fn apply_implicit_cast(value: &Value, src: DataType, target: DataType) -> Result<Value, EvalError> {
658 if src == target {
659 return Ok(value.clone());
660 }
661 coerce_via_catalog(value, src, target, None).map_err(|reason| EvalError::ImplicitCastFailed {
662 from: src,
663 to: target,
664 reason,
665 })
666}
667
668fn eval_cast(
669 inner: &Expr,
670 target: DataType,
671 row: &dyn Row,
672 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
673) -> Result<Value, EvalError> {
674 let v = evaluate_with_literal_decoder(inner, row, decode_literal)?;
675 if v.is_null() {
676 return Ok(Value::Null);
677 }
678 let src = v.data_type();
679 if src == target {
680 return Ok(v);
681 }
682 coerce_via_catalog(&v, src, target, None).map_err(|reason| EvalError::CastFailed {
683 from: src,
684 to: target,
685 reason,
686 })
687}
688
689fn eval_function(
690 name: &str,
691 args: &[Expr],
692 row: &dyn Row,
693 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
694) -> Result<Value, EvalError> {
695 if name.eq_ignore_ascii_case("COALESCE") {
701 for arg in args {
702 let v = evaluate_with_literal_decoder(arg, row, decode_literal)?;
703 if !v.is_null() {
704 return Ok(v);
705 }
706 }
707 return Ok(Value::Null);
708 }
709
710 let arg_values: Vec<Value> = args
711 .iter()
712 .map(|a| evaluate_with_literal_decoder(a, row, decode_literal))
713 .collect::<Result<Vec<_>, _>>()?;
714 let arg_types: Vec<DataType> = arg_values.iter().map(|v| v.data_type()).collect();
715
716 if arg_values.iter().any(Value::is_null)
721 && FUNCTION_CATALOG
722 .iter()
723 .any(|entry| entry.name.eq_ignore_ascii_case(name))
724 && FUNCTION_CATALOG
725 .iter()
726 .filter(|entry| entry.name.eq_ignore_ascii_case(name))
727 .all(|entry| !entry.variadic)
728 {
729 return Ok(Value::Null);
730 }
731
732 let (entry, coercions) =
733 coercion_spine::resolve_function(name, &arg_types).ok_or_else(|| {
734 EvalError::UnknownFunction {
735 name: name.to_string(),
736 args: arg_types.clone(),
737 }
738 })?;
739
740 let mut coerced: Vec<Value> = Vec::with_capacity(arg_values.len());
742 for (idx, value) in arg_values.into_iter().enumerate() {
743 let src = arg_types[idx];
744 match coercions.at(idx) {
745 Some(target) if src != target => {
746 coerced.push(apply_implicit_cast(&value, src, target)?);
747 }
748 _ => coerced.push(value),
749 }
750 }
751
752 if !entry.variadic && coerced.iter().any(|v| v.is_null()) {
756 return Ok(Value::Null);
757 }
758
759 dispatch_function(entry.name, &coerced)
760}
761
762fn dispatch_function(name: &str, args: &[Value]) -> Result<Value, EvalError> {
763 match name {
764 "UPPER" => match &args[0] {
765 Value::Text(s) => Ok(Value::Text(Arc::from(s.to_uppercase()))),
766 other => Err(EvalError::UnknownFunction {
767 name: name.to_string(),
768 args: vec![other.data_type()],
769 }),
770 },
771 "LOWER" => match &args[0] {
772 Value::Text(s) => Ok(Value::Text(Arc::from(s.to_lowercase()))),
773 other => Err(EvalError::UnknownFunction {
774 name: name.to_string(),
775 args: vec![other.data_type()],
776 }),
777 },
778 "TRIM" => trim_function(name, args, true, true),
779 "LTRIM" => trim_function(name, args, true, false),
780 "RTRIM" => trim_function(name, args, false, true),
781 "LENGTH" | "CHAR_LENGTH" | "CHARACTER_LENGTH" => match &args[0] {
782 Value::Text(s) => Ok(Value::Integer(s.chars().count() as i64)),
783 other => Err(EvalError::UnknownFunction {
784 name: name.to_string(),
785 args: vec![other.data_type()],
786 }),
787 },
788 "OCTET_LENGTH" => match &args[0] {
789 Value::Text(s) => Ok(Value::Integer(s.len() as i64)),
790 Value::Blob(b) => Ok(Value::Integer(b.len() as i64)),
791 other => Err(EvalError::UnknownFunction {
792 name: name.to_string(),
793 args: vec![other.data_type()],
794 }),
795 },
796 "CONCAT" => {
797 let mut out = String::new();
798 for arg in args {
799 match arg {
800 Value::Null => {}
801 Value::Text(value) => out.push_str(value),
802 _ => {
803 return Err(EvalError::UnknownFunction {
804 name: name.to_string(),
805 args: args.iter().map(Value::data_type).collect(),
806 })
807 }
808 }
809 }
810 Ok(Value::Text(Arc::from(out)))
811 }
812 "JSON_PARSE" => json_parse_value(&args[0]),
813 "JSON_EXTRACT" => Ok(json_extract_value(&args[0], &args[1], false)),
814 "JSON_EXTRACT_TEXT" => Ok(json_extract_value(&args[0], &args[1], true)),
815 "CONTAINS" => Ok(contains_value(&args[0], &args[1])),
816 "ABS" => match &args[0] {
817 Value::Integer(n) => n
818 .checked_abs()
819 .map(Value::Integer)
820 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
821 Value::BigInt(n) => n
822 .checked_abs()
823 .map(Value::BigInt)
824 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
825 Value::Float(n) => Ok(Value::Float(n.abs())),
826 Value::Decimal(n) => n
827 .checked_abs()
828 .map(Value::Decimal)
829 .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
830 other => Err(EvalError::UnknownFunction {
831 name: name.to_string(),
832 args: vec![other.data_type()],
833 }),
834 },
835 "SQRT" => unary_math(name, args, |x| {
836 if x < 0.0 {
837 return Err("input must be greater than or equal to zero");
838 }
839 Ok(x.sqrt())
840 }),
841 "POWER" | "POW" => binary_math(name, args, |base, exp| Ok(base.powf(exp))),
842 "EXP" => unary_math(name, args, |x| Ok(x.exp())),
843 "LN" => unary_math(name, args, |x| {
844 if x <= 0.0 {
845 return Err("input must be greater than zero");
846 }
847 Ok(x.ln())
848 }),
849 "LOG" if args.len() == 1 => unary_math(name, args, |x| {
850 if x <= 0.0 {
851 return Err("input must be greater than zero");
852 }
853 Ok(x.log10())
854 }),
855 "LOG" => binary_math(name, args, |base, x| {
856 if base <= 0.0 {
857 return Err("base must be greater than zero");
858 }
859 if base == 1.0 {
860 return Err("base must not equal one");
861 }
862 if x <= 0.0 {
863 return Err("input must be greater than zero");
864 }
865 Ok(x.log(base))
866 }),
867 "LOG10" => unary_math(name, args, |x| {
868 if x <= 0.0 {
869 return Err("input must be greater than zero");
870 }
871 Ok(x.log10())
872 }),
873 "SIN" => unary_math(name, args, |x| Ok(x.sin())),
874 "COS" => unary_math(name, args, |x| Ok(x.cos())),
875 "TAN" => unary_math(name, args, |x| Ok(x.tan())),
876 "ASIN" | "ARCSIN" => unary_math(name, args, |x| {
877 if !(-1.0..=1.0).contains(&x) {
878 return Err("input must be between -1 and 1");
879 }
880 Ok(x.asin())
881 }),
882 "ACOS" | "ARCCOS" => unary_math(name, args, |x| {
883 if !(-1.0..=1.0).contains(&x) {
884 return Err("input must be between -1 and 1");
885 }
886 Ok(x.acos())
887 }),
888 "ATAN" | "ARCTAN" => unary_math(name, args, |x| Ok(x.atan())),
889 "ATAN2" => binary_math(name, args, |y, x| Ok(y.atan2(x))),
890 "COT" => unary_math(name, args, |x| {
891 let tan = x.tan();
892 if tan == 0.0 {
893 return Err("input must not produce zero tangent");
894 }
895 Ok(1.0 / tan)
896 }),
897 "DEGREES" => unary_math(name, args, |x| Ok(x.to_degrees())),
898 "RADIANS" => unary_math(name, args, |x| Ok(x.to_radians())),
899 "PI" => checked_math_result(name, std::f64::consts::PI),
900 other => Err(EvalError::UnknownFunction {
905 name: other.to_string(),
906 args: args.iter().map(|v| v.data_type()).collect(),
907 }),
908 }
909}
910
911fn trim_function(name: &str, args: &[Value], left: bool, right: bool) -> Result<Value, EvalError> {
912 if args.len() != 1 {
913 return Err(EvalError::UnknownFunction {
914 name: name.to_string(),
915 args: args.iter().map(|v| v.data_type()).collect(),
916 });
917 }
918
919 match &args[0] {
920 Value::Text(s) => {
921 let trimmed = match (left, right) {
922 (true, true) => s.trim(),
923 (true, false) => s.trim_start(),
924 (false, true) => s.trim_end(),
925 (false, false) => s,
926 };
927 Ok(Value::Text(Arc::from(trimmed)))
928 }
929 other => Err(EvalError::UnknownFunction {
930 name: name.to_string(),
931 args: vec![other.data_type()],
932 }),
933 }
934}
935
936fn unary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
937where
938 F: FnOnce(f64) -> Result<f64, &'static str>,
939{
940 let input = math_arg(name, args.first(), 0)?;
941 let value = op(input).map_err(|reason| EvalError::InvalidNumericResult {
942 function: name.to_string(),
943 reason: reason.to_string(),
944 })?;
945 checked_math_result(name, value)
946}
947
948fn binary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
949where
950 F: FnOnce(f64, f64) -> Result<f64, &'static str>,
951{
952 let left = math_arg(name, args.first(), 0)?;
953 let right = math_arg(name, args.get(1), 1)?;
954 let value = op(left, right).map_err(|reason| EvalError::InvalidNumericResult {
955 function: name.to_string(),
956 reason: reason.to_string(),
957 })?;
958 checked_math_result(name, value)
959}
960
961fn math_arg(name: &str, value: Option<&Value>, index: usize) -> Result<f64, EvalError> {
962 let value = value.ok_or_else(|| EvalError::UnknownFunction {
963 name: name.to_string(),
964 args: Vec::new(),
965 })?;
966 let numeric = as_f64(value);
967 if numeric.is_finite() {
968 Ok(numeric)
969 } else {
970 Err(EvalError::InvalidNumericResult {
971 function: name.to_string(),
972 reason: format!("argument {index} is NaN or infinite"),
973 })
974 }
975}
976
977fn checked_math_result(name: &str, value: f64) -> Result<Value, EvalError> {
978 if value.is_finite() {
979 Ok(Value::Float(value))
980 } else {
981 Err(EvalError::InvalidNumericResult {
982 function: name.to_string(),
983 reason: "result is NaN or infinite".to_string(),
984 })
985 }
986}
987
988fn json_extract_value(input: &Value, path: &Value, as_text: bool) -> Value {
989 let Value::Text(path) = path else {
990 return Value::Null;
991 };
992 let Some(json) = value_to_json(input) else {
993 return Value::Null;
994 };
995 let Some(steps) = parse_json_path(path) else {
996 return Value::Null;
997 };
998 let Some(target) = json_path_get(&json, &steps) else {
999 return Value::Null;
1000 };
1001
1002 if as_text {
1003 match target {
1004 crate::serde_json::Value::String(value) => Value::text(value.clone()),
1005 crate::serde_json::Value::Null => Value::Null,
1006 crate::serde_json::Value::Bool(value) => Value::text(value.to_string()),
1007 crate::serde_json::Value::Integer(value) => Value::text(value.to_string()),
1008 crate::serde_json::Value::Number(value) => Value::text(value.to_string()),
1009 other => Value::text(other.to_string_compact()),
1010 }
1011 } else {
1012 Value::text(target.to_string_compact())
1013 }
1014}
1015
1016fn json_parse_value(input: &Value) -> Result<Value, EvalError> {
1017 let Value::Text(text) = input else {
1018 return Err(EvalError::UnknownFunction {
1019 name: "JSON_PARSE".to_string(),
1020 args: vec![input.data_type()],
1021 });
1022 };
1023 crate::serde_json::from_str::<crate::serde_json::Value>(text)
1024 .map(|json| Value::Json(json.to_string_compact().into_bytes()))
1025 .map_err(|err| EvalError::JsonParseFailed {
1026 reason: err.to_string(),
1027 })
1028}
1029
1030fn contains_value(input: &Value, needle: &Value) -> Value {
1031 let Value::Text(needle) = needle else {
1032 return Value::Null;
1033 };
1034 Value::Boolean(value_contains(input, needle))
1035}
1036
1037fn value_contains(value: &Value, needle: &str) -> bool {
1038 match value {
1039 Value::Array(values) => values.iter().any(|value| value_contains(value, needle)),
1040 Value::Json(_) => value_to_json(value)
1041 .as_ref()
1042 .is_some_and(|json| json_value_contains(json, needle)),
1043 Value::Text(value) => value.contains(needle),
1044 other => other.display_string().contains(needle),
1045 }
1046}
1047
1048fn json_value_contains(value: &crate::serde_json::Value, needle: &str) -> bool {
1049 match value {
1050 crate::serde_json::Value::Array(values) => values
1051 .iter()
1052 .any(|value| json_value_contains(value, needle)),
1053 crate::serde_json::Value::Object(map) => {
1059 map.values().any(|value| json_value_contains(value, needle))
1060 }
1061 crate::serde_json::Value::String(value) => value == needle,
1062 crate::serde_json::Value::Integer(value) => value.to_string() == needle,
1063 crate::serde_json::Value::Number(value) => value.to_string() == needle,
1064 crate::serde_json::Value::Decimal(value) => value == needle,
1065 crate::serde_json::Value::Bool(value) => value.to_string() == needle,
1066 crate::serde_json::Value::Null => false,
1067 }
1068}
1069
1070fn value_to_json(value: &Value) -> Option<crate::serde_json::Value> {
1071 match value {
1072 Value::Null => Some(crate::serde_json::Value::Null),
1073 Value::Json(bytes) => reddb_types::document_body_codec::decode_container_to_json(bytes)
1077 .or_else(|| crate::serde_json::from_slice(bytes).ok()),
1078 Value::Text(value) => crate::serde_json::from_str(value).ok(),
1079 _ => None,
1080 }
1081}
1082
1083enum JsonPathStep<'a> {
1084 Field(&'a str),
1085 Index(usize),
1086}
1087
1088fn parse_json_path(path: &str) -> Option<Vec<JsonPathStep<'_>>> {
1089 let path = path.trim();
1090 let rest = path.strip_prefix('$').unwrap_or(path);
1091 let mut steps = Vec::new();
1092 let bytes = rest.as_bytes();
1093 let mut index = 0;
1094 while index < bytes.len() {
1095 match bytes[index] {
1096 b'.' => {
1097 index += 1;
1098 let start = index;
1099 while index < bytes.len() && bytes[index] != b'.' && bytes[index] != b'[' {
1100 index += 1;
1101 }
1102 if start == index {
1103 return None;
1104 }
1105 steps.push(JsonPathStep::Field(
1106 std::str::from_utf8(&bytes[start..index]).ok()?,
1107 ));
1108 }
1109 b'[' => {
1110 index += 1;
1111 let start = index;
1112 while index < bytes.len() && bytes[index] != b']' {
1113 index += 1;
1114 }
1115 if index >= bytes.len() {
1116 return None;
1117 }
1118 steps.push(JsonPathStep::Index(
1119 std::str::from_utf8(&bytes[start..index])
1120 .ok()?
1121 .parse()
1122 .ok()?,
1123 ));
1124 index += 1;
1125 }
1126 _ => return None,
1127 }
1128 }
1129 Some(steps)
1130}
1131
1132fn json_path_get<'a>(
1133 root: &'a crate::serde_json::Value,
1134 steps: &[JsonPathStep<'_>],
1135) -> Option<&'a crate::serde_json::Value> {
1136 let mut current = root;
1137 for step in steps {
1138 current = match (step, current) {
1139 (JsonPathStep::Field(name), crate::serde_json::Value::Object(map)) => map.get(*name)?,
1140 (JsonPathStep::Index(index), crate::serde_json::Value::Array(values)) => {
1141 values.get(*index)?
1142 }
1143 _ => return None,
1144 };
1145 }
1146 Some(current)
1147}
1148
1149fn eval_case(
1150 branches: &[(Expr, Expr)],
1151 else_: Option<&Expr>,
1152 row: &dyn Row,
1153 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1154) -> Result<Value, EvalError> {
1155 for (cond, value) in branches {
1156 let c = evaluate_with_literal_decoder(cond, row, decode_literal)?;
1157 if matches!(c, Value::Boolean(true)) {
1158 return evaluate_with_literal_decoder(value, row, decode_literal);
1159 }
1160 }
1161 match else_ {
1162 Some(e) => evaluate_with_literal_decoder(e, row, decode_literal),
1163 None => Ok(Value::Null),
1164 }
1165}
1166
1167fn eval_in_list(
1168 target: &Expr,
1169 values: &[Expr],
1170 negated: bool,
1171 row: &dyn Row,
1172 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1173) -> Result<Value, EvalError> {
1174 if values.is_empty() {
1175 return Err(EvalError::EmptyInList);
1176 }
1177 let needle = evaluate_with_literal_decoder(target, row, decode_literal)?;
1178 if needle.is_null() {
1179 return Ok(Value::Null);
1180 }
1181 let mut saw_null = false;
1182 for v in values {
1183 let candidate = evaluate_with_literal_decoder(v, row, decode_literal)?;
1184 if candidate.is_null() {
1185 saw_null = true;
1186 continue;
1187 }
1188 if values_equal(&needle, &candidate) {
1189 return Ok(Value::Boolean(!negated));
1190 }
1191 }
1192 if saw_null {
1193 return Ok(Value::Null);
1194 }
1195 Ok(Value::Boolean(negated))
1196}
1197
1198fn eval_between(
1199 target: &Expr,
1200 low: &Expr,
1201 high: &Expr,
1202 negated: bool,
1203 row: &dyn Row,
1204 decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1205) -> Result<Value, EvalError> {
1206 let v = evaluate_with_literal_decoder(target, row, decode_literal)?;
1207 let lo = evaluate_with_literal_decoder(low, row, decode_literal)?;
1208 let hi = evaluate_with_literal_decoder(high, row, decode_literal)?;
1209 if v.is_null() || lo.is_null() || hi.is_null() {
1210 return Ok(Value::Null);
1211 }
1212 let lo_ok = compare_values(&v, &lo)
1213 .ok_or(EvalError::OperatorMismatch {
1214 op: BinOp::Ge,
1215 lhs: v.data_type(),
1216 rhs: lo.data_type(),
1217 })
1218 .map(|o| o != std::cmp::Ordering::Less)?;
1219 let hi_ok = compare_values(&v, &hi)
1220 .ok_or(EvalError::OperatorMismatch {
1221 op: BinOp::Le,
1222 lhs: v.data_type(),
1223 rhs: hi.data_type(),
1224 })
1225 .map(|o| o != std::cmp::Ordering::Greater)?;
1226 let inside = lo_ok && hi_ok;
1227 Ok(Value::Boolean(if negated { !inside } else { inside }))
1228}
1229
1230#[cfg(test)]
1231mod tests {
1232 use super::*;
1233 use reddb_rql::ast::Span;
1234
1235 fn lit(v: Value) -> Expr {
1236 Expr::Literal {
1237 value: v,
1238 span: Span::synthetic(),
1239 }
1240 }
1241
1242 fn binop(op: BinOp, l: Expr, r: Expr) -> Expr {
1243 Expr::BinaryOp {
1244 op,
1245 lhs: Box::new(l),
1246 rhs: Box::new(r),
1247 span: Span::synthetic(),
1248 }
1249 }
1250
1251 fn empty_row() -> impl Row {
1252 |_field: &FieldRef| -> Option<Value> { None }
1253 }
1254
1255 #[test]
1256 fn contains_descends_into_json_object_values() {
1257 let detections = br#"[{"label":"person","confidence":0.9,"bbox":[0,0,1,1]},
1261 {"label":"car","confidence":0.7,"bbox":[1,1,2,2]}]"#;
1262 let json = Value::Json(detections.to_vec());
1263 assert!(value_contains(&json, "person"));
1264 assert!(value_contains(&json, "car"));
1265 assert!(!value_contains(&json, "bicycle"));
1266 assert!(!value_contains(&json, "label"));
1268 }
1269
1270 #[test]
1271 fn integer_addition_overflow_surfaces_as_eval_error() {
1272 let expr = binop(
1273 BinOp::Add,
1274 lit(Value::Integer(i64::MAX)),
1275 lit(Value::Integer(1)),
1276 );
1277 let err = evaluate(&expr, &empty_row()).unwrap_err();
1278 assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Add });
1279 }
1280
1281 #[test]
1282 fn integer_multiplication_overflow_surfaces_as_eval_error() {
1283 let expr = binop(
1284 BinOp::Mul,
1285 lit(Value::Integer(i64::MAX)),
1286 lit(Value::Integer(2)),
1287 );
1288 let err = evaluate(&expr, &empty_row()).unwrap_err();
1289 assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Mul });
1290 }
1291
1292 #[test]
1293 fn integer_subtraction_overflow_surfaces_as_eval_error() {
1294 let expr = binop(
1295 BinOp::Sub,
1296 lit(Value::Integer(i64::MIN)),
1297 lit(Value::Integer(1)),
1298 );
1299 let err = evaluate(&expr, &empty_row()).unwrap_err();
1300 assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1301 }
1302
1303 #[test]
1304 fn unary_neg_overflow_on_min_int_surfaces_as_eval_error() {
1305 let expr = Expr::UnaryOp {
1306 op: UnaryOp::Neg,
1307 operand: Box::new(lit(Value::Integer(i64::MIN))),
1308 span: Span::synthetic(),
1309 };
1310 let err = evaluate(&expr, &empty_row()).unwrap_err();
1311 assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1312 }
1313
1314 #[test]
1315 fn null_propagates_through_arithmetic() {
1316 let expr = binop(BinOp::Add, lit(Value::Null), lit(Value::Integer(7)));
1317 let v = evaluate(&expr, &empty_row()).unwrap();
1318 assert_eq!(v, Value::Null);
1319 }
1320
1321 #[test]
1322 fn null_propagates_through_comparison() {
1323 let expr = binop(BinOp::Lt, lit(Value::Integer(1)), lit(Value::Null));
1324 let v = evaluate(&expr, &empty_row()).unwrap();
1325 assert_eq!(v, Value::Null);
1326 }
1327
1328 #[test]
1329 fn null_propagates_through_concat() {
1330 let expr = binop(
1331 BinOp::Concat,
1332 lit(Value::Text(Arc::from("hi"))),
1333 lit(Value::Null),
1334 );
1335 let v = evaluate(&expr, &empty_row()).unwrap();
1336 assert_eq!(v, Value::Null);
1337 }
1338
1339 #[test]
1340 fn three_valued_and_returns_false_when_one_side_false_even_with_null() {
1341 let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(false)));
1342 let v = evaluate(&expr, &empty_row()).unwrap();
1343 assert_eq!(v, Value::Boolean(false));
1344 }
1345
1346 #[test]
1347 fn three_valued_or_returns_true_when_one_side_true_even_with_null() {
1348 let expr = binop(BinOp::Or, lit(Value::Null), lit(Value::Boolean(true)));
1349 let v = evaluate(&expr, &empty_row()).unwrap();
1350 assert_eq!(v, Value::Boolean(true));
1351 }
1352
1353 #[test]
1354 fn three_valued_and_returns_null_for_null_and_true() {
1355 let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(true)));
1356 let v = evaluate(&expr, &empty_row()).unwrap();
1357 assert_eq!(v, Value::Null);
1358 }
1359
1360 #[test]
1361 fn implicit_cast_triggers_for_decimal_plus_integer() {
1362 let expr = binop(
1371 BinOp::Add,
1372 lit(Value::Decimal(10000)),
1373 lit(Value::Integer(2)),
1374 );
1375 let v = evaluate(&expr, &empty_row()).unwrap();
1376 assert_eq!(v, Value::Decimal(30000));
1377 }
1378
1379 #[test]
1380 fn integer_plus_bigint_resolves_to_preferred_float_overload() {
1381 let expr = binop(
1387 BinOp::Add,
1388 lit(Value::Integer(5)),
1389 lit(Value::BigInt(40_000_000_000)),
1390 );
1391 let v = evaluate(&expr, &empty_row()).unwrap();
1392 assert_eq!(v, Value::Float(40_000_000_005.0));
1393 }
1394
1395 #[test]
1396 fn integer_predicates_preserve_precision_across_signed_and_unsigned_boundaries() {
1397 let mut values = Vec::new();
1398 for number in [
1399 i64::MIN,
1400 -1,
1401 0,
1402 9_007_199_254_740_992,
1403 9_007_199_254_740_993,
1404 i64::MAX,
1405 ] {
1406 values.push((Value::Integer(number), i128::from(number)));
1407 values.push((Value::BigInt(number), i128::from(number)));
1408 }
1409 for number in [
1410 0,
1411 9_007_199_254_740_992,
1412 9_007_199_254_740_993,
1413 i64::MAX as u64,
1414 u64::MAX - 1,
1415 u64::MAX,
1416 ] {
1417 values.push((Value::UnsignedInteger(number), i128::from(number)));
1418 }
1419 for (left, left_exact) in &values {
1420 for (right, right_exact) in &values {
1421 for (operator, expected) in [
1422 (BinOp::Eq, left_exact == right_exact),
1423 (BinOp::Ne, left_exact != right_exact),
1424 (BinOp::Lt, left_exact < right_exact),
1425 (BinOp::Le, left_exact <= right_exact),
1426 (BinOp::Gt, left_exact > right_exact),
1427 (BinOp::Ge, left_exact >= right_exact),
1428 ] {
1429 let expression = binop(operator, lit(left.clone()), lit(right.clone()));
1430 assert_eq!(
1431 evaluate(&expression, &empty_row())
1432 .expect("integer comparison is supported"),
1433 Value::Boolean(expected),
1434 "{left:?} {operator:?} {right:?}"
1435 );
1436 }
1437 for negated in [false, true] {
1438 let expected = (*left_exact == *right_exact) != negated;
1439 let membership = Expr::InList {
1440 target: Box::new(lit(left.clone())),
1441 values: vec![lit(right.clone())],
1442 negated,
1443 span: Span::synthetic(),
1444 };
1445 let interval = Expr::Between {
1446 target: Box::new(lit(left.clone())),
1447 low: Box::new(lit(right.clone())),
1448 high: Box::new(lit(right.clone())),
1449 negated,
1450 span: Span::synthetic(),
1451 };
1452 for expression in [membership, interval] {
1453 assert_eq!(
1454 evaluate(&expression, &empty_row())
1455 .expect("integer predicate is supported"),
1456 Value::Boolean(expected),
1457 "{expression:?}"
1458 );
1459 }
1460 }
1461 }
1462 }
1463 }
1464
1465 #[test]
1466 fn implicit_cast_promotes_integer_to_float_for_float_addition() {
1467 let expr = binop(BinOp::Add, lit(Value::Integer(2)), lit(Value::Float(0.5)));
1471 let v = evaluate(&expr, &empty_row()).unwrap();
1472 assert_eq!(v, Value::Float(2.5));
1473 }
1474
1475 #[test]
1476 fn integer_division_promotes_to_float() {
1477 let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(2)));
1478 let v = evaluate(&expr, &empty_row()).unwrap();
1479 assert_eq!(v, Value::Float(3.5));
1480 }
1481
1482 #[test]
1483 fn division_by_zero_is_eval_error() {
1484 let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(0)));
1485 let err = evaluate(&expr, &empty_row()).unwrap_err();
1486 assert_eq!(err, EvalError::DivisionByZero);
1487 }
1488
1489 #[test]
1490 fn unknown_function_surfaces_as_eval_error() {
1491 let expr = Expr::FunctionCall {
1492 name: "no_such_fn".to_string(),
1493 args: vec![lit(Value::Integer(1))],
1494 span: Span::synthetic(),
1495 };
1496 let err = evaluate(&expr, &empty_row()).unwrap_err();
1497 match err {
1498 EvalError::UnknownFunction { name, args } => {
1499 assert_eq!(name, "no_such_fn");
1500 assert_eq!(args, vec![DataType::Integer]);
1501 }
1502 other => panic!("expected UnknownFunction, got {other:?}"),
1503 }
1504 }
1505
1506 #[test]
1507 fn coalesce_returns_first_non_null() {
1508 let expr = Expr::FunctionCall {
1509 name: "COALESCE".to_string(),
1510 args: vec![
1511 lit(Value::Null),
1512 lit(Value::Null),
1513 lit(Value::Integer(42)),
1514 lit(Value::Integer(99)),
1515 ],
1516 span: Span::synthetic(),
1517 };
1518 let v = evaluate(&expr, &empty_row()).unwrap();
1519 assert_eq!(v, Value::Integer(42));
1520 }
1521
1522 #[test]
1523 fn coalesce_all_null_returns_null() {
1524 let expr = Expr::FunctionCall {
1525 name: "COALESCE".to_string(),
1526 args: vec![lit(Value::Null), lit(Value::Null)],
1527 span: Span::synthetic(),
1528 };
1529 let v = evaluate(&expr, &empty_row()).unwrap();
1530 assert_eq!(v, Value::Null);
1531 }
1532
1533 #[test]
1534 fn variadic_concat_owns_null_semantics() {
1535 let expr = Expr::FunctionCall {
1536 name: "CONCAT".to_string(),
1537 args: vec![
1538 lit(Value::Text(Arc::from("red"))),
1539 lit(Value::Null),
1540 lit(Value::Text(Arc::from("db"))),
1541 ],
1542 span: Span::synthetic(),
1543 };
1544 let value = evaluate(&expr, &empty_row()).unwrap();
1545 assert_eq!(value, Value::Text(Arc::from("reddb")));
1546 }
1547
1548 #[test]
1549 fn upper_lower_dispatch_through_function_catalog() {
1550 let expr = Expr::FunctionCall {
1551 name: "UPPER".to_string(),
1552 args: vec![lit(Value::Text(Arc::from("hello")))],
1553 span: Span::synthetic(),
1554 };
1555 let v = evaluate(&expr, &empty_row()).unwrap();
1556 assert_eq!(v, Value::Text(Arc::from("HELLO")));
1557 }
1558
1559 #[test]
1560 fn length_of_null_propagates() {
1561 let expr = Expr::FunctionCall {
1562 name: "LENGTH".to_string(),
1563 args: vec![lit(Value::Null)],
1564 span: Span::synthetic(),
1565 };
1566 let v = evaluate(&expr, &empty_row()).unwrap();
1567 assert_eq!(v, Value::Null);
1568 }
1569
1570 #[test]
1571 fn case_when_picks_first_true_branch() {
1572 let expr = Expr::Case {
1573 branches: vec![
1574 (lit(Value::Boolean(false)), lit(Value::Integer(1))),
1575 (lit(Value::Boolean(true)), lit(Value::Integer(2))),
1576 (lit(Value::Boolean(true)), lit(Value::Integer(3))),
1577 ],
1578 else_: Some(Box::new(lit(Value::Integer(99)))),
1579 span: Span::synthetic(),
1580 };
1581 let v = evaluate(&expr, &empty_row()).unwrap();
1582 assert_eq!(v, Value::Integer(2));
1583 }
1584
1585 #[test]
1586 fn case_falls_through_to_else_when_no_branch_matches() {
1587 let expr = Expr::Case {
1588 branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1589 else_: Some(Box::new(lit(Value::Integer(99)))),
1590 span: Span::synthetic(),
1591 };
1592 let v = evaluate(&expr, &empty_row()).unwrap();
1593 assert_eq!(v, Value::Integer(99));
1594 }
1595
1596 #[test]
1597 fn case_returns_null_when_no_branch_matches_and_no_else() {
1598 let expr = Expr::Case {
1599 branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1600 else_: None,
1601 span: Span::synthetic(),
1602 };
1603 let v = evaluate(&expr, &empty_row()).unwrap();
1604 assert_eq!(v, Value::Null);
1605 }
1606
1607 #[test]
1608 fn is_null_handles_null_and_non_null() {
1609 let null_expr = Expr::IsNull {
1610 operand: Box::new(lit(Value::Null)),
1611 negated: false,
1612 span: Span::synthetic(),
1613 };
1614 assert_eq!(
1615 evaluate(&null_expr, &empty_row()).unwrap(),
1616 Value::Boolean(true)
1617 );
1618
1619 let non_null_expr = Expr::IsNull {
1620 operand: Box::new(lit(Value::Integer(7))),
1621 negated: false,
1622 span: Span::synthetic(),
1623 };
1624 assert_eq!(
1625 evaluate(&non_null_expr, &empty_row()).unwrap(),
1626 Value::Boolean(false)
1627 );
1628 }
1629
1630 #[test]
1631 fn between_inclusive_bounds() {
1632 let expr = Expr::Between {
1633 target: Box::new(lit(Value::Integer(5))),
1634 low: Box::new(lit(Value::Integer(1))),
1635 high: Box::new(lit(Value::Integer(10))),
1636 negated: false,
1637 span: Span::synthetic(),
1638 };
1639 assert_eq!(evaluate(&expr, &empty_row()).unwrap(), Value::Boolean(true));
1640 }
1641
1642 #[test]
1643 fn in_list_match_and_miss() {
1644 let hit = Expr::InList {
1645 target: Box::new(lit(Value::Integer(2))),
1646 values: vec![
1647 lit(Value::Integer(1)),
1648 lit(Value::Integer(2)),
1649 lit(Value::Integer(3)),
1650 ],
1651 negated: false,
1652 span: Span::synthetic(),
1653 };
1654 assert_eq!(evaluate(&hit, &empty_row()).unwrap(), Value::Boolean(true));
1655
1656 let miss = Expr::InList {
1657 target: Box::new(lit(Value::Integer(99))),
1658 values: vec![lit(Value::Integer(1)), lit(Value::Integer(2))],
1659 negated: false,
1660 span: Span::synthetic(),
1661 };
1662 assert_eq!(
1663 evaluate(&miss, &empty_row()).unwrap(),
1664 Value::Boolean(false)
1665 );
1666 }
1667
1668 #[test]
1669 fn column_lookup_walks_field_ref() {
1670 let row = |field: &FieldRef| -> Option<Value> {
1671 match field {
1672 FieldRef::TableColumn { table, column } if table == "t" && column == "x" => {
1673 Some(Value::Integer(11))
1674 }
1675 _ => None,
1676 }
1677 };
1678 let expr = Expr::Column {
1679 field: FieldRef::TableColumn {
1680 table: "t".to_string(),
1681 column: "x".to_string(),
1682 },
1683 span: Span::synthetic(),
1684 };
1685 assert_eq!(evaluate(&expr, &row).unwrap(), Value::Integer(11));
1686 }
1687
1688 #[test]
1689 fn missing_column_surfaces_unknown_column() {
1690 let row = |_: &FieldRef| -> Option<Value> { None };
1691 let expr = Expr::Column {
1692 field: FieldRef::TableColumn {
1693 table: "t".to_string(),
1694 column: "missing".to_string(),
1695 },
1696 span: Span::synthetic(),
1697 };
1698 let err = evaluate(&expr, &row).unwrap_err();
1699 match err {
1700 EvalError::UnknownColumn(_) => {}
1701 other => panic!("expected UnknownColumn, got {other:?}"),
1702 }
1703 }
1704
1705 #[test]
1706 fn parameter_without_bind_is_eval_error() {
1707 let expr = Expr::Parameter {
1708 index: 1,
1709 span: Span::synthetic(),
1710 };
1711 let err = evaluate(&expr, &empty_row()).unwrap_err();
1712 assert_eq!(err, EvalError::UnboundParameter(1));
1713 }
1714
1715 #[test]
1716 fn cast_integer_to_text_uses_explicit_path() {
1717 let expr = Expr::Cast {
1718 inner: Box::new(lit(Value::Integer(42))),
1719 target: DataType::Text,
1720 span: Span::synthetic(),
1721 };
1722 assert_eq!(
1723 evaluate(&expr, &empty_row()).unwrap(),
1724 Value::Text(Arc::from("42"))
1725 );
1726 }
1727
1728 #[test]
1729 fn concat_returns_text() {
1730 let expr = binop(
1731 BinOp::Concat,
1732 lit(Value::Text(Arc::from("foo"))),
1733 lit(Value::Text(Arc::from("bar"))),
1734 );
1735 assert_eq!(
1736 evaluate(&expr, &empty_row()).unwrap(),
1737 Value::Text(Arc::from("foobar"))
1738 );
1739 }
1740}