Skip to main content

uqa_sql/expr/scalar_postgres/
comparison.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bound comparison syntax uses shared SQL comparison and native array traversal owners.
8
9use super::super::{
10    eval_comparison_truth_with_engine, eval_value_comparison_truth_with_engine,
11    value_to_string_with_control, EvalContext,
12};
13use crate::{
14    ast::{BinaryOp, BooleanTest, FunctionDispatch},
15    error::{Result, SQLError},
16};
17use uqa_core::{
18    memory::{Produced, ProductionControl},
19    Value,
20};
21
22/// Evaluate Boolean nodes synthesized by DISTINCT syntax. Unlike written Boolean contexts, their already-Boolean field comparisons may contain set-returning inputs. Row comparisons retain `PostgreSQL`'s left-to-right short circuit.
23pub fn eval_distinct_boolean(
24    dispatch: FunctionDispatch,
25    count: usize,
26    mut evaluate: impl FnMut(usize) -> Result<Value>,
27) -> Option<Result<Value>> {
28    match dispatch {
29        FunctionDispatch::DistinctNot => Some((|| {
30            if count != 1 {
31                return Err(SQLError::Internal(
32                    "distinct negation takes one comparison".into(),
33                ));
34            }
35            match evaluate(0)? {
36                Value::Bool(value) => Ok(Value::Bool(!value)),
37                _ => Err(SQLError::Internal(
38                    "distinct comparison must be Boolean".into(),
39                )),
40            }
41        })()),
42        FunctionDispatch::RowDistinct => Some((|| {
43            for position in 0..count {
44                match evaluate(position)? {
45                    Value::Bool(true) => return Ok(Value::Bool(true)),
46                    Value::Bool(false) => {}
47                    _ => {
48                        return Err(SQLError::Internal(
49                            "distinct comparison must be Boolean".into(),
50                        ))
51                    }
52                }
53            }
54            Ok(Value::Bool(false))
55        })()),
56        _ => None,
57    }
58}
59
60pub(super) fn evaluate(
61    dispatch: FunctionDispatch,
62    args: &[Value],
63    control: &ProductionControl<'_>,
64) -> Option<Result<Produced<Value>>> {
65    evaluate_with_context(dispatch, args, control, &EvalContext::new(None, &[]))
66}
67
68pub(in crate::expr) fn evaluate_with_context(
69    dispatch: FunctionDispatch,
70    args: &[Value],
71    control: &ProductionControl<'_>,
72    context: &EvalContext<'_>,
73) -> Option<Result<Produced<Value>>> {
74    if let Some(result) =
75        eval_distinct_boolean(dispatch, args.len(), |index| Ok(args[index].clone()))
76    {
77        return Some(
78            result.and_then(|value| Ok(control.finish(value, control.empty_reservation())?)),
79        );
80    }
81    let result = match dispatch {
82        FunctionDispatch::AnyOperator => any_all(args, true, control, context),
83        FunctionDispatch::AllOperator => any_all(args, false, control, context),
84        FunctionDispatch::IsDistinct | FunctionDispatch::ValueIsDistinct => {
85            is_distinct(args, control, context)
86        }
87        FunctionDispatch::ValueNullTest { negated } => {
88            let [value] = args else {
89                return Some(Err(SQLError::Internal(
90                    "outer NULL test takes one input".into(),
91                )));
92            };
93            Ok(Value::Bool(matches!(value, Value::Null) != negated))
94        }
95        FunctionDispatch::BooleanTest(test) => boolean_test(test, args),
96        FunctionDispatch::BetweenSymmetric => between_symmetric(args, control, context),
97        _ => return None,
98    };
99    Some(result.and_then(|value| Ok(control.finish(value, control.empty_reservation())?)))
100}
101
102fn boolean_test(test: BooleanTest, args: &[Value]) -> Result<Value> {
103    let [value] = args else {
104        return Err(SQLError::Internal("Boolean test takes one input".into()));
105    };
106    let input = match value {
107        Value::Bool(value) => Some(*value),
108        Value::Null => None,
109        _ => {
110            return Err(SQLError::Internal(
111                "Boolean test received an untyped input".into(),
112            ))
113        }
114    };
115    Ok(Value::Bool(match test {
116        BooleanTest::IsTrue => input == Some(true),
117        BooleanTest::IsNotTrue => input != Some(true),
118        BooleanTest::IsFalse => input == Some(false),
119        BooleanTest::IsNotFalse => input != Some(false),
120        BooleanTest::IsUnknown => input.is_none(),
121        BooleanTest::IsNotUnknown => input.is_some(),
122    }))
123}
124
125fn any_all(
126    args: &[Value],
127    is_any: bool,
128    control: &ProductionControl<'_>,
129    context: &EvalContext<'_>,
130) -> Result<Value> {
131    control.check()?;
132    if args.len() != 3 {
133        return Err(SQLError::TypeMismatch("ANY/ALL takes 3 args".into()));
134    }
135    let op = match value_to_string_with_control(&args[2], control)?.as_str() {
136        "=" => BinaryOp::Equal,
137        "<>" | "!=" => BinaryOp::NotEqual,
138        "<" => BinaryOp::Less,
139        "<=" => BinaryOp::LessEqual,
140        ">" => BinaryOp::Greater,
141        ">=" => BinaryOp::GreaterEqual,
142        other => {
143            return Err(SQLError::Unsupported(format!(
144                "operator `{other}` with ANY/ALL"
145            )))
146        }
147    };
148    let Some(array) = args[1].array_view() else {
149        if matches!(args[1], Value::Null) {
150            return Ok(Value::Null);
151        }
152        return Err(SQLError::TypeMismatch("ANY/ALL requires an array".into()));
153    };
154    let mut saw_null = false;
155    let mut elements = array.elements_with_control(control)?;
156    while let Some(item) = elements.next_element()? {
157        match compare_value(op, &args[0], item, control, context, 0)? {
158            Some(true) if is_any => return Ok(Value::Bool(true)),
159            Some(false) if !is_any => return Ok(Value::Bool(false)),
160            None => saw_null = true,
161            _ => {}
162        }
163    }
164    Ok(if saw_null {
165        Value::Null
166    } else {
167        Value::Bool(!is_any)
168    })
169}
170
171fn is_distinct(
172    args: &[Value],
173    control: &ProductionControl<'_>,
174    context: &EvalContext<'_>,
175) -> Result<Value> {
176    control.check()?;
177    let [left, right] = args else {
178        return Err(SQLError::TypeMismatch(
179            "IS DISTINCT FROM takes 2 args".into(),
180        ));
181    };
182    let distinct = match (left, right) {
183        (Value::Null, Value::Null) => false,
184        (Value::Null, _) | (_, Value::Null) => true,
185        (left, right) => {
186            compare_value(BinaryOp::Equal, left, right, control, context, 0)? != Some(true)
187        }
188    };
189    Ok(Value::Bool(distinct))
190}
191
192fn between_symmetric(
193    args: &[Value],
194    control: &ProductionControl<'_>,
195    context: &EvalContext<'_>,
196) -> Result<Value> {
197    control.check()?;
198    let [value, low, high] = args else {
199        return Err(SQLError::TypeMismatch(
200            "BETWEEN SYMMETRIC takes 3 args".into(),
201        ));
202    };
203    let forward = between(value, low, high, control, context, 0)?;
204    if forward == Value::Bool(true) {
205        return Ok(forward);
206    }
207    let backward = between(value, high, low, control, context, 2)?;
208    Ok(match (forward, backward) {
209        (Value::Bool(true), _) | (_, Value::Bool(true)) => Value::Bool(true),
210        (Value::Null, _) | (_, Value::Null) => Value::Null,
211        _ => Value::Bool(false),
212    })
213}
214
215fn between(
216    value: &Value,
217    low: &Value,
218    high: &Value,
219    control: &ProductionControl<'_>,
220    context: &EvalContext<'_>,
221    slot: usize,
222) -> Result<Value> {
223    let ge = compare(BinaryOp::GreaterEqual, value, low, control, context, slot)?;
224    if ge == Some(false) {
225        return Ok(Value::Bool(false));
226    }
227    let le = compare(BinaryOp::LessEqual, value, high, control, context, slot + 1)?;
228    Ok(match (ge, le) {
229        (_, Some(false)) => Value::Bool(false),
230        (Some(true), Some(true)) => Value::Bool(true),
231        _ => Value::Null,
232    })
233}
234
235fn compare(
236    op: BinaryOp,
237    left: &Value,
238    right: &Value,
239    control: &ProductionControl<'_>,
240    context: &EvalContext<'_>,
241    slot: usize,
242) -> Result<Option<bool>> {
243    eval_comparison_truth_with_engine(
244        op,
245        left,
246        right,
247        control,
248        context.engine,
249        context.enum_comparison_state_at(slot),
250    )
251}
252
253fn compare_value(
254    op: BinaryOp,
255    left: &Value,
256    right: &Value,
257    control: &ProductionControl<'_>,
258    context: &EvalContext<'_>,
259    slot: usize,
260) -> Result<Option<bool>> {
261    eval_value_comparison_truth_with_engine(
262        op,
263        left,
264        right,
265        control,
266        context.engine,
267        context.enum_comparison_state_at(slot),
268    )
269}
270
271#[cfg(test)]
272mod tests;