Skip to main content

uqa_sql/expr/
binary.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL comparison, three-valued logic, and numeric arithmetic.
8
9use super::{eval, time, BinaryOp, EvalContext, Expr, Result, SQLError, SQLParam, Value};
10
11use uqa_core::memory::{Produced, ProductionControl};
12
13mod btree;
14mod comparison;
15pub use btree::{
16    compare_btree_inputs_with_catalog_and_control, compare_btree_inputs_with_invocation_state,
17    with_btree_input, BTreeInput,
18};
19mod selected;
20pub use selected::{
21    compare_selected_grouping_values_with_catalog, compare_selected_values_with_catalog,
22    equal_selected_values_with_catalog,
23};
24#[cfg(test)]
25mod production_tests;
26
27#[cfg(test)]
28pub(super) use comparison::eval_comparison_op;
29pub use comparison::{
30    compare_grouping_values_with_enum_catalog, compare_nullable_with_control,
31    compare_record_images_with_catalog, compare_typed_values_with_catalog_and_collation,
32    compare_typed_values_with_control, compare_typed_values_with_enum_catalog,
33    compare_with_control, equal_typed_values_with_catalog_and_collation,
34    equal_typed_values_with_enum_catalog, eval_comparison_truth,
35    eval_comparison_truth_with_control, eval_comparison_truth_with_deferred_state,
36    eval_comparison_truth_with_engine, eval_comparison_truth_with_enum_catalog,
37    eval_record_comparison_truth_with_engine, eval_value_comparison_truth_with_engine,
38    type_comparison_can_fail, validate_legacy_vector_comparison, value_comparison_can_fail,
39    values_equal_nullable_with_control, values_equal_with_control,
40    visit_record_image_fields_with_catalog,
41};
42pub(in crate::expr) use comparison::{require_array_element_support, ComparisonSupport};
43
44pub(super) fn eval_binary(
45    op: BinaryOp,
46    lhs: &Expr,
47    rhs: &Expr,
48    ctx: &EvalContext<'_>,
49) -> Result<Value> {
50    if let Some(value) = eval_binary_borrowed(op, lhs, rhs, ctx)? {
51        return Ok(value);
52    }
53    let l = eval(lhs, ctx)?;
54    let r = eval(rhs, ctx)?;
55    if matches!(
56        op,
57        BinaryOp::Equal
58            | BinaryOp::NotEqual
59            | BinaryOp::Less
60            | BinaryOp::LessEqual
61            | BinaryOp::Greater
62            | BinaryOp::GreaterEqual
63    ) {
64        if matches!((&l, &r), (Value::Row(_), Value::Row(_)))
65            && !matches!((lhs, rhs), (Expr::Row(_), Expr::Row(_)))
66        {
67            return eval_record_comparison_truth_with_engine(
68                op,
69                &l,
70                &r,
71                &ProductionControl::uncontrolled(),
72                ctx.engine,
73            )
74            .map(|value| value.map_or(Value::Null, Value::Bool));
75        }
76        return eval_comparison_truth_with_engine(
77            op,
78            &l,
79            &r,
80            &ProductionControl::uncontrolled(),
81            ctx.engine,
82            None,
83        )
84        .map(|value| value.map_or(Value::Null, Value::Bool));
85    }
86    if let Some(value) = super::enums::eval_comparison(
87        op,
88        &l,
89        &r,
90        ctx.engine.and_then(super::EngineHook::enum_labels),
91        None,
92    )? {
93        return Ok(value);
94    }
95    if is_arithmetic(op) && real_expr(lhs, ctx.params) && real_expr(rhs, ctx.params) {
96        return super::eval_float_arithmetic(op, &l, &r, super::FloatWidth::Real);
97    }
98    eval_binary_values_with_engine(
99        op,
100        &l,
101        &r,
102        integer_binary_width(lhs, rhs),
103        ctx.engine,
104        &ProductionControl::uncontrolled(),
105    )
106    .map(|value| value.into_uncontrolled().expect("ordinary binary result"))
107}
108
109pub(super) fn is_arithmetic(op: BinaryOp) -> bool {
110    matches!(
111        op,
112        BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide
113    )
114}
115
116fn real_expr(expression: &Expr, params: &[SQLParam]) -> bool {
117    match expression {
118        Expr::Cast { ty, .. } | Expr::TypedLiteral { ty, .. } => {
119            matches!(
120                crate::ast::ColumnType::from_sql_name(ty),
121                Ok(crate::ast::ColumnType::Real)
122            )
123        }
124        Expr::Param(index) => index
125            .checked_sub(1)
126            .and_then(|index| params.get(index))
127            .and_then(SQLParam::declared_scalar_type)
128            .is_some_and(|ty| matches!(ty, crate::ast::ColumnType::Real)),
129        Expr::UnaryMinus(inner) => real_expr(inner, params),
130        Expr::Binary { op, lhs, rhs } if is_arithmetic(*op) => {
131            real_expr(lhs, params) && real_expr(rhs, params)
132        }
133        _ => false,
134    }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
138pub enum IntegerWidth {
139    SmallInt,
140    Integer,
141    BigInt,
142}
143
144#[must_use]
145pub fn integer_width_for_literal(value: i64) -> IntegerWidth {
146    if i32::try_from(value).is_ok() {
147        IntegerWidth::Integer
148    } else {
149        IntegerWidth::BigInt
150    }
151}
152
153#[must_use]
154pub fn integer_width_for_type(ty: &str) -> Option<IntegerWidth> {
155    let ty = ty.trim();
156    [
157        (
158            IntegerWidth::SmallInt,
159            &["smallint", "int2", "pg_catalog.int2"][..],
160        ),
161        (
162            IntegerWidth::Integer,
163            &[
164                "integer",
165                "int",
166                "int4",
167                "serial",
168                "serial4",
169                "pg_catalog.int4",
170            ][..],
171        ),
172        (
173            IntegerWidth::BigInt,
174            &["bigint", "int8", "bigserial", "serial8", "pg_catalog.int8"][..],
175        ),
176    ]
177    .into_iter()
178    .find_map(|(width, names)| {
179        names
180            .iter()
181            .any(|name| ty.eq_ignore_ascii_case(name))
182            .then_some(width)
183    })
184}
185
186fn integer_expr_width(expr: &Expr) -> Option<IntegerWidth> {
187    match expr {
188        Expr::Literal(Value::Int(value)) => Some(integer_width_for_literal(*value)),
189        Expr::Cast { ty, .. } | Expr::TypedLiteral { ty, .. } => integer_width_for_type(ty),
190        Expr::Binary {
191            op: BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide,
192            lhs,
193            rhs,
194        } => Some(integer_expr_width(lhs)?.max(integer_expr_width(rhs)?)),
195        _ => None,
196    }
197}
198
199fn integer_binary_width(lhs: &Expr, rhs: &Expr) -> Option<IntegerWidth> {
200    Some(integer_expr_width(lhs)?.max(integer_expr_width(rhs)?))
201}
202
203/// Apply a binary SQL operator to values that have already been evaluated.
204/// Execution engines use this when a hot path compiles expression traversal
205/// ahead of time but must retain the evaluator's exact comparison, numeric
206/// promotion, NULL, overflow, and division-by-zero semantics.
207pub fn eval_binary_values(op: BinaryOp, l: &Value, r: &Value) -> Result<Value> {
208    eval_binary_values_with_control(op, l, r, &ProductionControl::uncontrolled()).map(|value| {
209        value
210            .into_uncontrolled()
211            .expect("ordinary binary result has no reservation")
212    })
213}
214
215/// Evaluate the existing binary operator while owning every value producer and comparison workspace under one allowance.
216pub fn eval_binary_values_with_control(
217    op: BinaryOp,
218    l: &Value,
219    r: &Value,
220    control: &ProductionControl<'_>,
221) -> Result<Produced<Value>> {
222    binary_values(op, l, r, None, control)
223}
224
225fn binary_values(
226    op: BinaryOp,
227    l: &Value,
228    r: &Value,
229    engine: Option<&dyn super::EngineHook>,
230    control: &ProductionControl<'_>,
231) -> Result<Produced<Value>> {
232    control.check()?;
233    if matches!(l, Value::Null) || matches!(r, Value::Null) {
234        return Ok(control.finish(Value::Null, control.empty_reservation())?);
235    }
236    if let (true, Value::Datum(datum)) = (is_arithmetic(op), l) {
237        return binary_values(
238            op,
239            &*super::datums::read_with_control(datum, control)?,
240            r,
241            engine,
242            control,
243        );
244    }
245    if let (true, Value::Datum(datum)) = (is_arithmetic(op), r) {
246        return binary_values(
247            op,
248            l,
249            &*super::datums::read_with_control(datum, control)?,
250            engine,
251            control,
252        );
253    }
254    match op {
255        BinaryOp::Equal
256        | BinaryOp::NotEqual
257        | BinaryOp::Less
258        | BinaryOp::LessEqual
259        | BinaryOp::Greater
260        | BinaryOp::GreaterEqual => {
261            let value = eval_comparison_truth_with_control(op, l, r, control)?
262                .map(Value::Bool)
263                .unwrap_or(Value::Null);
264            control
265                .finish(value, control.empty_reservation())
266                .map_err(Into::into)
267        }
268        BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide => {
269            arith(l, r, op, engine, control)
270        }
271    }
272}
273
274/// Evaluate an operator while retaining the integer type selected by SQL
275/// operator resolution. The dynamic [`Value`] carrier stores all integers as
276/// `i64`, so expression plans pass this width alongside the operands.
277pub fn eval_binary_values_with_integer_width(
278    op: BinaryOp,
279    l: &Value,
280    r: &Value,
281    integer_width: Option<IntegerWidth>,
282) -> Result<Value> {
283    eval_binary_values_with_integer_width_with_control(
284        op,
285        l,
286        r,
287        integer_width,
288        &ProductionControl::uncontrolled(),
289    )
290    .map(|value| {
291        value
292            .into_uncontrolled()
293            .expect("ordinary width-checked result has no reservation")
294    })
295}
296
297/// Preserve the selected integer width without separating an allocated result from its owner on errors.
298pub fn eval_binary_values_with_integer_width_with_control(
299    op: BinaryOp,
300    l: &Value,
301    r: &Value,
302    integer_width: Option<IntegerWidth>,
303    control: &ProductionControl<'_>,
304) -> Result<Produced<Value>> {
305    eval_binary_values_with_engine(op, l, r, integer_width, None, control)
306}
307
308/// Evaluate already produced operands with their selected integer width and live session inputs.
309pub fn eval_binary_values_with_engine(
310    op: BinaryOp,
311    l: &Value,
312    r: &Value,
313    integer_width: Option<IntegerWidth>,
314    engine: Option<&dyn super::EngineHook>,
315    control: &ProductionControl<'_>,
316) -> Result<Produced<Value>> {
317    let result = binary_values(op, l, r, engine, control)?;
318    let Some(integer_width) = integer_width else {
319        return Ok(result);
320    };
321    let Value::Int(value) = *result else {
322        return Ok(result);
323    };
324    let in_range = match integer_width {
325        IntegerWidth::SmallInt => i16::try_from(value).is_ok(),
326        IntegerWidth::Integer => i32::try_from(value).is_ok(),
327        IntegerWidth::BigInt => true,
328    };
329    if in_range {
330        Ok(result)
331    } else {
332        Err(out_of_range(match integer_width {
333            IntegerWidth::SmallInt => "smallint",
334            IntegerWidth::Integer => "integer",
335            IntegerWidth::BigInt => "bigint",
336        }))
337    }
338}
339
340pub(super) enum EvalOperand<'a> {
341    Borrowed(&'a Value),
342    Owned(Value),
343}
344
345impl EvalOperand<'_> {
346    fn as_value(&self) -> &Value {
347        match self {
348            Self::Borrowed(value) => value,
349            Self::Owned(value) => value,
350        }
351    }
352}
353
354pub(super) fn eval_binary_borrowed(
355    op: BinaryOp,
356    lhs: &Expr,
357    rhs: &Expr,
358    ctx: &EvalContext<'_>,
359) -> Result<Option<Value>> {
360    if !matches!(
361        op,
362        BinaryOp::Equal
363            | BinaryOp::NotEqual
364            | BinaryOp::Less
365            | BinaryOp::LessEqual
366            | BinaryOp::Greater
367            | BinaryOp::GreaterEqual
368    ) {
369        return Ok(None);
370    }
371    let Some(l) = eval_operand_borrowed(lhs, ctx)? else {
372        return Ok(None);
373    };
374    let Some(r) = eval_operand_borrowed(rhs, ctx)? else {
375        return Ok(None);
376    };
377    let l = l.as_value();
378    let r = r.as_value();
379    if matches!((l, r), (Value::Row(_), Value::Row(_))) {
380        return eval_record_comparison_truth_with_engine(
381            op,
382            l,
383            r,
384            &ProductionControl::uncontrolled(),
385            ctx.engine,
386        )
387        .map(|value| Some(value.map_or(Value::Null, Value::Bool)));
388    }
389    eval_comparison_truth_with_engine(
390        op,
391        l,
392        r,
393        &ProductionControl::uncontrolled(),
394        ctx.engine,
395        None,
396    )
397    .map(|value| Some(value.map_or(Value::Null, Value::Bool)))
398}
399
400pub(super) fn eval_operand_borrowed<'a>(
401    expr: &Expr,
402    ctx: &EvalContext<'a>,
403) -> Result<Option<EvalOperand<'a>>> {
404    match expr {
405        Expr::Literal(value) => Ok(Some(EvalOperand::Owned(value.clone()))),
406        Expr::Param(i) => match i.checked_sub(1).and_then(|index| ctx.params.get(index)) {
407            Some(SQLParam::Scalar(value) | SQLParam::TypedScalar { value, .. }) => {
408                Ok(Some(EvalOperand::Borrowed(value)))
409            }
410            Some(SQLParam::Vector(_) | SQLParam::Tensor(_) | SQLParam::DeferredError { .. }) => {
411                Ok(None)
412            }
413            None => Err(SQLError::MissingParam(*i)),
414        },
415        Expr::Column(name) => {
416            if ctx.row_lookup()?.column_is_ambiguous(name) {
417                return Err(SQLError::AmbiguousColumn(name.clone()));
418            }
419            Ok(Some(match ctx.row_lookup()?.column(name) {
420                Some(value) => EvalOperand::Borrowed(value),
421                None => EvalOperand::Owned(Value::Null),
422            }))
423        }
424        Expr::QualifiedColumn { qualifier, column } => {
425            if ctx
426                .row_lookup()?
427                .qualified_column_is_ambiguous(qualifier, column)
428            {
429                return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
430            }
431            Ok(Some(
432                match ctx.row_lookup()?.qualified_column(qualifier, column) {
433                    Some(value) => EvalOperand::Borrowed(value),
434                    None => EvalOperand::Owned(Value::Null),
435                },
436            ))
437        }
438        _ => Ok(None),
439    }
440}
441
442/// Whether a condition holds. `NULL` does not; text, which reaches a condition only as an `unknown` literal or parameter, holds when `boolin` reads it as true (parse analysis rejects any other text); the engine's numeric retrieval predicates hold when non-zero.
443pub fn truthy(v: &Value) -> bool {
444    match v {
445        Value::Null => false,
446        Value::Bool(b) => *b,
447        Value::Int(n) => *n != 0,
448        Value::Float(f) => *f != 0.0,
449        Value::Decimal(d) => !d.is_zero(),
450        Value::Str(s) | Value::FixedChar(s) => super::parse_boolean_input(s) == Some(true),
451        _ => true,
452    }
453}
454
455/// `PostgreSQL` `division by zero` error (SQLSTATE 22012).
456pub(crate) fn division_by_zero() -> SQLError {
457    SQLError::Routine {
458        sqlstate: "22012".into(),
459        message: "division by zero".into(),
460    }
461}
462
463/// `PostgreSQL`'s error for a date, time, timestamp or interval beyond its type's range (SQLSTATE 22008).
464pub(crate) fn datetime_out_of_range(type_name: &str) -> SQLError {
465    SQLError::Routine {
466        sqlstate: "22008".into(),
467        message: format!("{type_name} out of range"),
468    }
469}
470
471/// `PostgreSQL` numeric overflow error (SQLSTATE 22003).
472pub(crate) fn out_of_range(type_name: &str) -> SQLError {
473    SQLError::Routine {
474        sqlstate: "22003".into(),
475        message: format!("{type_name} out of range"),
476    }
477}
478
479fn arith(
480    a: &Value,
481    b: &Value,
482    op: BinaryOp,
483    engine: Option<&dyn super::EngineHook>,
484    control: &ProductionControl<'_>,
485) -> Result<Produced<Value>> {
486    control.check()?;
487    // SQL three-valued logic: NULL `op` anything == NULL.
488    if matches!(a, Value::Null) || matches!(b, Value::Null) {
489        return control
490            .finish(Value::Null, control.empty_reservation())
491            .map_err(Into::into);
492    }
493    // Integer x integer is the overwhelmingly common analytical path.
494    // Resolve it before probing unrelated temporal / decimal / floating
495    // representations, while retaining PostgreSQL overflow behavior. The
496    // caller applies the SQL operator's int2/int4/int8 result width after this
497    // carrier-level i64 operation.
498    if let (Value::Int(li), Value::Int(ri)) = (a, b) {
499        let out = match op {
500            BinaryOp::Add => li.checked_add(*ri),
501            BinaryOp::Subtract => li.checked_sub(*ri),
502            BinaryOp::Multiply => li.checked_mul(*ri),
503            BinaryOp::Divide => {
504                if *ri == 0 {
505                    return Err(division_by_zero());
506                }
507                // Integer / integer in SQL truncates toward zero.
508                li.checked_div(*ri)
509            }
510            _ => {
511                return Err(SQLError::Internal(format!(
512                    "non-arithmetic operator {op:?} reached integer arithmetic"
513                )))
514            }
515        };
516        let value = out.map(Value::Int).ok_or_else(|| out_of_range("bigint"))?;
517        return control
518            .finish(value, control.empty_reservation())
519            .map_err(Into::into);
520    }
521    if matches!(op, BinaryOp::Subtract)
522        && matches!(a, Value::JsonB(_) | Value::Map(_) | Value::List(_))
523    {
524        if let Some(value) = super::json::json_delete_values_with_control(a, b, control)? {
525            return Ok(value);
526        }
527    }
528    if matches!(a, Value::Temporal(_)) || matches!(b, Value::Temporal(_)) {
529        let value = time::temporal_arith_with_control(a, b, op, engine, control)?;
530        return control
531            .finish(value, control.empty_reservation())
532            .map_err(Into::into);
533    }
534    let has_decimal = matches!(a, Value::Decimal(_)) || matches!(b, Value::Decimal(_));
535    let has_float = matches!(a, Value::Float(_)) || matches!(b, Value::Float(_));
536    // PostgreSQL numeric promotion: double precision wins mixed
537    // float/numeric arithmetic. Exact decimal arithmetic only applies
538    // when no float operand is involved.
539    if has_decimal && !has_float {
540        return decimal_arith(a, b, op, control);
541    }
542    let value = super::eval_float_arithmetic_with_control(
543        op,
544        a,
545        b,
546        super::FloatWidth::DoublePrecision,
547        control,
548    )?;
549    control
550        .finish(value, control.empty_reservation())
551        .map_err(Into::into)
552}
553
554fn decimal_arith(
555    a: &Value,
556    b: &Value,
557    op: BinaryOp,
558    control: &ProductionControl<'_>,
559) -> Result<Produced<Value>> {
560    let left = super::conversion::to_decimal_with_control(a, control)?;
561    let right = super::conversion::to_decimal_with_control(b, control)?;
562    let value = match op {
563        BinaryOp::Add => left.checked_add_with_control(&right, control)?,
564        BinaryOp::Subtract => left.checked_sub_with_control(&right, control)?,
565        BinaryOp::Multiply => left.checked_mul_with_control(&right, control)?,
566        BinaryOp::Divide => {
567            if right.is_zero() {
568                return Err(division_by_zero());
569            }
570            left.checked_div_postgres_with_control(&right, control)?
571        }
572        _ => {
573            return Err(SQLError::Internal(format!(
574                "non-arithmetic operator {op:?} reached decimal arithmetic"
575            )))
576        }
577    }
578    .ok_or_else(|| out_of_range("numeric"))?;
579    let (value, memory) = value.into_parts();
580    control
581        .finish(Value::Decimal(value), memory)
582        .map_err(Into::into)
583}