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