Skip to main content

uqa_sql/expr/binary/
comparison.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL NULL and row comparison rules share the native controlled value owners.
8
9use super::super::enums::{EnumComparisonState, EnumLabelCatalog};
10use super::{BinaryOp, Result, SQLError, Value};
11use std::cmp::Ordering;
12use uqa_core::memory::ProductionControl;
13
14mod collations;
15pub use collations::{
16    compare_typed_values_with_catalog_and_collation, equal_typed_values_with_catalog_and_collation,
17};
18mod image;
19mod records;
20mod support;
21mod temporal;
22pub use image::{compare_record_images_with_catalog, visit_record_image_fields_with_catalog};
23pub(in crate::expr) use support::{require_array_element_support, ComparisonSupport};
24
25#[cfg(test)]
26pub(in crate::expr) fn eval_comparison_op(op: BinaryOp, l: &Value, r: &Value) -> Result<Value> {
27    Ok(eval_comparison_truth(op, l, r)?
28        .map(Value::Bool)
29        .unwrap_or(Value::Null))
30}
31
32/// Compare two values without allocating an intermediate [`Value::Bool`]. `None` represents SQL UNKNOWN, including an undecided anonymous row comparison.
33#[inline]
34pub fn eval_comparison_truth(op: BinaryOp, l: &Value, r: &Value) -> Result<Option<bool>> {
35    eval_comparison_truth_with_control(op, l, r, &ProductionControl::uncontrolled())
36}
37
38/// Evaluate the same three-valued comparison while admitting the native numeric, JSONB and array comparison workspace to the caller's allowance.
39pub fn eval_comparison_truth_with_control(
40    op: BinaryOp,
41    l: &Value,
42    r: &Value,
43    control: &ProductionControl<'_>,
44) -> Result<Option<bool>> {
45    control.check()?;
46    let out = match op {
47        BinaryOp::Equal => values_equal_nullable_with_control(l, r, control)?,
48        BinaryOp::NotEqual => values_equal_nullable_with_control(l, r, control)?.map(|v| !v),
49        BinaryOp::Less => compare_nullable_with_control(l, r, control)?.map(|v| v.is_lt()),
50        BinaryOp::LessEqual => compare_nullable_with_control(l, r, control)?.map(|v| v.is_le()),
51        BinaryOp::Greater => compare_nullable_with_control(l, r, control)?.map(|v| v.is_gt()),
52        BinaryOp::GreaterEqual => compare_nullable_with_control(l, r, control)?.map(|v| v.is_ge()),
53        _ => {
54            return Err(SQLError::Internal(format!(
55                "non-comparison operator {op:?} reached comparison evaluation"
56            )))
57        }
58    };
59    Ok(out)
60}
61
62/// Borrow physical type metadata from scalar hooks even when the embedder provides no enum capability.
63pub fn eval_comparison_truth_with_engine(
64    op: BinaryOp,
65    left: &Value,
66    right: &Value,
67    control: &ProductionControl<'_>,
68    engine: Option<&dyn crate::expr::EngineHook>,
69    state: Option<&EnumComparisonState>,
70) -> Result<Option<bool>> {
71    eval_comparison_truth_with_deferred_state(op, left, right, control, engine, || state)
72}
73
74/// Compare complete SQL values selected by a consumer such as CASE, NULLIF or ANY. Anonymous record carriers retain record operators; three-valued ROW constructor comparison is selected separately by expression syntax.
75pub fn eval_value_comparison_truth_with_engine(
76    op: BinaryOp,
77    left: &Value,
78    right: &Value,
79    control: &ProductionControl<'_>,
80    engine: Option<&dyn crate::expr::EngineHook>,
81    state: Option<&EnumComparisonState>,
82) -> Result<Option<bool>> {
83    if matches!((left, right), (Value::Row(_), Value::Row(_))) {
84        eval_record_comparison_truth_with_engine(op, left, right, control, engine)
85    } else {
86        eval_comparison_truth_with_engine(op, left, right, control, engine, state)
87    }
88}
89
90/// Compare record operands selected by SQL syntax. A record-valued column, cast or parameter retains record field operators even when its carrier is an anonymous `Row`; only two uncast ROW constructors select three-valued row comparison.
91pub fn eval_record_comparison_truth_with_engine(
92    op: BinaryOp,
93    left: &Value,
94    right: &Value,
95    control: &ProductionControl<'_>,
96    engine: Option<&dyn crate::expr::EngineHook>,
97) -> Result<Option<bool>> {
98    control.check()?;
99    if matches!(left, Value::Null) || matches!(right, Value::Null) {
100        return Ok(None);
101    }
102    let catalog = engine.map(crate::expr::EngineValueCatalog);
103    let catalog = catalog
104        .as_ref()
105        .map(|catalog| catalog as &dyn crate::expr::SQLValueCatalog);
106    if matches!(op, BinaryOp::Equal | BinaryOp::NotEqual) {
107        let equal = equal_typed_values_with_enum_catalog(left, right, control, catalog)?;
108        return Ok(Some(if op == BinaryOp::Equal { equal } else { !equal }));
109    }
110    let order = compare_typed_values_with_enum_catalog(left, right, control, catalog, None)?;
111    Ok(Some(match op {
112        BinaryOp::Less => order.is_lt(),
113        BinaryOp::LessEqual => order.is_le(),
114        BinaryOp::Greater => order.is_gt(),
115        BinaryOp::GreaterEqual => order.is_ge(),
116        _ => {
117            return Err(SQLError::Internal(format!(
118                "non-comparison operator {op:?} reached record comparison"
119            )))
120        }
121    }))
122}
123
124/// Primitive scalar comparisons need no catalog or private enum call state. Resolve that state only when the evaluated carriers require the general comparison path; operand evaluation and its SQL ordering remain the caller's responsibility.
125#[inline]
126pub fn eval_comparison_truth_with_deferred_state<'a>(
127    op: BinaryOp,
128    left: &Value,
129    right: &Value,
130    control: &ProductionControl<'_>,
131    engine: Option<&dyn crate::expr::EngineHook>,
132    state: impl FnOnce() -> Option<&'a EnumComparisonState>,
133) -> Result<Option<bool>> {
134    control.check()?;
135    let primitive = match (left, right) {
136        (Value::Null, _) | (_, Value::Null) => Some(None),
137        (Value::Int(_), Value::Int(_))
138        | (Value::Float(_), Value::Float(_))
139        | (Value::Bool(_), Value::Bool(_)) => Some(Some(left.cmp(right))),
140        _ => None,
141    };
142    if let Some(order) = primitive {
143        return match op {
144            BinaryOp::Equal => Ok(order.map(Ordering::is_eq)),
145            BinaryOp::NotEqual => Ok(order.map(|order| !order.is_eq())),
146            BinaryOp::Less => Ok(order.map(Ordering::is_lt)),
147            BinaryOp::LessEqual => Ok(order.map(Ordering::is_le)),
148            BinaryOp::Greater => Ok(order.map(Ordering::is_gt)),
149            BinaryOp::GreaterEqual => Ok(order.map(Ordering::is_ge)),
150            _ => Err(SQLError::Internal(format!(
151                "non-comparison operator {op:?} reached comparison evaluation"
152            ))),
153        };
154    }
155    let catalog = engine.map(crate::expr::value_catalog::EngineValueCatalog);
156    eval_comparison_truth_with_context(
157        op,
158        left,
159        right,
160        control,
161        engine,
162        catalog
163            .as_ref()
164            .map(|catalog| catalog as &dyn crate::expr::SQLValueCatalog),
165        state(),
166    )
167}
168
169/// Observe scalar and nested enums through the caller's catalog, preserving private scalar/row call state, shared type support state and ordinary three-valued rules.
170pub fn eval_comparison_truth_with_enum_catalog(
171    op: BinaryOp,
172    left: &Value,
173    right: &Value,
174    control: &ProductionControl<'_>,
175    enums: Option<&dyn super::super::enums::EnumLabelCatalog>,
176    state: Option<&super::super::enums::EnumComparisonState>,
177) -> Result<Option<bool>> {
178    eval_comparison_truth_with_context(op, left, right, control, None, enums, state)
179}
180
181fn eval_comparison_truth_with_context(
182    op: BinaryOp,
183    left: &Value,
184    right: &Value,
185    control: &ProductionControl<'_>,
186    engine: Option<&dyn crate::expr::EngineHook>,
187    enums: Option<&dyn EnumLabelCatalog>,
188    state: Option<&EnumComparisonState>,
189) -> Result<Option<bool>> {
190    control.check()?;
191    if matches!(op, BinaryOp::Equal | BinaryOp::NotEqual) {
192        return values_equal_nullable_with_catalog(left, right, control, enums, engine)
193            .map(|equal| equal.map(|equal| if op == BinaryOp::Equal { equal } else { !equal }));
194    }
195    if !matches!(
196        op,
197        BinaryOp::Less | BinaryOp::LessEqual | BinaryOp::Greater | BinaryOp::GreaterEqual
198    ) {
199        return Err(SQLError::Internal(format!(
200            "non-comparison operator {op:?} reached comparison evaluation"
201        )));
202    }
203    let order = compare_nullable_with_catalog(left, right, control, enums, state, engine)?;
204    Ok(order.map(|order| match op {
205        BinaryOp::Less => order.is_lt(),
206        BinaryOp::LessEqual => order.is_le(),
207        BinaryOp::Greater => order.is_gt(),
208        BinaryOp::GreaterEqual => order.is_ge(),
209        _ => unreachable!("only comparison operators reach comparison evaluation"),
210    }))
211}
212
213/// Two-valued equality treats SQL UNKNOWN as no match for CASE, NULLIF and membership probes.
214#[cfg(test)]
215pub(in crate::expr) fn values_equal(a: &Value, b: &Value) -> Result<bool> {
216    Ok(values_equal_nullable(a, b)? == Some(true))
217}
218
219pub fn values_equal_with_control(
220    a: &Value,
221    b: &Value,
222    control: &ProductionControl<'_>,
223) -> Result<bool> {
224    Ok(values_equal_nullable_with_control(a, b, control)? == Some(true))
225}
226
227#[cfg(test)]
228pub(in crate::expr) fn values_equal_nullable(a: &Value, b: &Value) -> Result<Option<bool>> {
229    values_equal_nullable_with_control(a, b, &ProductionControl::uncontrolled())
230}
231
232pub fn values_equal_nullable_with_control(
233    a: &Value,
234    b: &Value,
235    control: &ProductionControl<'_>,
236) -> Result<Option<bool>> {
237    values_equal_nullable_with_catalog(a, b, control, None, None)
238}
239
240fn values_equal_nullable_with_catalog(
241    a: &Value,
242    b: &Value,
243    control: &ProductionControl<'_>,
244    enums: Option<&dyn super::super::enums::EnumLabelCatalog>,
245    engine: Option<&dyn crate::expr::EngineHook>,
246) -> Result<Option<bool>> {
247    control.check()?;
248    if let Some(value) = super::super::enums::eval_comparison(BinaryOp::Equal, a, b, enums, None)? {
249        return match value {
250            Value::Null => Ok(None),
251            Value::Bool(value) => Ok(Some(value)),
252            _ => unreachable!("equality returns boolean or NULL"),
253        };
254    }
255    if let Some(order) = super::super::datums::compare_jsonb_with_control(a, b, control)? {
256        return Ok(Some(order.is_eq()));
257    }
258    if let Some(order) = compare_physical_range(a, b, control, enums)? {
259        return Ok(Some(order.is_eq()));
260    }
261    let equal = match (a, b) {
262        (Value::Null, _) | (_, Value::Null) => None,
263        (Value::Datum(datum), _) => {
264            return values_equal_nullable_with_catalog(
265                &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
266                b,
267                control,
268                enums,
269                engine,
270            )
271        }
272        (_, Value::Datum(datum)) => {
273            return values_equal_nullable_with_catalog(
274                a,
275                &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
276                control,
277                enums,
278                engine,
279            )
280        }
281        (Value::Temporal(x), Value::Str(y)) | (Value::Str(y), Value::Temporal(x)) => Some(
282            x.parse_same_kind_in_order_with_control(
283                y,
284                crate::expr::transaction_timestamp_or_clock(),
285                crate::expr::temporal_date_order(),
286                control,
287            )?
288            .is_some_and(|parsed| x.cmp(&parsed).is_eq()),
289        ),
290        (Value::Temporal(left), Value::Temporal(right)) => Some(
291            temporal::compare(left, right, engine, control)?
292                .map_or_else(|| left == right, Ordering::is_eq),
293        ),
294        (Value::FixedChar(x), Value::Str(y)) | (Value::Str(y), Value::FixedChar(x)) => {
295            Some(compare_fixed_text(x, y, control)?.is_eq())
296        }
297        // Anonymous rows use SQL three-valued equality: a definite mismatch wins over an earlier NULL field. Native arrays and stored records instead use total element equality through the value owner below.
298        (Value::Row(xs), Value::Row(ys)) => {
299            if xs.len() != ys.len() {
300                return Ok(Some(false));
301            }
302            let mut unknown = false;
303            for (index, (x, y)) in xs.iter().zip(ys).enumerate() {
304                let oid = row_field_oid(xs, index).or_else(|| row_field_oid(ys, index));
305                let equal = if let Some(order) = compare_declared_range(x, y, oid, control, enums)?
306                {
307                    Some(order.is_eq())
308                } else if matches!((x, y), (Value::Row(_), Value::Row(_))) {
309                    Some(equal_values(
310                        x,
311                        y,
312                        control,
313                        enums,
314                        false,
315                        collations::DEFAULT,
316                    )?)
317                } else {
318                    values_equal_nullable_with_catalog(x, y, control, enums, engine)?
319                };
320                match equal {
321                    Some(false) => return Ok(Some(false)),
322                    Some(true) => {}
323                    None => unknown = true,
324                }
325            }
326            if unknown {
327                None
328            } else {
329                Some(true)
330            }
331        }
332        _ => Some(equal_values(
333            a,
334            b,
335            control,
336            enums,
337            false,
338            collations::DEFAULT,
339        )?),
340    };
341    Ok(equal)
342}
343
344/// Compare with the existing two-valued selector convention that SQL UNKNOWN sorts as equal.
345pub fn compare_with_control(
346    a: &Value,
347    b: &Value,
348    control: &ProductionControl<'_>,
349) -> Result<Ordering> {
350    Ok(compare_nullable_with_control(a, b, control)?.unwrap_or(Ordering::Equal))
351}
352
353pub fn compare_nullable_with_control(
354    a: &Value,
355    b: &Value,
356    control: &ProductionControl<'_>,
357) -> Result<Option<Ordering>> {
358    compare_nullable_with_catalog(a, b, control, None, None, None)
359}
360
361fn compare_nullable_with_catalog(
362    a: &Value,
363    b: &Value,
364    control: &ProductionControl<'_>,
365    enums: Option<&dyn EnumLabelCatalog>,
366    state: Option<&EnumComparisonState>,
367    engine: Option<&dyn crate::expr::EngineHook>,
368) -> Result<Option<Ordering>> {
369    control.check()?;
370    if matches!(a, Value::Null) || matches!(b, Value::Null) {
371        return Ok(None);
372    }
373    if let Some(order) = super::super::enums::comparison_order(a, b, enums, state, false)? {
374        return Ok(Some(order));
375    }
376    if let Some(order) = super::super::datums::compare_jsonb_with_control(a, b, control)? {
377        return Ok(Some(order));
378    }
379    if let Some(order) = compare_physical_range(a, b, control, enums)? {
380        return Ok(Some(order));
381    }
382    match (a, b) {
383        (Value::Null, _) | (_, Value::Null) => Ok(None),
384        (Value::Datum(datum), _) => compare_nullable_with_catalog(
385            &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
386            b,
387            control,
388            enums,
389            state,
390            engine,
391        ),
392        (_, Value::Datum(datum)) => compare_nullable_with_catalog(
393            a,
394            &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
395            control,
396            enums,
397            state,
398            engine,
399        ),
400        (
401            Value::Int(_) | Value::Float(_) | Value::Decimal(_),
402            Value::Int(_) | Value::Float(_) | Value::Decimal(_),
403        )
404        | (Value::Bool(_), Value::Decimal(_))
405        | (Value::Decimal(_), Value::Bool(_))
406        | (Value::Str(_), Value::Str(_))
407        | (Value::FixedChar(_), Value::FixedChar(_))
408        | (Value::BitString(_), Value::BitString(_))
409        | (Value::JsonB(_), Value::JsonB(_))
410        | (Value::Bool(_), Value::Bool(_))
411        | (Value::Array(_), Value::Array(_))
412        | (Value::LegacyVector(_), Value::LegacyVector(_))
413        | (Value::List(_), Value::List(_))
414        | (Value::Record(_), Value::Record(_) | Value::Row(_))
415        | (Value::Row(_), Value::Record(_))
416        | (Value::Enum(_), Value::Enum(_)) => Ok(Some(compare_sql_values(a, b, control, enums)?)),
417        (Value::Temporal(left), Value::Temporal(right)) => Ok(Some(
418            temporal::compare(left, right, engine, control)?.unwrap_or_else(|| left.cmp(right)),
419        )),
420        (Value::FixedChar(x), Value::Str(y)) | (Value::Str(x), Value::FixedChar(y)) => {
421            Ok(Some(compare_fixed_text(x, y, control)?))
422        }
423        (Value::Temporal(x), Value::Str(y)) => x
424            .parse_same_kind_in_order_with_control(
425                y,
426                crate::expr::transaction_timestamp_or_clock(),
427                crate::expr::temporal_date_order(),
428                control,
429            )?
430            .map(|parsed| Some(x.cmp(&parsed)))
431            .ok_or_else(|| SQLError::TypeMismatch(format!("cannot compare {a:?} with {b:?}"))),
432        (Value::Str(x), Value::Temporal(y)) => y
433            .parse_same_kind_in_order_with_control(
434                x,
435                crate::expr::transaction_timestamp_or_clock(),
436                crate::expr::temporal_date_order(),
437                control,
438            )?
439            .map(|parsed| Some(parsed.cmp(y)))
440            .ok_or_else(|| SQLError::TypeMismatch(format!("cannot compare {a:?} with {b:?}"))),
441        // Ordering is lexicographic; reaching NULL before a definite comparison leaves it unknown.
442        (Value::Row(xs), Value::Row(ys)) => {
443            compare_anonymous_row(xs, ys, control, enums, state, engine)
444        }
445        (lhs, rhs) => Err(SQLError::TypeMismatch(format!(
446            "cannot compare {lhs:?} with {rhs:?}"
447        ))),
448    }
449}
450
451fn compare_anonymous_row(
452    left: &uqa_core::RowValue,
453    right: &uqa_core::RowValue,
454    control: &ProductionControl<'_>,
455    enums: Option<&dyn EnumLabelCatalog>,
456    state: Option<&EnumComparisonState>,
457    engine: Option<&dyn crate::expr::EngineHook>,
458) -> Result<Option<Ordering>> {
459    for (index, (left_value, right_value)) in left.iter().zip(right).enumerate() {
460        let oid = row_field_oid(left, index).or_else(|| row_field_oid(right, index));
461        let (left, right) = (left_value, right_value);
462        let field =
463            if matches!(left, Value::Enum(_) | Value::Datum(_)) && !matches!(right, Value::Null) {
464                state.map(|state| state.field(index))
465            } else {
466                None
467            };
468        let order = if let Some(order) = compare_declared_range(left, right, oid, control, enums)? {
469            Some(order)
470        } else if matches!((left, right), (Value::Row(_), Value::Row(_))) {
471            Some(compare_typed_values_with_catalog(
472                left, right, control, enums,
473            )?)
474        } else {
475            compare_nullable_with_catalog(left, right, control, enums, field.as_deref(), engine)?
476        };
477        match order {
478            Some(Ordering::Equal) => {}
479            other => return Ok(other),
480        }
481    }
482    Ok(Some(left.len().cmp(&right.len())))
483}
484
485fn row_field_oid(row: &uqa_core::RowValue, index: usize) -> Option<u32> {
486    row.field_types()?.get(index).map(|field| field.oid)
487}
488
489fn compare_sql_values(
490    left: &Value,
491    right: &Value,
492    control: &ProductionControl<'_>,
493    enums: Option<&dyn EnumLabelCatalog>,
494) -> Result<Ordering> {
495    // Primitive mixed float/integer and float/numeric operators select float8 inputs. Physical keys and already-bound container elements keep their exact carrier order.
496    if matches!(
497        (left, right),
498        (Value::Float(_), Value::Int(_) | Value::Decimal(_))
499            | (Value::Int(_) | Value::Decimal(_), Value::Float(_))
500    ) {
501        let left =
502            super::super::cast_value_from_with_control(left, "double precision", None, control)?;
503        let right =
504            super::super::cast_value_from_with_control(right, "double precision", None, control)?;
505        return Ok(left.cmp(&right));
506    }
507    compare_typed_values_with_catalog(left, right, control, enums)
508}
509
510/// Compare already-bound values, preserving type operator failures and total container NULL semantics. Callers supply top-level NULL placement and must apply operator-selected casts first.
511pub fn compare_typed_values_with_control(
512    left: &Value,
513    right: &Value,
514    control: &ProductionControl<'_>,
515) -> Result<Ordering> {
516    compare_typed_values_with_catalog(left, right, control, None)
517}
518
519/// Compare one physical ordering key with its private scalar enum call state. Nested array/record fields use the catalog's shared type comparison state.
520pub fn compare_typed_values_with_enum_catalog(
521    left: &Value,
522    right: &Value,
523    control: &ProductionControl<'_>,
524    enums: Option<&dyn EnumLabelCatalog>,
525    state: Option<&EnumComparisonState>,
526) -> Result<Ordering> {
527    control.check()?;
528    if !matches!(left, Value::Null) && !matches!(right, Value::Null) {
529        if let Some(order) =
530            super::super::enums::comparison_order(left, right, enums, state, false)?
531        {
532            return Ok(order);
533        }
534    }
535    compare_typed_values_with_catalog(left, right, control, enums)
536}
537
538/// Order internal equality groups by physical enum identity, including nested keys. This ordering is not exposed as SQL ORDER BY and never observes an enum label merely to eliminate duplicates.
539pub fn compare_grouping_values_with_enum_catalog(
540    left: &Value,
541    right: &Value,
542    control: &ProductionControl<'_>,
543    enums: Option<&dyn EnumLabelCatalog>,
544) -> Result<Ordering> {
545    compare_typed_values_for_purpose(
546        left,
547        right,
548        control,
549        enums,
550        EnumKeyOrder::Identity,
551        collations::DEFAULT,
552    )
553}
554
555#[derive(Clone, Copy)]
556pub(super) enum EnumKeyOrder {
557    Declaration,
558    Identity,
559}
560
561fn enum_key_order(
562    left: &Value,
563    right: &Value,
564    enums: Option<&dyn EnumLabelCatalog>,
565    order: EnumKeyOrder,
566) -> Result<Option<Ordering>> {
567    if matches!(order, EnumKeyOrder::Identity) {
568        if let Some(enums) = enums {
569            if let (Some(left), Some(right)) = (
570                super::super::enums::comparison_identity(enums, left)?,
571                super::super::enums::comparison_identity(enums, right)?,
572            ) {
573                return Ok(Some(left.cmp(&right)));
574            }
575        }
576        return Ok(None);
577    }
578    super::super::enums::comparison_order(left, right, enums, None, true)
579}
580
581fn compare_typed_values_with_catalog(
582    left: &Value,
583    right: &Value,
584    control: &ProductionControl<'_>,
585    enums: Option<&dyn EnumLabelCatalog>,
586) -> Result<Ordering> {
587    compare_typed_values_for_purpose(
588        left,
589        right,
590        control,
591        enums,
592        EnumKeyOrder::Declaration,
593        collations::DEFAULT,
594    )
595}
596
597fn compare_typed_values_for_purpose(
598    left: &Value,
599    right: &Value,
600    control: &ProductionControl<'_>,
601    enums: Option<&dyn EnumLabelCatalog>,
602    enum_order: EnumKeyOrder,
603    collation: u32,
604) -> Result<Ordering> {
605    control.check()?;
606    if let Some(order) = super::super::datums::compare_jsonb_with_control(left, right, control)? {
607        return Ok(order);
608    }
609    match (left, right) {
610        (Value::Null, Value::Null) => return Ok(Ordering::Equal),
611        (Value::Null, _) => return Ok(Ordering::Greater),
612        (_, Value::Null) => return Ok(Ordering::Less),
613        _ => {}
614    }
615    if let Some(order) = enum_key_order(left, right, enums, enum_order)? {
616        return Ok(order);
617    }
618    if let Some(order) = compare_physical_range(left, right, control, enums)? {
619        return Ok(order);
620    }
621    match (left, right) {
622        (Value::Datum(datum), _) => {
623            return compare_typed_values_for_purpose(
624                &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
625                right,
626                control,
627                enums,
628                enum_order,
629                collation,
630            )
631        }
632        (_, Value::Datum(datum)) => {
633            return compare_typed_values_for_purpose(
634                left,
635                &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
636                control,
637                enums,
638                enum_order,
639                collation,
640            )
641        }
642        (Value::Array(left), Value::Array(right)) => {
643            return compare_arrays(left, right, control, enums, enum_order, collation);
644        }
645        (Value::Record(_) | Value::Row(_), Value::Record(_) | Value::Row(_)) => {
646            return records::compare_typed(left, right, enums, control, enum_order);
647        }
648        (Value::List(left), Value::List(right)) => {
649            return compare_sequence(
650                left.iter(),
651                right.iter(),
652                control,
653                enums,
654                enum_order,
655                collation,
656            );
657        }
658        (Value::Str(left), Value::Str(right)) => {
659            return collations::compare_text(left, right, collation, enum_order, control);
660        }
661        (Value::FixedChar(left), Value::FixedChar(right)) => {
662            let left = uqa_core::fixed_char_comparison_text_with_control(left, control)?;
663            let right = uqa_core::fixed_char_comparison_text_with_control(right, control)?;
664            return collations::compare_text(left, right, collation, enum_order, control);
665        }
666        // Enum operators are declared on one enum type; binding coerces every other operand to it.
667        (Value::Enum(left), Value::Enum(right)) if left.type_oid() == right.type_oid() => {
668            return Ok(left.key().cmp(right.key()));
669        }
670        (Value::Enum(_), _) | (_, Value::Enum(_)) => {
671            return Err(SQLError::Internal(format!(
672                "enum comparison reached operands of different types: {} and {}",
673                comparison_operand_type(left),
674                comparison_operand_type(right)
675            )));
676        }
677        (Value::Json(_), Value::Json(_)) => {
678            return Err(ComparisonSupport::Ordering.error("42883", "json".into()));
679        }
680        _ => {}
681    }
682    for value in [left, right] {
683        if let Value::LegacyVector(vector) = value {
684            validate_legacy_vector_comparison(vector)?;
685        }
686    }
687    left.cmp_with_control(right, control).map_err(Into::into)
688}
689
690pub(super) fn compare_arrays(
691    left: &uqa_core::ArrayValue,
692    right: &uqa_core::ArrayValue,
693    control: &ProductionControl<'_>,
694    enums: Option<&dyn EnumLabelCatalog>,
695    enum_order: EnumKeyOrder,
696    collation: u32,
697) -> Result<Ordering> {
698    validate_array_element_types(left, right)?;
699    let oid = left.element_type_oid().or(right.element_type_oid());
700    left.cmp_by_with_control(right, control, |left, right, control| {
701        if let Some(order) = compare_declared_range(left, right, oid, control, enums)? {
702            return Ok(order);
703        }
704        compare_typed_values_for_purpose(left, right, control, enums, enum_order, collation)
705    })
706}
707
708fn comparison_operand_type(value: &Value) -> String {
709    match value {
710        Value::Enum(label) => format!("enum type OID {}", label.type_oid()),
711        other => super::super::diagnostics::value_type_name(other).to_owned(),
712    }
713}
714
715/// Validate the layout required by the `oidvector` scalar equality, ordering and hashing operators. Array operators on `int2vector` permit dimensionless arrays.
716pub fn validate_legacy_vector_comparison(vector: &uqa_core::LegacyVectorValue) -> Result<()> {
717    if vector.kind() == uqa_core::LegacyVectorKind::Oid && !vector.has_vector_layout() {
718        return Err(SQLError::Routine {
719            sqlstate: "42804".into(),
720            message: "array is not a valid oidvector".into(),
721        });
722    }
723    Ok(())
724}
725
726/// Declared SQL keys whose runtime values may require a fallible comparison operator.
727pub fn type_comparison_can_fail(ty: &crate::ast::ColumnType) -> bool {
728    use crate::ast::ColumnType;
729    match ty {
730        ColumnType::OidVector
731        | ColumnType::Record
732        | ColumnType::Composite(_)
733        | ColumnType::Array(_) => true,
734        ColumnType::Domain { base: element, .. } => type_comparison_can_fail(element),
735        _ => false,
736    }
737}
738
739/// Whether an opaque value key can suppress a SQL operator failure. A single such input remains legal until an operator compares it.
740pub fn value_comparison_can_fail(value: &Value) -> bool {
741    match value {
742        Value::Datum(_) => true,
743        Value::LegacyVector(vector) => {
744            vector.kind() == uqa_core::LegacyVectorKind::Oid && !vector.has_vector_layout()
745        }
746        Value::Array(array) => {
747            array.element_type_oid().is_some()
748                || array.elements().iter().any(value_comparison_can_fail)
749        }
750        Value::Row(values) => {
751            values.field_types().is_some() || values.iter().any(value_comparison_can_fail)
752        }
753        Value::List(values) => values.iter().any(value_comparison_can_fail),
754        Value::Record(fields) => {
755            fields.type_oid().is_some()
756                || fields
757                    .iter()
758                    .any(|(_, value)| value_comparison_can_fail(value))
759        }
760        _ => false,
761    }
762}
763
764/// Compare already-bound group/hash keys without enum output. Physical enum
765/// identities use the same equality as `enum_eq`, including inside containers.
766pub fn equal_typed_values_with_enum_catalog(
767    left: &Value,
768    right: &Value,
769    control: &ProductionControl<'_>,
770    enums: Option<&dyn super::super::enums::EnumLabelCatalog>,
771) -> Result<bool> {
772    equal_values(left, right, control, enums, true, collations::DEFAULT)
773}
774
775fn equal_values(
776    left: &Value,
777    right: &Value,
778    control: &ProductionControl<'_>,
779    enums: Option<&dyn super::super::enums::EnumLabelCatalog>,
780    typed: bool,
781    collation: u32,
782) -> Result<bool> {
783    control.check()?;
784    if let Some(order) = super::super::datums::compare_jsonb_with_control(left, right, control)? {
785        return Ok(order.is_eq());
786    }
787    if matches!(left, Value::Null) || matches!(right, Value::Null) {
788        return Ok(matches!((left, right), (Value::Null, Value::Null)));
789    }
790    if let Some(enums) = enums {
791        if let (Some(left), Some(right)) = (
792            super::super::enums::comparison_identity(enums, left)?,
793            super::super::enums::comparison_identity(enums, right)?,
794        ) {
795            return Ok(left == right);
796        }
797    }
798    if let Some(order) = compare_physical_range(left, right, control, enums)? {
799        return Ok(order.is_eq());
800    }
801    match (left, right) {
802        (Value::Datum(datum), _) => equal_values(
803            &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
804            right,
805            control,
806            enums,
807            typed,
808            collation,
809        ),
810        (_, Value::Datum(datum)) => equal_values(
811            left,
812            &*super::super::datums::read_with_value_catalog_and_control(datum, enums, control)?,
813            control,
814            enums,
815            typed,
816            collation,
817        ),
818        (Value::Array(left), Value::Array(right)) => {
819            validate_array_element_types(left, right)?;
820            let oid = left.element_type_oid().or(right.element_type_oid());
821            left.eq_by_with_control(right, control, |left, right, control| {
822                if let Some(order) = compare_declared_range(left, right, oid, control, enums)? {
823                    return Ok(order.is_eq());
824                }
825                equal_values(left, right, control, enums, typed, collation)
826            })
827        }
828        (Value::Record(_) | Value::Row(_), Value::Record(_) | Value::Row(_)) => {
829            records::equal_typed(left, right, enums, control, typed)
830        }
831        (Value::List(left), Value::List(right)) => {
832            equal_sequence(left.iter(), right.iter(), control, enums, typed, collation)
833        }
834        (Value::Str(left), Value::Str(right)) => {
835            Ok(
836                collations::compare_text(left, right, collation, EnumKeyOrder::Identity, control)?
837                    .is_eq(),
838            )
839        }
840        (Value::FixedChar(left), Value::FixedChar(right)) => {
841            let left = uqa_core::fixed_char_comparison_text_with_control(left, control)?;
842            let right = uqa_core::fixed_char_comparison_text_with_control(right, control)?;
843            Ok(
844                collations::compare_text(left, right, collation, EnumKeyOrder::Identity, control)?
845                    .is_eq(),
846            )
847        }
848        (Value::Json(_), Value::Json(_)) => {
849            Err(ComparisonSupport::Equality.error("42883", "json".into()))
850        }
851        _ if typed => Ok(compare_typed_values_with_control(left, right, control)?.is_eq()),
852        _ => Ok(compare_sql_values(left, right, control, enums)?.is_eq()),
853    }
854}
855
856fn compare_physical_range(
857    left: &Value,
858    right: &Value,
859    control: &ProductionControl<'_>,
860    catalog: Option<&dyn EnumLabelCatalog>,
861) -> Result<Option<Ordering>> {
862    use crate::expr::range::RangeComparisonValue;
863    if matches!(left, Value::Null) || matches!(right, Value::Null) {
864        return Ok(None);
865    }
866    let oid = match RangeComparisonValue::declared_physical_oid(left, catalog)? {
867        Some(oid) => Some(oid),
868        None => RangeComparisonValue::declared_physical_oid(right, catalog)?,
869    };
870    compare_declared_range(left, right, oid, control, catalog)
871}
872
873fn compare_declared_range(
874    left: &Value,
875    right: &Value,
876    oid: Option<u32>,
877    control: &ProductionControl<'_>,
878    catalog: Option<&dyn EnumLabelCatalog>,
879) -> Result<Option<Ordering>> {
880    let Some(oid) = oid else {
881        return Ok(None);
882    };
883    // Ordinary text retains text order. A range identity comes from the selected record field or array element, never from the spelling of its value.
884    if !matches!(
885        (left, right),
886        (
887            Value::Str(_) | Value::Datum(_),
888            Value::Str(_) | Value::Datum(_)
889        )
890    ) {
891        return Ok(None);
892    }
893    use crate::expr::range::RangeComparisonValue;
894    let Some(left) = RangeComparisonValue::from_declared_with_control(left, oid, catalog, control)?
895    else {
896        return Ok(None);
897    };
898    let right = RangeComparisonValue::from_declared_with_control(right, oid, catalog, control)?
899        .ok_or_else(|| {
900            SQLError::Internal("selected range identity changed during comparison".into())
901        })?;
902    left.cmp_with_catalog_and_control(&right, catalog, control)
903        .map(Some)
904}
905
906fn validate_array_element_types(
907    left: &uqa_core::ArrayValue,
908    right: &uqa_core::ArrayValue,
909) -> Result<()> {
910    if matches!((left.element_type_oid(), right.element_type_oid()), (Some(left), Some(right)) if left != right)
911    {
912        return Err(SQLError::Routine {
913            sqlstate: "42804".into(),
914            message: "cannot compare arrays of different element types".into(),
915        });
916    }
917    Ok(())
918}
919
920fn equal_sequence<'a>(
921    mut left: impl Iterator<Item = &'a Value>,
922    mut right: impl Iterator<Item = &'a Value>,
923    control: &ProductionControl<'_>,
924    enums: Option<&dyn super::super::enums::EnumLabelCatalog>,
925    typed: bool,
926    collation: u32,
927) -> Result<bool> {
928    loop {
929        control.check()?;
930        match (left.next(), right.next()) {
931            (Some(left), Some(right))
932                if equal_values(left, right, control, enums, typed, collation)? => {}
933            (None, None) => return Ok(true),
934            _ => return Ok(false),
935        }
936    }
937}
938
939fn compare_sequence<'a>(
940    mut left: impl Iterator<Item = &'a Value>,
941    mut right: impl Iterator<Item = &'a Value>,
942    control: &ProductionControl<'_>,
943    enums: Option<&dyn EnumLabelCatalog>,
944    enum_order: EnumKeyOrder,
945    collation: u32,
946) -> Result<Ordering> {
947    loop {
948        control.check()?;
949        let ordering = match (left.next(), right.next()) {
950            (Some(left), Some(right)) => compare_typed_values_for_purpose(
951                left, right, control, enums, enum_order, collation,
952            )?,
953            (Some(_), None) => Ordering::Greater,
954            (None, Some(_)) => Ordering::Less,
955            (None, None) => return Ok(Ordering::Equal),
956        };
957        if !ordering.is_eq() {
958            return Ok(ordering);
959        }
960    }
961}
962
963fn compare_fixed_text(
964    left: &str,
965    right: &str,
966    control: &ProductionControl<'_>,
967) -> Result<Ordering> {
968    let left = uqa_core::fixed_char_comparison_text_with_control(left, control)?;
969    let right = uqa_core::fixed_char_comparison_text_with_control(right, control)?;
970    let left = left.as_bytes();
971    let right = right.as_bytes();
972    for (left, right) in left.chunks(4096).zip(right.chunks(4096)) {
973        control.check()?;
974        let ordering = left.cmp(right);
975        if !ordering.is_eq() {
976            return Ok(ordering);
977        }
978    }
979    control.check()?;
980    Ok(left.len().cmp(&right.len()))
981}
982
983#[cfg(test)]
984mod tests;