Skip to main content

datafusion_expr_common/
casts.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Utilities for casting scalar literals to different data types
6//!
7//! This module contains functions for casting ScalarValue literals
8//! to different data types, originally extracted from the optimizer's
9//! unwrap_cast module to be shared between logical and physical layers.
10
11use std::cmp::Ordering;
12use std::sync::Arc;
13
14use crate::interval_arithmetic::Interval;
15use crate::operator::Operator;
16
17use arrow::datatypes::{
18    DataType, MAX_DECIMAL32_FOR_EACH_PRECISION, MAX_DECIMAL64_FOR_EACH_PRECISION,
19    MAX_DECIMAL128_FOR_EACH_PRECISION, MIN_DECIMAL32_FOR_EACH_PRECISION,
20    MIN_DECIMAL64_FOR_EACH_PRECISION, MIN_DECIMAL128_FOR_EACH_PRECISION, TimeUnit,
21};
22use arrow::temporal_conversions::{
23    MICROSECONDS, MILLISECONDS, MILLISECONDS_IN_DAY, NANOSECONDS,
24};
25use datafusion_common::{Result, ScalarValue};
26
27/// Source-domain preimage of `CAST(source_expr AS target_type) OP literal`.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum CastPredicatePreimage {
30    /// An exact same-operator source bound or literal, i.e. the rewrite is
31    /// `source_expr OP value` with the original comparison operator.
32    Exact(ScalarValue),
33    /// A half-open source-domain interval `[lower, upper)`; the caller maps the
34    /// comparison operator onto its bounds. Equal bounds mean no single source
35    /// value maps to the literal, an empty equality preimage, while ordered
36    /// comparisons still compare against that bound as in `< bound` or
37    /// `>= bound`.
38    Range(Interval),
39}
40
41impl CastPredicatePreimage {
42    /// Returns whether this preimage and comparison operator produce multiple
43    /// predicates that each evaluate the input expression.
44    pub fn duplicates_input(&self, op: Operator) -> bool {
45        matches!(self, Self::Range(_))
46            && matches!(
47                op,
48                Operator::Eq
49                    | Operator::NotEq
50                    | Operator::IsDistinctFrom
51                    | Operator::IsNotDistinctFrom
52            )
53    }
54}
55
56/// Convert a literal [`ScalarValue`] to `target_type`, preserving the exact value.
57///
58/// Returns `None` if the value cannot be represented in `target_type`
59/// *exactly*.
60///
61/// This is a restricted, value-preserving cast used to rewrite comparison
62/// predicates of the form `CAST(col AS target_type) <op> literal` into
63/// `col <op> try_cast_literal_to_type(literal, col_type)`. The rewrite requires
64/// an exact literal preimage and an accepted cast family; for integer or
65/// decimal sources with a decimal target of equal or greater scale, it may
66/// change cast overflow errors or NULLs to a boolean result for values outside
67/// the target range.
68///
69/// # Supported Casts
70/// * numeric → numeric, including integers, decimals, `Date32`/`Date64` and
71///   `Timestamps`, rejecting literal conversions outside the target's range or
72///   that would lose decimal digits
73/// * string → string between `Utf8`, `LargeUtf8` and `Utf8View`
74/// * wrapping a value into, or unwrapping it out of, a `Dictionary` whose value
75///   type matches the literal's type
76/// * `Binary` → `FixedSizeBinary` of the matching length
77/// * `Timestamp` → `Timestamp` cast between different time units is allowed even
78///   though it can truncate (for example nanoseconds → seconds), and a unit
79///   conversion that overflows yields a `NULL` literal rather than `None`.
80///
81/// # See Also
82/// - [`ScalarValue::cast_to`]: a general-purpose cast that can lose information
83///   or change a value's meaning.
84pub fn try_cast_literal_to_type(
85    lit_value: &ScalarValue,
86    target_type: &DataType,
87) -> Option<ScalarValue> {
88    let lit_data_type = lit_value.data_type();
89    if !is_supported_type(&lit_data_type) || !is_supported_type(target_type) {
90        return None;
91    }
92    if lit_value.is_null() {
93        // null value can be cast to any type of null value
94        return ScalarValue::try_from(target_type).ok();
95    }
96    try_cast_numeric_literal(lit_value, target_type)
97        .or_else(|| try_cast_string_literal(lit_value, target_type))
98        .or_else(|| try_cast_dictionary(lit_value, target_type))
99        .or_else(|| try_cast_binary(lit_value, target_type))
100}
101
102/// Computes a source-domain preimage for `CAST(source AS target_type) OP literal`.
103///
104/// This is the shared semantic core for logical and physical cast-predicate
105/// rewrites. It returns an exact same-operator source bound or literal as
106/// [`CastPredicatePreimage::Exact`] where moving the cast preserves comparison
107/// semantics subject to the documented family-level overflow exceptions, and a
108/// [`CastPredicatePreimage::Range`] for many-to-one casts with known preimages
109/// (timestamp precision narrowing) or for non-aligned timestamp widening
110/// literals.
111pub fn cast_predicate_preimage(
112    source_type: &DataType,
113    target_type: &DataType,
114    op: Operator,
115    lit_value: &ScalarValue,
116) -> Result<Option<CastPredicatePreimage>> {
117    // Timestamp casts have their own rules: a truncation bucket when the cast
118    // narrows, and the source values equal to the literal when it does not. A
119    // rejected timestamp cast keeps its `CAST` instead of falling back to
120    // another cast family.
121    if let Some((source, target)) = timestamp_cast_types(source_type, target_type) {
122        return Ok(timestamp_preimage(
123            source_type,
124            source,
125            target,
126            op,
127            lit_value,
128        ));
129    }
130
131    if let Some(value) =
132        exact_preimage_int_to_str_eq_like(source_type, target_type, op, lit_value)
133    {
134        return Ok(Some(CastPredicatePreimage::Exact(value)));
135    }
136
137    Ok(exact_preimage_cast(source_type, target_type, lit_value)
138        .map(CastPredicatePreimage::Exact))
139}
140
141/// Computes a singleton source-domain literal for exact cast-predicate rewrites.
142///
143/// This intentionally returns `None` for timestamp precision narrowing and for
144/// non-aligned timestamp widening: those casts need range preimages instead.
145pub fn exact_preimage_cast(
146    source_type: &DataType,
147    target_type: &DataType,
148    lit_value: &ScalarValue,
149) -> Option<ScalarValue> {
150    // Timestamp casts need unit arithmetic rather than a literal round trip; only
151    // their singleton preimages are valid here.
152    if let Some((source, target)) = timestamp_cast_types(source_type, target_type) {
153        return match timestamp_preimage(
154            source_type,
155            source,
156            target,
157            Operator::Eq,
158            lit_value,
159        )? {
160            CastPredicatePreimage::Exact(value) => Some(value),
161            CastPredicatePreimage::Range(_) => None,
162        };
163    }
164
165    // Apply a family-level gate: the source→target cast must normally preserve
166    // the full source domain. Integer or decimal sources to a decimal target
167    // are admitted by scale instead (see `is_exact_cast_safe`), accepting
168    // precision/width overflow as a boolean result for out-of-range rows.
169    if !is_exact_cast_safe(source_type, target_type) {
170        return None;
171    }
172
173    try_cast_literal_to_type(lit_value, source_type)
174}
175
176/// Returns true when casting a timestamp from `source_type` to `target_type`
177/// loses timestamp precision.
178pub fn is_timestamp_precision_narrowing_cast(
179    source_type: &DataType,
180    target_type: &DataType,
181) -> bool {
182    let (DataType::Timestamp(source_unit, _), DataType::Timestamp(target_unit, _)) =
183        (source_type, target_type)
184    else {
185        return false;
186    };
187
188    timestamp_unit_scale(source_unit) > timestamp_unit_scale(target_unit)
189}
190
191/// Returns the source and target types of a timestamp cast, each unwrapped from
192/// at most one `Dictionary` level.
193fn timestamp_cast_types<'a>(
194    source_type: &'a DataType,
195    target_type: &'a DataType,
196) -> Option<(&'a DataType, &'a DataType)> {
197    let unwrap = |data_type: &'a DataType| match data_type {
198        DataType::Dictionary(_, value_type) => value_type.as_ref(),
199        data_type => data_type,
200    };
201    let (source, target) = (unwrap(source_type), unwrap(target_type));
202    (matches!(source, DataType::Timestamp(_, _))
203        && matches!(target, DataType::Timestamp(_, _)))
204    .then_some((source, target))
205}
206
207/// Returns `true` when casting `source_type` to `target_type` is exact and
208/// order-preserving over the source values the cast succeeds on. Integer or
209/// decimal sources to a decimal target are admitted when the source scale is
210/// nonnegative and the target scale is at least the source scale: a successful
211/// cast only multiplies the unscaled value by an integral power of ten.
212/// Precision or width overflow is the explicit exception: `CAST` errors and
213/// `TRY_CAST` yields NULL for such source values, while the rewritten predicate
214/// compares the source value and returns TRUE/FALSE. This rule is type-based
215/// and does not distinguish implicit coercions from explicit casts.
216///
217/// This is a conservative gate used by [`exact_preimage_cast`] for the non
218/// timestamp cast families; timestamp casts are handled by
219/// [`timestamp_preimage`] instead.
220fn is_exact_cast_safe(source_type: &DataType, target_type: &DataType) -> bool {
221    // Unwrap at most one level of dictionary for family-level checking.
222    let (src, tgt) = match (source_type, target_type) {
223        (DataType::Dictionary(_, v_src), DataType::Dictionary(_, v_tgt)) => {
224            (v_src.as_ref(), v_tgt.as_ref())
225        }
226        (DataType::Dictionary(_, v_src), tgt) => (v_src.as_ref(), tgt),
227        (src, DataType::Dictionary(_, v_tgt)) => (src, v_tgt.as_ref()),
228        _ => (source_type, target_type),
229    };
230
231    // Integer or decimal sources to a decimal target are accepted when the
232    // source scale is nonnegative and the target only adds fractional digits.
233    // This precedes identity so negative-scale decimals are rejected by the
234    // scale check instead of reaching the scale arithmetic and panicking.
235    if is_decimal_type(tgt) && (is_decimal_type(src) || is_integer_type(src)) {
236        let s_src = if is_decimal_type(src) {
237            decimal_precision_scale(src).1
238        } else {
239            0
240        };
241        return s_src >= 0 && decimal_precision_scale(tgt).1 >= s_src;
242    }
243
244    if src == tgt {
245        return true;
246    }
247
248    // Whitelist of family-level safe casts.  Anything not listed here is
249    // considered potentially information-losing and blocked.
250    if is_integer_type(src) && is_integer_type(tgt) {
251        return is_safe_integer_cast(src, tgt);
252    }
253    if matches!(
254        (src, tgt),
255        (DataType::Date32, DataType::Int32)
256            | (DataType::Int32, DataType::Date32)
257            | (DataType::Date64, DataType::Int64)
258            | (DataType::Int64, DataType::Date64)
259    ) {
260        // Date32 ↔ Int32 and Date64 ↔ Int64 share the same internal
261        // representation.
262        return true;
263    }
264    if matches!((src, tgt), (DataType::Date32, DataType::Date64)) {
265        // Date32 → Date64 is injective: every source day maps to its midnight
266        // millisecond value. The literal conversion below enforces the exact
267        // day-boundary requirement in the reverse direction.
268        return true;
269    }
270    if is_supported_string_type(src) && is_supported_string_type(tgt) {
271        // String width casts among Utf8 / LargeUtf8 / Utf8View.
272        return true;
273    }
274    if matches!((src, tgt), (DataType::FixedSizeBinary(_), DataType::Binary)) {
275        // FixedSizeBinary(n) → Binary is always widening.
276        return true;
277    }
278    if matches!(
279        (src, tgt),
280        (DataType::FixedSizeBinary(n1), DataType::FixedSizeBinary(n2)) if n1 == n2
281    ) {
282        return true;
283    }
284    false
285}
286
287/// Returns `true` for integer types (signed and unsigned, excluding Date and
288/// Decimal).
289fn is_integer_type(dt: &DataType) -> bool {
290    matches!(
291        dt,
292        DataType::Int8
293            | DataType::Int16
294            | DataType::Int32
295            | DataType::Int64
296            | DataType::UInt8
297            | DataType::UInt16
298            | DataType::UInt32
299            | DataType::UInt64
300    )
301}
302
303/// Integer cast that is value-preserving over the full source domain.
304fn is_safe_integer_cast(src: &DataType, tgt: &DataType) -> bool {
305    use DataType::*;
306    match (src, tgt) {
307        // Signed → wider signed
308        (Int8, Int16 | Int32 | Int64) => true,
309        (Int16, Int32 | Int64) => true,
310        (Int32, Int64) => true,
311        // Unsigned → wider unsigned
312        (UInt8, UInt16 | UInt32 | UInt64) => true,
313        (UInt16, UInt32 | UInt64) => true,
314        (UInt32, UInt64) => true,
315        // Unsigned → wider signed (full source range fits in target)
316        (UInt8, Int16 | Int32 | Int64) => true,
317        (UInt16, Int32 | Int64) => true,
318        (UInt32, Int64) => true,
319        // Anything else is narrowing, partial, or crosses signedness
320        // without guaranteed domain containment.
321        _ => false,
322    }
323}
324
325fn is_decimal_type(dt: &DataType) -> bool {
326    matches!(
327        dt,
328        DataType::Decimal128(_, _)
329            | DataType::Decimal64(_, _)
330            | DataType::Decimal32(_, _)
331    )
332}
333
334fn decimal_precision_scale(dt: &DataType) -> (u8, i8) {
335    match dt {
336        DataType::Decimal128(p, s)
337        | DataType::Decimal64(p, s)
338        | DataType::Decimal32(p, s) => (*p, *s),
339        _ => unreachable!(),
340    }
341}
342
343/// Computes a singleton preimage for equality-like predicates over casts whose
344/// target value is a string representation of an integer source value.
345///
346/// For example, `CAST(int_col AS Utf8) = '123'` can be rewritten to
347/// `int_col = 123`, but `CAST(int_col AS Utf8) = '0123'` cannot be rewritten to
348/// `int_col = 123` because casting `123` back to a string yields `'123'`, not
349/// `'0123'`.
350fn exact_preimage_int_to_str_eq_like(
351    source_type: &DataType,
352    target_type: &DataType,
353    op: Operator,
354    lit_value: &ScalarValue,
355) -> Option<ScalarValue> {
356    if !matches!(
357        target_type,
358        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
359    ) {
360        return None;
361    }
362
363    match (op, lit_value) {
364        (
365            Operator::Eq
366            | Operator::NotEq
367            | Operator::IsDistinctFrom
368            | Operator::IsNotDistinctFrom,
369            ScalarValue::Utf8(Some(_))
370            | ScalarValue::Utf8View(Some(_))
371            | ScalarValue::LargeUtf8(Some(_)),
372        ) => {
373            // Only try for integer types (TODO can we do this for other types
374            // like timestamps)?
375            use DataType::*;
376            if matches!(
377                source_type,
378                Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64
379            ) {
380                let casted = lit_value.cast_to(source_type).ok()?;
381                let round_tripped = casted.cast_to(&lit_value.data_type()).ok()?;
382                if lit_value != &round_tripped {
383                    return None;
384                }
385                Some(casted)
386            } else {
387                None
388            }
389        }
390        _ => None,
391    }
392}
393
394/// Computes the source-domain preimage of `CAST(source AS target) OP literal`
395/// for a timestamp precision cast.
396///
397/// `source` and `target` are already unwrapped from one `Dictionary` level;
398/// `source_type` is the original source type, whose dictionary key is applied to
399/// every bound together with the source unit and timezone, so nothing from the
400/// target type leaks into the rewritten predicate. Rejected casts return `None`.
401///
402/// Retained policy: at extreme source values where the cast itself overflows,
403/// `CAST` can error and `TRY_CAST` can return `NULL` while the rewritten
404/// source-unit comparison returns a Boolean.
405fn timestamp_preimage(
406    source_type: &DataType,
407    source: &DataType,
408    target: &DataType,
409    op: Operator,
410    lit_value: &ScalarValue,
411) -> Option<CastPredicatePreimage> {
412    let (
413        DataType::Timestamp(source_unit, source_tz),
414        DataType::Timestamp(target_unit, target_tz),
415    ) = (source, target)
416    else {
417        return None;
418    };
419
420    // Arrow reads a naive value as local wall-clock time in the target timezone
421    // and shifts it to UTC (`adjust_timestamp_to_timezone`), which this unit
422    // arithmetic does not model, so the cast is kept.
423    if source_tz.is_none() && target_tz.is_some() {
424        return None;
425    }
426
427    // The literal must already be a timestamp in the target unit and timezone; it
428    // is never converted, and at most one dictionary wrapper is unwrapped.
429    let literal = match lit_value {
430        ScalarValue::Dictionary(_, inner) => inner.as_ref(),
431        literal => literal,
432    };
433    if literal.data_type() != *target {
434        return None;
435    }
436    let (ScalarValue::TimestampSecond(literal_value, _)
437    | ScalarValue::TimestampMillisecond(literal_value, _)
438    | ScalarValue::TimestampMicrosecond(literal_value, _)
439    | ScalarValue::TimestampNanosecond(literal_value, _)) = literal
440    else {
441        return None;
442    };
443
444    let bound = |value| {
445        let scalar = timestamp_scalar(source_unit, source_tz.clone(), value);
446        match source_type {
447            DataType::Dictionary(key_type, _) => {
448                ScalarValue::Dictionary(key_type.clone(), Box::new(scalar))
449            }
450            _ => scalar,
451        }
452    };
453
454    let source_scale = i128::from(timestamp_unit_scale(source_unit));
455    let target_scale = i128::from(timestamp_unit_scale(target_unit));
456
457    let Some(literal_value) = *literal_value else {
458        // A narrowing NULL has no bucket; widening and same-unit casts keep the
459        // NULL on the source side.
460        return (source_scale <= target_scale)
461            .then(|| CastPredicatePreimage::Exact(bound(None)));
462    };
463
464    // A single source-domain half-open interval `[lower, upper)`: narrowing casts
465    // many values onto the literal, so it is the truncation bucket; a widening or
466    // same-unit cast maps the literal from one source value when it is aligned and
467    // from none otherwise.
468    let (lower, upper) = if source_scale > target_scale {
469        trunc_toward_zero_bucket(literal_value, source_scale / target_scale)?
470    } else {
471        let ratio = target_scale / source_scale;
472        let literal_value = i128::from(literal_value);
473        let floor = literal_value.div_euclid(ratio);
474        let ceil = floor + i128::from(literal_value.rem_euclid(ratio) != 0);
475        (ceil, floor + 1)
476    };
477
478    if lower == upper {
479        // No source value maps to the literal, so only ordered comparisons can
480        // move the cast, and only when both sides share the source timezone.
481        if source_tz != target_tz
482            || !matches!(
483                op,
484                Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
485            )
486        {
487            return None;
488        }
489    } else if upper == lower + 1 {
490        // Exactly one source value maps to the literal. Its exclusive upper bound
491        // can sit one past `i64::MAX`, so only `lower` is range-checked.
492        return Some(CastPredicatePreimage::Exact(bound(Some(
493            i64::try_from(lower).ok()?,
494        ))));
495    }
496
497    let (lower, upper) = (i64::try_from(lower).ok()?, i64::try_from(upper).ok()?);
498    Interval::try_new(bound(Some(lower)), bound(Some(upper)))
499        .ok()
500        .map(CastPredicatePreimage::Range)
501}
502
503/// Returns the half-open source-domain bucket `[lower, upper)` that truncates
504/// toward zero to `value` when divided by `bucket_width`.
505///
506/// Timestamp precision narrowing follows integer truncation toward zero rather
507/// than mathematical floor. For example, when `bucket_width = 1_000_000`, both
508/// `999_999` and `-999_999` truncate to `0`, while `-1_000_000` truncates to
509/// `-1`.
510///
511/// This makes the inverse bucket depend on the sign of `value`:
512///
513/// * `value > 0`: `[value * width, (value + 1) * width)`
514/// * `value == 0`: `[1 - width, width)`, spanning small negative and positive
515///   values that both truncate to zero
516/// * `value < 0`: `[(value - 1) * width + 1, value * width + 1)`
517///
518/// The arithmetic uses `checked_*` operations and returns `None` if an
519/// intermediate bound cannot be represented as `i128`.
520fn trunc_toward_zero_bucket(value: i64, bucket_width: i128) -> Option<(i128, i128)> {
521    let value = value as i128;
522    match value.cmp(&0) {
523        Ordering::Greater => {
524            let lower = value.checked_mul(bucket_width)?;
525            let upper = value.checked_add(1)?.checked_mul(bucket_width)?;
526            Some((lower, upper))
527        }
528        Ordering::Equal => Some((1_i128.checked_sub(bucket_width)?, bucket_width)),
529        Ordering::Less => {
530            let lower = value
531                .checked_sub(1)?
532                .checked_mul(bucket_width)?
533                .checked_add(1)?;
534            let upper = value.checked_mul(bucket_width)?.checked_add(1)?;
535            Some((lower, upper))
536        }
537    }
538}
539
540fn timestamp_unit_scale(unit: &TimeUnit) -> i64 {
541    match unit {
542        TimeUnit::Second => 1,
543        TimeUnit::Millisecond => MILLISECONDS,
544        TimeUnit::Microsecond => MICROSECONDS,
545        TimeUnit::Nanosecond => NANOSECONDS,
546    }
547}
548
549/// Builds a timestamp scalar in `unit` and `tz`.
550fn timestamp_scalar(
551    unit: &TimeUnit,
552    tz: Option<Arc<str>>,
553    value: Option<i64>,
554) -> ScalarValue {
555    match unit {
556        TimeUnit::Second => ScalarValue::TimestampSecond(value, tz),
557        TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(value, tz),
558        TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(value, tz),
559        TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(value, tz),
560    }
561}
562
563/// Returns true if unwrap_cast_in_comparison supports this data type
564pub fn is_supported_type(data_type: &DataType) -> bool {
565    is_supported_numeric_type(data_type)
566        || is_supported_string_type(data_type)
567        || is_supported_dictionary_type(data_type)
568        || is_supported_binary_type(data_type)
569}
570
571fn is_date_type(data_type: &DataType) -> bool {
572    matches!(data_type, DataType::Date32 | DataType::Date64)
573}
574
575/// Returns true when unwrapping a date/timestamp cast could change comparison
576/// semantics.
577///
578/// A `Date` stores only a calendar day, while a `Timestamp` stores a specific
579/// instant or wall-clock time. `Timestamp -> Date` is lossy because it drops the
580/// time-of-day. `Date -> Timestamp` is also lossy in this optimizer context
581/// because there is no unique inverse: converting a date to a timestamp has to
582/// invent a time component such as midnight.
583///
584/// For example, `CAST(ts AS DATE) = DATE '2024-01-01'` means "any timestamp
585/// during that day", but unwrapping it to `ts = TIMESTAMP '2024-01-01
586/// 00:00:00'` matches only midnight.
587///
588/// An identity cast (`from_type == to_type`, e.g. `Date32 -> Date32`) never
589/// changes comparison semantics and is therefore not lossy.
590///
591/// A cast between the two date types (`Date32` <-> `Date64`) is not pre-filtered
592/// as lossy here, because whether it loses information is a per-value question
593/// rather than a per-type one. `Date32` -> `Date64` is always exact (a day scaled
594/// to midnight in milliseconds). `Date64` -> `Date32` is exact only when the value
595/// lands on a day boundary: Arrow nominally defines `Date64` as whole days encoded
596/// in milliseconds, but arrow-rs does not enforce that (see arrow-rs#5288), so a
597/// `Date64` carrying sub-day milliseconds would lose them. This is not a licence to
598/// drop them - [`try_cast_numeric_literal`] returns `None` for a `Date64` value not
599/// divisible by 86_400_000, so an inexact `Date64` -> `Date32` fold never happens.
600fn is_lossy_temporal_cast(from_type: &DataType, to_type: &DataType) -> bool {
601    if from_type == to_type {
602        return false;
603    }
604    if is_date_type(from_type) && is_date_type(to_type) {
605        return false;
606    }
607    (is_date_type(from_type) && to_type.is_temporal())
608        || (is_date_type(to_type) && from_type.is_temporal())
609}
610
611/// Returns true when casting a date column from `from_type` to `to_type` narrows
612/// `Date64` (milliseconds) to `Date32` (days).
613///
614/// `CAST(date64 AS Date32) = lit_day` matches any millisecond within that day,
615/// but the rewritten `date64 = lit_ms` matches only midnight. Arrow does not
616/// require `Date64` values to be whole days (see arrow-rs#5288), so the column
617/// may carry sub-day values the planner cannot see; the widening direction
618/// (`Date32 -> Date64`) is injective and stays allowed.
619///
620/// This pair is already rejected by the `is_exact_cast_safe` allowlist
621/// (including when wrapped in a `Dictionary`), so predicate rewrites do not need
622/// a separate `Date64 -> Date32` early return.
623#[deprecated(
624    since = "56.0.0",
625    note = "Date64 -> Date32 is rejected by the cast_predicate_preimage allowlist"
626)]
627pub fn is_date_narrowing_cast(from_type: &DataType, to_type: &DataType) -> bool {
628    matches!((from_type, to_type), (DataType::Date64, DataType::Date32))
629}
630/// Returns true if unwrap_cast_in_comparison supports this numeric type
631fn is_supported_numeric_type(data_type: &DataType) -> bool {
632    matches!(
633        data_type,
634        DataType::UInt8
635            | DataType::UInt16
636            | DataType::UInt32
637            | DataType::UInt64
638            | DataType::Int8
639            | DataType::Int16
640            | DataType::Int32
641            | DataType::Int64
642            | DataType::Date32
643            | DataType::Date64
644            | DataType::Decimal32(_, _)
645            | DataType::Decimal64(_, _)
646            | DataType::Decimal128(_, _)
647            | DataType::Timestamp(_, _)
648    )
649}
650
651/// Returns true if unwrap_cast_in_comparison supports casting this value as a string
652fn is_supported_string_type(data_type: &DataType) -> bool {
653    matches!(
654        data_type,
655        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
656    )
657}
658
659/// Returns true if unwrap_cast_in_comparison supports casting this value as a dictionary
660fn is_supported_dictionary_type(data_type: &DataType) -> bool {
661    matches!(data_type,
662                    DataType::Dictionary(_, inner) if is_supported_type(inner))
663}
664
665fn is_supported_binary_type(data_type: &DataType) -> bool {
666    matches!(data_type, DataType::Binary | DataType::FixedSizeBinary(_))
667}
668
669/// Scale a `Date32`/`Date64` literal value into the units of `target_type`,
670/// returning `None` when the conversion is not exact.
671///
672/// `Date32` counts **days** since the Unix epoch while `Date64` counts
673/// **milliseconds** since the Unix epoch, so a cross conversion scales by
674/// [`MILLISECONDS_IN_DAY`]:
675/// * `Date32` -> `Date64` is always exact: `days * MILLISECONDS_IN_DAY`
676///   (guarded against `i64`/`i128` overflow).
677/// * `Date64` -> `Date32` is exact only when the millisecond value lands on a
678///   whole-day boundary; otherwise it returns `None` so the cast unwrap is
679///   skipped (correct for every operator, including `=`).
680///
681/// For a same-type date cast or a date/integer cast the generic `mul`
682/// multiplier already applies, so this returns `value * mul`.
683fn scale_date_literal(
684    value: i128,
685    from_type: &DataType,
686    target_type: &DataType,
687    mul: i128,
688) -> Option<i128> {
689    const MILLIS_PER_DAY: i128 = MILLISECONDS_IN_DAY as i128;
690    match (from_type, target_type) {
691        (DataType::Date32, DataType::Date64) => value.checked_mul(MILLIS_PER_DAY),
692        (DataType::Date64, DataType::Date32) => {
693            (value % MILLIS_PER_DAY == 0).then_some(value / MILLIS_PER_DAY)
694        }
695        _ => value.checked_mul(mul),
696    }
697}
698
699/// Convert a numeric value from one numeric data type to another
700fn try_cast_numeric_literal(
701    lit_value: &ScalarValue,
702    target_type: &DataType,
703) -> Option<ScalarValue> {
704    let lit_data_type = lit_value.data_type();
705    if !is_supported_numeric_type(&lit_data_type)
706        || !is_supported_numeric_type(target_type)
707    {
708        return None;
709    }
710
711    if is_lossy_temporal_cast(&lit_data_type, target_type) {
712        return None;
713    }
714
715    let mul = match target_type {
716        DataType::UInt8
717        | DataType::UInt16
718        | DataType::UInt32
719        | DataType::UInt64
720        | DataType::Int8
721        | DataType::Int16
722        | DataType::Int32
723        | DataType::Int64
724        | DataType::Date32
725        | DataType::Date64 => 1_i128,
726        DataType::Timestamp(_, _) => 1_i128,
727        DataType::Decimal32(_, scale) => 10_i128.pow(*scale as u32),
728        DataType::Decimal64(_, scale) => 10_i128.pow(*scale as u32),
729        DataType::Decimal128(_, scale) => 10_i128.pow(*scale as u32),
730        _ => return None,
731    };
732    let (target_min, target_max) = match target_type {
733        DataType::UInt8 => (u8::MIN as i128, u8::MAX as i128),
734        DataType::UInt16 => (u16::MIN as i128, u16::MAX as i128),
735        DataType::UInt32 => (u32::MIN as i128, u32::MAX as i128),
736        DataType::UInt64 => (u64::MIN as i128, u64::MAX as i128),
737        DataType::Int8 => (i8::MIN as i128, i8::MAX as i128),
738        DataType::Int16 => (i16::MIN as i128, i16::MAX as i128),
739        DataType::Int32 | DataType::Date32 => (i32::MIN as i128, i32::MAX as i128),
740        DataType::Int64 | DataType::Date64 => (i64::MIN as i128, i64::MAX as i128),
741        DataType::Timestamp(_, _) => (i64::MIN as i128, i64::MAX as i128),
742        DataType::Decimal32(precision, _) => (
743            // Different precision for decimal32 can store different range of value.
744            // For example, the precision is 3, the max of value is `999` and the min
745            // value is `-999`
746            MIN_DECIMAL32_FOR_EACH_PRECISION[*precision as usize] as i128,
747            MAX_DECIMAL32_FOR_EACH_PRECISION[*precision as usize] as i128,
748        ),
749        DataType::Decimal64(precision, _) => (
750            // Different precision for decimal64 can store different range of value.
751            // For example, the precision is 3, the max of value is `999` and the min
752            // value is `-999`
753            MIN_DECIMAL64_FOR_EACH_PRECISION[*precision as usize] as i128,
754            MAX_DECIMAL64_FOR_EACH_PRECISION[*precision as usize] as i128,
755        ),
756        DataType::Decimal128(precision, _) => (
757            // Different precision for decimal128 can store different range of value.
758            // For example, the precision is 3, the max of value is `999` and the min
759            // value is `-999`
760            MIN_DECIMAL128_FOR_EACH_PRECISION[*precision as usize],
761            MAX_DECIMAL128_FOR_EACH_PRECISION[*precision as usize],
762        ),
763        _ => return None,
764    };
765    let lit_value_target_type = match lit_value {
766        ScalarValue::Int8(Some(v)) => (*v as i128).checked_mul(mul),
767        ScalarValue::Int16(Some(v)) => (*v as i128).checked_mul(mul),
768        ScalarValue::Int32(Some(v)) => (*v as i128).checked_mul(mul),
769        ScalarValue::Int64(Some(v)) => (*v as i128).checked_mul(mul),
770        ScalarValue::UInt8(Some(v)) => (*v as i128).checked_mul(mul),
771        ScalarValue::UInt16(Some(v)) => (*v as i128).checked_mul(mul),
772        ScalarValue::UInt32(Some(v)) => (*v as i128).checked_mul(mul),
773        ScalarValue::UInt64(Some(v)) => (*v as i128).checked_mul(mul),
774        ScalarValue::Date32(Some(v)) => {
775            scale_date_literal(*v as i128, &lit_data_type, target_type, mul)
776        }
777        ScalarValue::Date64(Some(v)) => {
778            scale_date_literal(*v as i128, &lit_data_type, target_type, mul)
779        }
780        ScalarValue::TimestampSecond(Some(v), _) => (*v as i128).checked_mul(mul),
781        ScalarValue::TimestampMillisecond(Some(v), _) => (*v as i128).checked_mul(mul),
782        ScalarValue::TimestampMicrosecond(Some(v), _) => (*v as i128).checked_mul(mul),
783        ScalarValue::TimestampNanosecond(Some(v), _) => (*v as i128).checked_mul(mul),
784        ScalarValue::Decimal32(Some(v), _, scale) => {
785            let v = *v as i128;
786            let lit_scale_mul = 10_i128.pow(*scale as u32);
787            if mul >= lit_scale_mul {
788                // Example:
789                // lit is decimal(123,3,2)
790                // target type is decimal(5,3)
791                // the lit can be converted to the decimal(1230,5,3)
792                v.checked_mul(mul / lit_scale_mul)
793            } else if v % (lit_scale_mul / mul) == 0 {
794                // Example:
795                // lit is decimal(123000,10,3)
796                // target type is int32: the lit can be converted to INT32(123)
797                // target type is decimal(10,2): the lit can be converted to decimal(12300,10,2)
798                Some(v / (lit_scale_mul / mul))
799            } else {
800                // can't convert the lit decimal to the target data type
801                None
802            }
803        }
804        ScalarValue::Decimal64(Some(v), _, scale) => {
805            let v = *v as i128;
806            let lit_scale_mul = 10_i128.pow(*scale as u32);
807            if mul >= lit_scale_mul {
808                // Example:
809                // lit is decimal(123,3,2)
810                // target type is decimal(5,3)
811                // the lit can be converted to the decimal(1230,5,3)
812                v.checked_mul(mul / lit_scale_mul)
813            } else if v % (lit_scale_mul / mul) == 0 {
814                // Example:
815                // lit is decimal(123000,10,3)
816                // target type is int32: the lit can be converted to INT32(123)
817                // target type is decimal(10,2): the lit can be converted to decimal(12300,10,2)
818                Some(v / (lit_scale_mul / mul))
819            } else {
820                // can't convert the lit decimal to the target data type
821                None
822            }
823        }
824        ScalarValue::Decimal128(Some(v), _, scale) => {
825            let lit_scale_mul = 10_i128.pow(*scale as u32);
826            if mul >= lit_scale_mul {
827                // Example:
828                // lit is decimal(123,3,2)
829                // target type is decimal(5,3)
830                // the lit can be converted to the decimal(1230,5,3)
831                (*v).checked_mul(mul / lit_scale_mul)
832            } else if (*v) % (lit_scale_mul / mul) == 0 {
833                // Example:
834                // lit is decimal(123000,10,3)
835                // target type is int32: the lit can be converted to INT32(123)
836                // target type is decimal(10,2): the lit can be converted to decimal(12300,10,2)
837                Some(*v / (lit_scale_mul / mul))
838            } else {
839                // can't convert the lit decimal to the target data type
840                None
841            }
842        }
843        _ => None,
844    };
845
846    match lit_value_target_type {
847        None => None,
848        Some(value) => {
849            if value >= target_min && value <= target_max {
850                // the value casted from lit to the target type is in the range of target type.
851                // return the target type of scalar value
852                let result_scalar = match target_type {
853                    DataType::Int8 => ScalarValue::Int8(Some(value as i8)),
854                    DataType::Int16 => ScalarValue::Int16(Some(value as i16)),
855                    DataType::Int32 => ScalarValue::Int32(Some(value as i32)),
856                    DataType::Int64 => ScalarValue::Int64(Some(value as i64)),
857                    DataType::Date32 => ScalarValue::Date32(Some(value as i32)),
858                    DataType::Date64 => ScalarValue::Date64(Some(value as i64)),
859                    DataType::UInt8 => ScalarValue::UInt8(Some(value as u8)),
860                    DataType::UInt16 => ScalarValue::UInt16(Some(value as u16)),
861                    DataType::UInt32 => ScalarValue::UInt32(Some(value as u32)),
862                    DataType::UInt64 => ScalarValue::UInt64(Some(value as u64)),
863                    DataType::Timestamp(TimeUnit::Second, tz) => {
864                        let value = cast_between_timestamp(
865                            &lit_data_type,
866                            &DataType::Timestamp(TimeUnit::Second, tz.clone()),
867                            value,
868                        );
869                        ScalarValue::TimestampSecond(value, tz.clone())
870                    }
871                    DataType::Timestamp(TimeUnit::Millisecond, tz) => {
872                        let value = cast_between_timestamp(
873                            &lit_data_type,
874                            &DataType::Timestamp(TimeUnit::Millisecond, tz.clone()),
875                            value,
876                        );
877                        ScalarValue::TimestampMillisecond(value, tz.clone())
878                    }
879                    DataType::Timestamp(TimeUnit::Microsecond, tz) => {
880                        let value = cast_between_timestamp(
881                            &lit_data_type,
882                            &DataType::Timestamp(TimeUnit::Microsecond, tz.clone()),
883                            value,
884                        );
885                        ScalarValue::TimestampMicrosecond(value, tz.clone())
886                    }
887                    DataType::Timestamp(TimeUnit::Nanosecond, tz) => {
888                        let value = cast_between_timestamp(
889                            &lit_data_type,
890                            &DataType::Timestamp(TimeUnit::Nanosecond, tz.clone()),
891                            value,
892                        );
893                        ScalarValue::TimestampNanosecond(value, tz.clone())
894                    }
895                    DataType::Decimal32(p, s) => {
896                        ScalarValue::Decimal32(Some(value as i32), *p, *s)
897                    }
898                    DataType::Decimal64(p, s) => {
899                        ScalarValue::Decimal64(Some(value as i64), *p, *s)
900                    }
901                    DataType::Decimal128(p, s) => {
902                        ScalarValue::Decimal128(Some(value), *p, *s)
903                    }
904                    _ => {
905                        return None;
906                    }
907                };
908                Some(result_scalar)
909            } else {
910                None
911            }
912        }
913    }
914}
915
916fn try_cast_string_literal(
917    lit_value: &ScalarValue,
918    target_type: &DataType,
919) -> Option<ScalarValue> {
920    let string_value = lit_value.try_as_str()?.map(|s| s.to_string());
921    let scalar_value = match target_type {
922        DataType::Utf8 => ScalarValue::Utf8(string_value),
923        DataType::LargeUtf8 => ScalarValue::LargeUtf8(string_value),
924        DataType::Utf8View => ScalarValue::Utf8View(string_value),
925        _ => return None,
926    };
927    Some(scalar_value)
928}
929
930/// Attempt to cast to/from a dictionary type by wrapping/unwrapping the dictionary
931fn try_cast_dictionary(
932    lit_value: &ScalarValue,
933    target_type: &DataType,
934) -> Option<ScalarValue> {
935    let lit_value_type = lit_value.data_type();
936    let result_scalar = match (lit_value, target_type) {
937        // Unwrap dictionary when inner type matches target type
938        (ScalarValue::Dictionary(_, inner_value), _)
939            if inner_value.data_type() == *target_type =>
940        {
941            (**inner_value).clone()
942        }
943        // Wrap type when target type is dictionary
944        (_, DataType::Dictionary(index_type, inner_type))
945            if **inner_type == lit_value_type =>
946        {
947            ScalarValue::Dictionary(index_type.clone(), Box::new(lit_value.clone()))
948        }
949        _ => {
950            return None;
951        }
952    };
953    Some(result_scalar)
954}
955
956/// Cast a timestamp value from one unit to another
957fn cast_between_timestamp(from: &DataType, to: &DataType, value: i128) -> Option<i64> {
958    let value = value as i64;
959    let from_scale = match from {
960        DataType::Timestamp(unit, _) => timestamp_unit_scale(unit),
961        _ => return Some(value),
962    };
963
964    let to_scale = match to {
965        DataType::Timestamp(unit, _) => timestamp_unit_scale(unit),
966        _ => return Some(value),
967    };
968
969    match from_scale.cmp(&to_scale) {
970        Ordering::Less => value.checked_mul(to_scale / from_scale),
971        Ordering::Greater => Some(value / (from_scale / to_scale)),
972        Ordering::Equal => Some(value),
973    }
974}
975
976fn try_cast_binary(
977    lit_value: &ScalarValue,
978    target_type: &DataType,
979) -> Option<ScalarValue> {
980    match (lit_value, target_type) {
981        (ScalarValue::Binary(Some(v)), DataType::FixedSizeBinary(n))
982            if v.len() == *n as usize =>
983        {
984            Some(ScalarValue::FixedSizeBinary(*n, Some(v.clone())))
985        }
986        _ => None,
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993    use arrow::compute::{CastOptions, cast_with_options};
994    use arrow::datatypes::{Field, Fields};
995    use std::sync::Arc;
996
997    #[derive(Debug, Clone)]
998    enum ExpectedCast {
999        /// test successfully cast value and it is as specified
1000        Value(ScalarValue),
1001        /// test returned OK, but could not cast the value
1002        NoValue,
1003    }
1004
1005    /// Runs try_cast_literal_to_type with the specified inputs and
1006    /// ensure it computes the expected output, and ensures the
1007    /// casting is consistent with the Arrow kernels
1008    fn expect_cast(
1009        literal: ScalarValue,
1010        target_type: DataType,
1011        expected_result: ExpectedCast,
1012    ) {
1013        let actual_value = try_cast_literal_to_type(&literal, &target_type);
1014
1015        println!("expect_cast: ");
1016        println!("  {literal:?} --> {target_type}");
1017        println!("  expected_result: {expected_result:?}");
1018        println!("  actual_result:   {actual_value:?}");
1019
1020        match expected_result {
1021            ExpectedCast::Value(expected_value) => {
1022                let actual_value =
1023                    actual_value.expect("Expected cast value but got None");
1024
1025                assert_eq!(actual_value, expected_value);
1026
1027                // Verify that calling the arrow
1028                // cast kernel yields the same results
1029                // input array
1030                let literal_array = literal
1031                    .to_array_of_size(1)
1032                    .expect("Failed to convert to array of size");
1033                let expected_array = expected_value
1034                    .to_array_of_size(1)
1035                    .expect("Failed to convert to array of size");
1036                let cast_array = cast_with_options(
1037                    &literal_array,
1038                    &target_type,
1039                    &CastOptions::default(),
1040                )
1041                .expect("Expected to be cast array with arrow cast kernel");
1042
1043                assert_eq!(
1044                    &expected_array, &cast_array,
1045                    "Result of casting {literal:?} with arrow was\n {cast_array:#?}\nbut expected\n{expected_array:#?}"
1046                );
1047
1048                // Verify that for timestamp types the timezones are the same
1049                // (ScalarValue::cmp doesn't account for timezones);
1050                if let (
1051                    DataType::Timestamp(left_unit, left_tz),
1052                    DataType::Timestamp(right_unit, right_tz),
1053                ) = (actual_value.data_type(), expected_value.data_type())
1054                {
1055                    assert_eq!(left_unit, right_unit);
1056                    assert_eq!(left_tz, right_tz);
1057                }
1058            }
1059            ExpectedCast::NoValue => {
1060                assert!(
1061                    actual_value.is_none(),
1062                    "Expected no cast value, but got {actual_value:?}"
1063                );
1064            }
1065        }
1066    }
1067
1068    #[test]
1069    fn test_try_cast_to_type_nulls() {
1070        // test that nulls can be cast to/from all integer types
1071        let scalars = vec![
1072            ScalarValue::Int8(None),
1073            ScalarValue::Int16(None),
1074            ScalarValue::Int32(None),
1075            ScalarValue::Int64(None),
1076            ScalarValue::UInt8(None),
1077            ScalarValue::UInt16(None),
1078            ScalarValue::UInt32(None),
1079            ScalarValue::UInt64(None),
1080            ScalarValue::Decimal128(None, 3, 0),
1081            ScalarValue::Decimal128(None, 8, 2),
1082            ScalarValue::Utf8(None),
1083            ScalarValue::LargeUtf8(None),
1084        ];
1085
1086        for s1 in &scalars {
1087            for s2 in &scalars {
1088                let expected_value = ExpectedCast::Value(s2.clone());
1089
1090                expect_cast(s1.clone(), s2.data_type(), expected_value);
1091            }
1092        }
1093    }
1094
1095    #[test]
1096    fn test_try_cast_to_type_int_in_range() {
1097        // test values that can be cast to/from all integer types
1098        let scalars = vec![
1099            ScalarValue::Int8(Some(123)),
1100            ScalarValue::Int16(Some(123)),
1101            ScalarValue::Int32(Some(123)),
1102            ScalarValue::Int64(Some(123)),
1103            ScalarValue::UInt8(Some(123)),
1104            ScalarValue::UInt16(Some(123)),
1105            ScalarValue::UInt32(Some(123)),
1106            ScalarValue::UInt64(Some(123)),
1107            ScalarValue::Decimal128(Some(123), 3, 0),
1108            ScalarValue::Decimal128(Some(12300), 8, 2),
1109        ];
1110
1111        for s1 in &scalars {
1112            for s2 in &scalars {
1113                let expected_value = ExpectedCast::Value(s2.clone());
1114
1115                expect_cast(s1.clone(), s2.data_type(), expected_value);
1116            }
1117        }
1118
1119        let max_i32 = ScalarValue::Int32(Some(i32::MAX));
1120        expect_cast(
1121            max_i32,
1122            DataType::UInt64,
1123            ExpectedCast::Value(ScalarValue::UInt64(Some(i32::MAX as u64))),
1124        );
1125
1126        let min_i32 = ScalarValue::Int32(Some(i32::MIN));
1127        expect_cast(
1128            min_i32,
1129            DataType::Int64,
1130            ExpectedCast::Value(ScalarValue::Int64(Some(i32::MIN as i64))),
1131        );
1132
1133        let max_i64 = ScalarValue::Int64(Some(i64::MAX));
1134        expect_cast(
1135            max_i64,
1136            DataType::UInt64,
1137            ExpectedCast::Value(ScalarValue::UInt64(Some(i64::MAX as u64))),
1138        );
1139    }
1140
1141    #[test]
1142    fn test_try_cast_to_type_int_out_of_range() {
1143        let min_i32 = ScalarValue::Int32(Some(i32::MIN));
1144        let min_i64 = ScalarValue::Int64(Some(i64::MIN));
1145        let max_i64 = ScalarValue::Int64(Some(i64::MAX));
1146        let max_u64 = ScalarValue::UInt64(Some(u64::MAX));
1147
1148        expect_cast(max_i64.clone(), DataType::Int8, ExpectedCast::NoValue);
1149
1150        expect_cast(max_i64.clone(), DataType::Int16, ExpectedCast::NoValue);
1151
1152        expect_cast(max_i64, DataType::Int32, ExpectedCast::NoValue);
1153
1154        expect_cast(max_u64, DataType::Int64, ExpectedCast::NoValue);
1155
1156        expect_cast(min_i64, DataType::UInt64, ExpectedCast::NoValue);
1157
1158        expect_cast(min_i32, DataType::UInt64, ExpectedCast::NoValue);
1159
1160        // decimal out of range
1161        expect_cast(
1162            ScalarValue::Decimal128(Some(99999999999999999999999999999999999900), 38, 0),
1163            DataType::Int64,
1164            ExpectedCast::NoValue,
1165        );
1166
1167        expect_cast(
1168            ScalarValue::Decimal128(Some(-9999999999999999999999999999999999), 37, 1),
1169            DataType::Int64,
1170            ExpectedCast::NoValue,
1171        );
1172    }
1173
1174    #[test]
1175    fn test_try_decimal_cast_in_range() {
1176        expect_cast(
1177            ScalarValue::Decimal128(Some(12300), 5, 2),
1178            DataType::Decimal128(3, 0),
1179            ExpectedCast::Value(ScalarValue::Decimal128(Some(123), 3, 0)),
1180        );
1181
1182        expect_cast(
1183            ScalarValue::Decimal128(Some(12300), 5, 2),
1184            DataType::Decimal128(8, 0),
1185            ExpectedCast::Value(ScalarValue::Decimal128(Some(123), 8, 0)),
1186        );
1187
1188        expect_cast(
1189            ScalarValue::Decimal128(Some(12300), 5, 2),
1190            DataType::Decimal128(8, 5),
1191            ExpectedCast::Value(ScalarValue::Decimal128(Some(12300000), 8, 5)),
1192        );
1193    }
1194
1195    #[test]
1196    fn test_try_decimal_cast_out_of_range() {
1197        // decimal would lose precision
1198        expect_cast(
1199            ScalarValue::Decimal128(Some(12345), 5, 2),
1200            DataType::Decimal128(3, 0),
1201            ExpectedCast::NoValue,
1202        );
1203
1204        // decimal would lose precision
1205        expect_cast(
1206            ScalarValue::Decimal128(Some(12300), 5, 2),
1207            DataType::Decimal128(2, 0),
1208            ExpectedCast::NoValue,
1209        );
1210    }
1211
1212    #[test]
1213    fn test_try_cast_to_type_timestamps() {
1214        for time_unit in [
1215            TimeUnit::Second,
1216            TimeUnit::Millisecond,
1217            TimeUnit::Microsecond,
1218            TimeUnit::Nanosecond,
1219        ] {
1220            let utc = Some("+00:00".into());
1221            // No timezone, utc timezone
1222            let (lit_tz_none, lit_tz_utc) = match time_unit {
1223                TimeUnit::Second => (
1224                    ScalarValue::TimestampSecond(Some(12345), None),
1225                    ScalarValue::TimestampSecond(Some(12345), utc),
1226                ),
1227
1228                TimeUnit::Millisecond => (
1229                    ScalarValue::TimestampMillisecond(Some(12345), None),
1230                    ScalarValue::TimestampMillisecond(Some(12345), utc),
1231                ),
1232
1233                TimeUnit::Microsecond => (
1234                    ScalarValue::TimestampMicrosecond(Some(12345), None),
1235                    ScalarValue::TimestampMicrosecond(Some(12345), utc),
1236                ),
1237
1238                TimeUnit::Nanosecond => (
1239                    ScalarValue::TimestampNanosecond(Some(12345), None),
1240                    ScalarValue::TimestampNanosecond(Some(12345), utc),
1241                ),
1242            };
1243
1244            // DataFusion ignores timezones for comparisons of ScalarValue
1245            // so double check it here
1246            assert_eq!(lit_tz_none, lit_tz_utc);
1247
1248            // e.g. DataType::Timestamp(_, None)
1249            let dt_tz_none = lit_tz_none.data_type();
1250
1251            // e.g. DataType::Timestamp(_, Some(utc))
1252            let dt_tz_utc = lit_tz_utc.data_type();
1253
1254            // None <--> None
1255            expect_cast(
1256                lit_tz_none.clone(),
1257                dt_tz_none.clone(),
1258                ExpectedCast::Value(lit_tz_none.clone()),
1259            );
1260
1261            // None <--> Utc
1262            expect_cast(
1263                lit_tz_none.clone(),
1264                dt_tz_utc.clone(),
1265                ExpectedCast::Value(lit_tz_utc.clone()),
1266            );
1267
1268            // Utc <--> None
1269            expect_cast(
1270                lit_tz_utc.clone(),
1271                dt_tz_none.clone(),
1272                ExpectedCast::Value(lit_tz_none.clone()),
1273            );
1274
1275            // Utc <--> Utc
1276            expect_cast(
1277                lit_tz_utc.clone(),
1278                dt_tz_utc.clone(),
1279                ExpectedCast::Value(lit_tz_utc.clone()),
1280            );
1281
1282            // timestamp to int64
1283            expect_cast(
1284                lit_tz_utc.clone(),
1285                DataType::Int64,
1286                ExpectedCast::Value(ScalarValue::Int64(Some(12345))),
1287            );
1288
1289            // int64 to timestamp
1290            expect_cast(
1291                ScalarValue::Int64(Some(12345)),
1292                dt_tz_none.clone(),
1293                ExpectedCast::Value(lit_tz_none.clone()),
1294            );
1295
1296            // int64 to timestamp
1297            expect_cast(
1298                ScalarValue::Int64(Some(12345)),
1299                dt_tz_utc.clone(),
1300                ExpectedCast::Value(lit_tz_utc.clone()),
1301            );
1302
1303            // timestamp to string (not supported yet)
1304            expect_cast(
1305                lit_tz_utc.clone(),
1306                DataType::LargeUtf8,
1307                ExpectedCast::NoValue,
1308            );
1309        }
1310    }
1311
1312    #[test]
1313    fn test_try_cast_to_type_date_timestamp_lossy_not_allowed() {
1314        expect_cast(
1315            ScalarValue::Date32(Some(1)),
1316            DataType::Timestamp(TimeUnit::Second, None),
1317            ExpectedCast::NoValue,
1318        );
1319
1320        expect_cast(
1321            ScalarValue::Date64(Some(86_400_000)),
1322            DataType::Timestamp(TimeUnit::Millisecond, None),
1323            ExpectedCast::NoValue,
1324        );
1325
1326        expect_cast(
1327            ScalarValue::TimestampSecond(Some(86_400), None),
1328            DataType::Date32,
1329            ExpectedCast::NoValue,
1330        );
1331
1332        expect_cast(
1333            ScalarValue::TimestampMillisecond(Some(86_400_000), None),
1334            DataType::Date64,
1335            ExpectedCast::NoValue,
1336        );
1337    }
1338
1339    #[test]
1340    fn test_try_cast_identity_date_allowed() {
1341        // An identity Date cast (e.g. `CAST(date_col AS DATE)` where the column
1342        // is already Date32) must fold: it never changes comparison semantics,
1343        // so `try_cast_literal_to_type` should return the same value rather than
1344        // treating it as a lossy temporal cast.
1345        expect_cast(
1346            ScalarValue::Date32(Some(19_723)),
1347            DataType::Date32,
1348            ExpectedCast::Value(ScalarValue::Date32(Some(19_723))),
1349        );
1350
1351        expect_cast(
1352            ScalarValue::Date64(Some(1_704_067_200_000)),
1353            DataType::Date64,
1354            ExpectedCast::Value(ScalarValue::Date64(Some(1_704_067_200_000))),
1355        );
1356
1357        // is_lossy_temporal_cast must classify an identity cast as non-lossy.
1358        assert!(!is_lossy_temporal_cast(
1359            &DataType::Date32,
1360            &DataType::Date32
1361        ));
1362        assert!(!is_lossy_temporal_cast(
1363            &DataType::Date64,
1364            &DataType::Date64
1365        ));
1366    }
1367
1368    #[test]
1369    fn test_try_cast_between_date32_and_date64() {
1370        // 2025-01-01 is day 20089 since the Unix epoch, which is
1371        // 20089 * 86_400_000 = 1_735_689_600_000 milliseconds.
1372        const DAY_2025_01_01: i32 = 20089;
1373        const MS_2025_01_01: i64 = 1_735_689_600_000;
1374        assert_eq!(DAY_2025_01_01 as i64 * MILLISECONDS_IN_DAY, MS_2025_01_01);
1375
1376        // Date32 -> Date64 is always exact (days scaled up to milliseconds).
1377        expect_cast(
1378            ScalarValue::Date32(Some(DAY_2025_01_01)),
1379            DataType::Date64,
1380            ExpectedCast::Value(ScalarValue::Date64(Some(MS_2025_01_01))),
1381        );
1382
1383        // Date64 -> Date32 is exact only on a whole-day boundary.
1384        expect_cast(
1385            ScalarValue::Date64(Some(MS_2025_01_01)),
1386            DataType::Date32,
1387            ExpectedCast::Value(ScalarValue::Date32(Some(DAY_2025_01_01))),
1388        );
1389
1390        // A Date64 value that is not on a day boundary cannot be represented as
1391        // a Date32 exactly, so no rewrite is produced.
1392        expect_cast(
1393            ScalarValue::Date64(Some(MS_2025_01_01 + 1)),
1394            DataType::Date32,
1395            ExpectedCast::NoValue,
1396        );
1397        expect_cast(
1398            ScalarValue::Date64(Some(MS_2025_01_01 - 1)),
1399            DataType::Date32,
1400            ExpectedCast::NoValue,
1401        );
1402
1403        // The epoch and negative (pre-epoch) days round-trip exactly.
1404        expect_cast(
1405            ScalarValue::Date32(Some(0)),
1406            DataType::Date64,
1407            ExpectedCast::Value(ScalarValue::Date64(Some(0))),
1408        );
1409        expect_cast(
1410            ScalarValue::Date32(Some(-1)),
1411            DataType::Date64,
1412            ExpectedCast::Value(ScalarValue::Date64(Some(-MILLISECONDS_IN_DAY))),
1413        );
1414        expect_cast(
1415            ScalarValue::Date64(Some(-MILLISECONDS_IN_DAY)),
1416            DataType::Date32,
1417            ExpectedCast::Value(ScalarValue::Date32(Some(-1))),
1418        );
1419
1420        // Same-type date casts remain identity conversions.
1421        expect_cast(
1422            ScalarValue::Date32(Some(DAY_2025_01_01)),
1423            DataType::Date32,
1424            ExpectedCast::Value(ScalarValue::Date32(Some(DAY_2025_01_01))),
1425        );
1426        expect_cast(
1427            ScalarValue::Date64(Some(MS_2025_01_01)),
1428            DataType::Date64,
1429            ExpectedCast::Value(ScalarValue::Date64(Some(MS_2025_01_01))),
1430        );
1431    }
1432
1433    #[test]
1434    fn test_is_lossy_temporal_cast_date_pairs() {
1435        // Date <-> Date is let through the pre-filter (per-value exactness is
1436        // enforced downstream in try_cast_numeric_literal, not here).
1437        assert!(!is_lossy_temporal_cast(
1438            &DataType::Date32,
1439            &DataType::Date64
1440        ));
1441        assert!(!is_lossy_temporal_cast(
1442            &DataType::Date64,
1443            &DataType::Date32
1444        ));
1445        // Identity is not lossy.
1446        assert!(!is_lossy_temporal_cast(
1447            &DataType::Date32,
1448            &DataType::Date32
1449        ));
1450        // Date <-> Timestamp remains lossy.
1451        let ts = DataType::Timestamp(TimeUnit::Millisecond, None);
1452        assert!(is_lossy_temporal_cast(&DataType::Date32, &ts));
1453        assert!(is_lossy_temporal_cast(&ts, &DataType::Date32));
1454    }
1455
1456    #[test]
1457    fn test_timestamp_precision_narrowing_cast() {
1458        let ts_ns = DataType::Timestamp(TimeUnit::Nanosecond, None);
1459        let ts_us = DataType::Timestamp(TimeUnit::Microsecond, None);
1460        let ts_ms = DataType::Timestamp(TimeUnit::Millisecond, None);
1461        let ts_s = DataType::Timestamp(TimeUnit::Second, None);
1462
1463        assert!(is_timestamp_precision_narrowing_cast(&ts_ns, &ts_ms));
1464        assert!(is_timestamp_precision_narrowing_cast(&ts_us, &ts_s));
1465        assert!(!is_timestamp_precision_narrowing_cast(&ts_ms, &ts_ns));
1466        assert!(!is_timestamp_precision_narrowing_cast(&ts_ms, &ts_ms));
1467        assert!(!is_timestamp_precision_narrowing_cast(
1468            &DataType::Int64,
1469            &ts_ms
1470        ));
1471    }
1472
1473    #[test]
1474    fn test_cast_predicate_preimage_duplicates_input() {
1475        let exact = CastPredicatePreimage::Exact(ScalarValue::Int32(Some(1)));
1476        let range = CastPredicatePreimage::Range(
1477            Interval::try_new(ScalarValue::Int32(Some(0)), ScalarValue::Int32(Some(2)))
1478                .unwrap(),
1479        );
1480        let cases = [
1481            (Operator::Eq, true),
1482            (Operator::NotEq, true),
1483            (Operator::IsDistinctFrom, true),
1484            (Operator::IsNotDistinctFrom, true),
1485            (Operator::Lt, false),
1486            (Operator::LtEq, false),
1487            (Operator::Gt, false),
1488            (Operator::GtEq, false),
1489        ];
1490
1491        for (op, range_duplicates) in cases {
1492            assert!(!exact.duplicates_input(op), "Exact with {op:?}");
1493            assert_eq!(
1494                range.duplicates_input(op),
1495                range_duplicates,
1496                "Range with {op:?}"
1497            );
1498        }
1499    }
1500
1501    #[test]
1502    #[expect(
1503        deprecated,
1504        reason = "kept to verify the deprecated helper's semantics"
1505    )]
1506    fn test_is_date_narrowing_cast() {
1507        // Only Date64 -> Date32 narrows (ms -> days, many-to-one).
1508        assert!(is_date_narrowing_cast(&DataType::Date64, &DataType::Date32));
1509        // The widening direction is injective and must not be flagged.
1510        assert!(!is_date_narrowing_cast(
1511            &DataType::Date32,
1512            &DataType::Date64
1513        ));
1514        // Identity and non-date pairs are not date-narrowing casts.
1515        assert!(!is_date_narrowing_cast(
1516            &DataType::Date32,
1517            &DataType::Date32
1518        ));
1519        assert!(!is_date_narrowing_cast(
1520            &DataType::Date64,
1521            &DataType::Date64
1522        ));
1523        assert!(!is_date_narrowing_cast(&DataType::Int64, &DataType::Date32));
1524    }
1525
1526    #[test]
1527    fn test_scale_date_literal_exactness_and_overflow() {
1528        const MS_PER_DAY: i128 = MILLISECONDS_IN_DAY as i128;
1529
1530        // Date32 -> Date64 is always exact: days scaled to midnight milliseconds.
1531        // 2025-01-01 is day 20089 = 1_735_689_600_000 ms.
1532        assert_eq!(
1533            scale_date_literal(20089, &DataType::Date32, &DataType::Date64, 1),
1534            Some(1_735_689_600_000)
1535        );
1536        assert_eq!(
1537            scale_date_literal(0, &DataType::Date32, &DataType::Date64, 1),
1538            Some(0)
1539        );
1540        // Negative (pre-epoch) whole day: 1969-12-31 is day -1 = -86_400_000 ms.
1541        assert_eq!(
1542            scale_date_literal(-1, &DataType::Date32, &DataType::Date64, 1),
1543            Some(-86_400_000)
1544        );
1545
1546        // Date64 -> Date32 is exact only on a whole-day boundary.
1547        assert_eq!(
1548            scale_date_literal(
1549                1_735_689_600_000,
1550                &DataType::Date64,
1551                &DataType::Date32,
1552                1
1553            ),
1554            Some(20089)
1555        );
1556        assert_eq!(
1557            scale_date_literal(-86_400_000, &DataType::Date64, &DataType::Date32, 1),
1558            Some(-1)
1559        );
1560        // Sub-day values are not exactly representable as a Date32, in both the
1561        // positive and the pre-epoch negative direction -> None (no fold).
1562        assert_eq!(
1563            scale_date_literal(
1564                1_735_732_800_000,
1565                &DataType::Date64,
1566                &DataType::Date32,
1567                1
1568            ),
1569            None
1570        );
1571        assert_eq!(
1572            scale_date_literal(-43_200_000, &DataType::Date64, &DataType::Date32, 1),
1573            None
1574        );
1575
1576        // Extremes: a Date32 at i32::MIN / i32::MAX widens with checked i128
1577        // arithmetic, producing the exact millisecond value without overflow or
1578        // panic.
1579        assert_eq!(
1580            scale_date_literal(i32::MAX as i128, &DataType::Date32, &DataType::Date64, 1),
1581            Some(i32::MAX as i128 * MS_PER_DAY)
1582        );
1583        assert_eq!(
1584            scale_date_literal(i32::MIN as i128, &DataType::Date32, &DataType::Date64, 1),
1585            Some(i32::MIN as i128 * MS_PER_DAY)
1586        );
1587    }
1588
1589    #[test]
1590    fn test_try_cast_to_type_unsupported() {
1591        // int64 to list
1592        expect_cast(
1593            ScalarValue::Int64(Some(12345)),
1594            DataType::List(Arc::new(Field::new("f", DataType::Int32, true))),
1595            ExpectedCast::NoValue,
1596        );
1597    }
1598
1599    #[test]
1600    fn test_try_cast_literal_to_timestamp() {
1601        // same timestamp
1602        let new_scalar = try_cast_literal_to_type(
1603            &ScalarValue::TimestampNanosecond(Some(123456), None),
1604            &DataType::Timestamp(TimeUnit::Nanosecond, None),
1605        )
1606        .unwrap();
1607
1608        assert_eq!(
1609            new_scalar,
1610            ScalarValue::TimestampNanosecond(Some(123456), None)
1611        );
1612
1613        // TimestampNanosecond to TimestampMicrosecond
1614        let new_scalar = try_cast_literal_to_type(
1615            &ScalarValue::TimestampNanosecond(Some(123456), None),
1616            &DataType::Timestamp(TimeUnit::Microsecond, None),
1617        )
1618        .unwrap();
1619
1620        assert_eq!(
1621            new_scalar,
1622            ScalarValue::TimestampMicrosecond(Some(123), None)
1623        );
1624
1625        // TimestampNanosecond to TimestampMillisecond
1626        let new_scalar = try_cast_literal_to_type(
1627            &ScalarValue::TimestampNanosecond(Some(123456), None),
1628            &DataType::Timestamp(TimeUnit::Millisecond, None),
1629        )
1630        .unwrap();
1631
1632        assert_eq!(new_scalar, ScalarValue::TimestampMillisecond(Some(0), None));
1633
1634        // TimestampNanosecond to TimestampSecond
1635        let new_scalar = try_cast_literal_to_type(
1636            &ScalarValue::TimestampNanosecond(Some(123456), None),
1637            &DataType::Timestamp(TimeUnit::Second, None),
1638        )
1639        .unwrap();
1640
1641        assert_eq!(new_scalar, ScalarValue::TimestampSecond(Some(0), None));
1642
1643        // TimestampMicrosecond to TimestampNanosecond
1644        let new_scalar = try_cast_literal_to_type(
1645            &ScalarValue::TimestampMicrosecond(Some(123), None),
1646            &DataType::Timestamp(TimeUnit::Nanosecond, None),
1647        )
1648        .unwrap();
1649
1650        assert_eq!(
1651            new_scalar,
1652            ScalarValue::TimestampNanosecond(Some(123000), None)
1653        );
1654
1655        // TimestampMicrosecond to TimestampMillisecond
1656        let new_scalar = try_cast_literal_to_type(
1657            &ScalarValue::TimestampMicrosecond(Some(123), None),
1658            &DataType::Timestamp(TimeUnit::Millisecond, None),
1659        )
1660        .unwrap();
1661
1662        assert_eq!(new_scalar, ScalarValue::TimestampMillisecond(Some(0), None));
1663
1664        // TimestampMicrosecond to TimestampSecond
1665        let new_scalar = try_cast_literal_to_type(
1666            &ScalarValue::TimestampMicrosecond(Some(123456789), None),
1667            &DataType::Timestamp(TimeUnit::Second, None),
1668        )
1669        .unwrap();
1670        assert_eq!(new_scalar, ScalarValue::TimestampSecond(Some(123), None));
1671
1672        // TimestampMillisecond to TimestampNanosecond
1673        let new_scalar = try_cast_literal_to_type(
1674            &ScalarValue::TimestampMillisecond(Some(123), None),
1675            &DataType::Timestamp(TimeUnit::Nanosecond, None),
1676        )
1677        .unwrap();
1678        assert_eq!(
1679            new_scalar,
1680            ScalarValue::TimestampNanosecond(Some(123000000), None)
1681        );
1682
1683        // TimestampMillisecond to TimestampMicrosecond
1684        let new_scalar = try_cast_literal_to_type(
1685            &ScalarValue::TimestampMillisecond(Some(123), None),
1686            &DataType::Timestamp(TimeUnit::Microsecond, None),
1687        )
1688        .unwrap();
1689        assert_eq!(
1690            new_scalar,
1691            ScalarValue::TimestampMicrosecond(Some(123000), None)
1692        );
1693        // TimestampMillisecond to TimestampSecond
1694        let new_scalar = try_cast_literal_to_type(
1695            &ScalarValue::TimestampMillisecond(Some(123456789), None),
1696            &DataType::Timestamp(TimeUnit::Second, None),
1697        )
1698        .unwrap();
1699        assert_eq!(new_scalar, ScalarValue::TimestampSecond(Some(123456), None));
1700
1701        // TimestampSecond to TimestampNanosecond
1702        let new_scalar = try_cast_literal_to_type(
1703            &ScalarValue::TimestampSecond(Some(123), None),
1704            &DataType::Timestamp(TimeUnit::Nanosecond, None),
1705        )
1706        .unwrap();
1707        assert_eq!(
1708            new_scalar,
1709            ScalarValue::TimestampNanosecond(Some(123000000000), None)
1710        );
1711
1712        // TimestampSecond to TimestampMicrosecond
1713        let new_scalar = try_cast_literal_to_type(
1714            &ScalarValue::TimestampSecond(Some(123), None),
1715            &DataType::Timestamp(TimeUnit::Microsecond, None),
1716        )
1717        .unwrap();
1718        assert_eq!(
1719            new_scalar,
1720            ScalarValue::TimestampMicrosecond(Some(123000000), None)
1721        );
1722
1723        // TimestampSecond to TimestampMillisecond
1724        let new_scalar = try_cast_literal_to_type(
1725            &ScalarValue::TimestampSecond(Some(123), None),
1726            &DataType::Timestamp(TimeUnit::Millisecond, None),
1727        )
1728        .unwrap();
1729        assert_eq!(
1730            new_scalar,
1731            ScalarValue::TimestampMillisecond(Some(123000), None)
1732        );
1733
1734        // overflow
1735        let new_scalar = try_cast_literal_to_type(
1736            &ScalarValue::TimestampSecond(Some(i64::MAX), None),
1737            &DataType::Timestamp(TimeUnit::Millisecond, None),
1738        )
1739        .unwrap();
1740        assert_eq!(new_scalar, ScalarValue::TimestampMillisecond(None, None));
1741    }
1742
1743    #[test]
1744    fn test_cast_predicate_preimage_exact() {
1745        assert_preimage_exact(
1746            &DataType::Int32,
1747            &DataType::Int64,
1748            Operator::Gt,
1749            &ScalarValue::Int64(Some(10)),
1750            ScalarValue::Int32(Some(10)),
1751        );
1752
1753        assert_preimage_exact(
1754            &DataType::Int32,
1755            &DataType::Utf8,
1756            Operator::Eq,
1757            &ScalarValue::Utf8(Some("123".to_string())),
1758            ScalarValue::Int32(Some(123)),
1759        );
1760
1761        assert_preimage_none(
1762            &DataType::Int32,
1763            &DataType::Utf8,
1764            Operator::Eq,
1765            &ScalarValue::Utf8(Some("0123".to_string())),
1766        );
1767    }
1768
1769    #[test]
1770    fn test_cast_predicate_preimage_timestamp_narrowing_range() {
1771        // Truncation toward zero decides the bucket by sign: positive, zero spans
1772        // both sides, and negative buckets shift by one.
1773        for (source_unit, target_unit, lit, lower, upper) in [
1774            (
1775                TimeUnit::Nanosecond,
1776                TimeUnit::Millisecond,
1777                1000,
1778                1_000_000_000,
1779                1_001_000_000,
1780            ),
1781            (
1782                TimeUnit::Nanosecond,
1783                TimeUnit::Millisecond,
1784                0,
1785                -999_999,
1786                1_000_000,
1787            ),
1788            (
1789                TimeUnit::Nanosecond,
1790                TimeUnit::Millisecond,
1791                -1,
1792                -1_999_999,
1793                -999_999,
1794            ),
1795            (
1796                TimeUnit::Microsecond,
1797                TimeUnit::Second,
1798                1,
1799                1_000_000,
1800                2_000_000,
1801            ),
1802            (
1803                TimeUnit::Nanosecond,
1804                TimeUnit::Second,
1805                -2,
1806                -2_999_999_999,
1807                -1_999_999_999,
1808            ),
1809            (TimeUnit::Nanosecond, TimeUnit::Microsecond, 0, -999, 1_000),
1810            (TimeUnit::Millisecond, TimeUnit::Second, 1, 1000, 2000),
1811            (TimeUnit::Millisecond, TimeUnit::Second, -1, -1999, -999),
1812            (TimeUnit::Microsecond, TimeUnit::Millisecond, 0, -999, 1000),
1813        ] {
1814            assert_timestamp_narrowing_range(source_unit, target_unit, lit, lower, upper);
1815        }
1816    }
1817
1818    #[test]
1819    fn test_timestamp_narrowing_range_rejects_naive_to_timezone() {
1820        let source = DataType::Timestamp(TimeUnit::Nanosecond, None);
1821        let target = DataType::Timestamp(TimeUnit::Millisecond, Some("+01:00".into()));
1822        let literal = ScalarValue::TimestampMillisecond(Some(0), Some("+01:00".into()));
1823        assert_preimage_none(&source, &target, Operator::Eq, &literal);
1824    }
1825
1826    #[test]
1827    fn test_naive_to_timezone_timestamp_rejected() {
1828        // Same unit, widening and narrowing targets: Arrow adjusts naive
1829        // values to UTC, which the precision arithmetic does not model. The
1830        // literal is unit-aligned (0), so the rejection comes from the timezone
1831        // adjustment and not from an unaligned widening bound.
1832        for (source_unit, target_unit) in [
1833            (TimeUnit::Nanosecond, TimeUnit::Nanosecond),
1834            (TimeUnit::Millisecond, TimeUnit::Nanosecond),
1835            (TimeUnit::Nanosecond, TimeUnit::Millisecond),
1836        ] {
1837            let source = DataType::Timestamp(source_unit, None);
1838            let target = DataType::Timestamp(target_unit, Some("+07:00".into()));
1839            let literal = timestamp_scalar(&target_unit, Some("+07:00".into()), Some(0));
1840
1841            assert!(
1842                exact_preimage_cast(&source, &target, &literal).is_none(),
1843                "{source:?} -> {target:?} must not have an exact preimage"
1844            );
1845            for op in [
1846                Operator::Eq,
1847                Operator::Gt,
1848                Operator::LtEq,
1849                Operator::IsDistinctFrom,
1850            ] {
1851                assert_preimage_none(&source, &target, op, &literal);
1852            }
1853        }
1854
1855        // Conservative for every timezone, including fixed zero offsets:
1856        // `Some("UTC")` is rejected like `Some("+07:00")`.
1857        let source = DataType::Timestamp(TimeUnit::Nanosecond, None);
1858        for tz in ["UTC", "+00:00"] {
1859            let target = DataType::Timestamp(TimeUnit::Nanosecond, Some(tz.into()));
1860            assert_preimage_none(
1861                &source,
1862                &target,
1863                Operator::Eq,
1864                &ScalarValue::TimestampNanosecond(Some(0), Some(tz.into())),
1865            );
1866        }
1867
1868        // Positive control: a timezone-aware source keeps the accepted same-unit
1869        // and widening policies.
1870        let aware_ms = DataType::Timestamp(TimeUnit::Millisecond, Some("+07:00".into()));
1871        let aware_ns = DataType::Timestamp(TimeUnit::Nanosecond, Some("+07:00".into()));
1872        assert_preimage_exact(
1873            &aware_ns,
1874            &aware_ns,
1875            Operator::Eq,
1876            &ScalarValue::TimestampNanosecond(Some(7), Some("+07:00".into())),
1877            ScalarValue::TimestampNanosecond(Some(7), Some("+07:00".into())),
1878        );
1879        assert_preimage_exact(
1880            &aware_ms,
1881            &aware_ns,
1882            Operator::Eq,
1883            &ScalarValue::TimestampNanosecond(Some(7_000_000), Some("+07:00".into())),
1884            ScalarValue::TimestampMillisecond(Some(7), Some("+07:00".into())),
1885        );
1886    }
1887
1888    #[test]
1889    fn test_naive_to_timezone_dictionary_wrapped_rejected() {
1890        let dict = |inner: DataType| {
1891            DataType::Dictionary(Box::new(DataType::Int32), Box::new(inner))
1892        };
1893        let naive_ns = DataType::Timestamp(TimeUnit::Nanosecond, None);
1894        let aware_ns = DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into()));
1895        let literal = ScalarValue::TimestampNanosecond(Some(0), Some("UTC".into()));
1896
1897        // Timestamp preimages unwrap one level of dictionary, so a wrapped
1898        // naive -> aware pair is rejected like the bare pair.
1899        assert_preimage_none(&naive_ns, &aware_ns, Operator::Eq, &literal);
1900        assert_preimage_none(
1901            &dict(naive_ns.clone()),
1902            &dict(aware_ns.clone()),
1903            Operator::Eq,
1904            &literal,
1905        );
1906        assert_preimage_none(&dict(naive_ns.clone()), &aware_ns, Operator::Eq, &literal);
1907        assert_preimage_none(&naive_ns, &dict(aware_ns.clone()), Operator::Eq, &literal);
1908
1909        // Safe controls stay allowed: aware -> aware unit widening and identity.
1910        assert_preimage_exact(
1911            &DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into())),
1912            &DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
1913            Operator::Eq,
1914            &ScalarValue::TimestampNanosecond(Some(1_000_000), Some("UTC".into())),
1915            ScalarValue::TimestampMillisecond(Some(1), Some("UTC".into())),
1916        );
1917        assert_preimage_exact(
1918            &aware_ns,
1919            &aware_ns,
1920            Operator::Eq,
1921            &literal,
1922            ScalarValue::TimestampNanosecond(Some(0), Some("UTC".into())),
1923        );
1924    }
1925
1926    #[test]
1927    fn test_cast_predicate_preimage_timestamp_widening_ordered() {
1928        let ts_ms = DataType::Timestamp(TimeUnit::Millisecond, None);
1929        let ts_ns = DataType::Timestamp(TimeUnit::Nanosecond, None);
1930
1931        assert_preimage_exact(
1932            &ts_ms,
1933            &ts_ns,
1934            Operator::Eq,
1935            &ScalarValue::TimestampNanosecond(Some(123_000_000), None),
1936            ScalarValue::TimestampMillisecond(Some(123), None),
1937        );
1938
1939        for (source_unit, target_unit) in [
1940            (TimeUnit::Second, TimeUnit::Millisecond),
1941            (TimeUnit::Second, TimeUnit::Microsecond),
1942            (TimeUnit::Second, TimeUnit::Nanosecond),
1943            (TimeUnit::Millisecond, TimeUnit::Microsecond),
1944            (TimeUnit::Millisecond, TimeUnit::Nanosecond),
1945            (TimeUnit::Microsecond, TimeUnit::Nanosecond),
1946        ] {
1947            assert_timestamp_widening_ordered(source_unit, target_unit);
1948        }
1949
1950        assert_preimage_none(
1951            &ts_ms,
1952            &ts_ns,
1953            Operator::Eq,
1954            &ScalarValue::TimestampNanosecond(Some(123_456_789), None),
1955        );
1956    }
1957
1958    #[test]
1959    fn test_timestamp_widening_ordered_rejections_and_timezone() {
1960        let source_type = DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into()));
1961        let target_type = DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into()));
1962        let literal =
1963            ScalarValue::TimestampNanosecond(Some(123_456_789), Some("UTC".into()));
1964
1965        // A non-aligned literal has no singleton source value, so ordered
1966        // comparisons use the empty interval and equality-like ones keep the
1967        // cast. `123_456_789 / 1_000_000` floors to 123, so the interval is
1968        // `[124, 124)`.
1969        let empty = Some(CastPredicatePreimage::Range(
1970            Interval::try_new(
1971                ScalarValue::TimestampMillisecond(Some(124), Some("UTC".into())),
1972                ScalarValue::TimestampMillisecond(Some(124), Some("UTC".into())),
1973            )
1974            .unwrap(),
1975        ));
1976        for op in [Operator::GtEq, Operator::Gt, Operator::Lt, Operator::LtEq] {
1977            assert_eq!(
1978                cast_predicate_preimage(&source_type, &target_type, op, &literal)
1979                    .unwrap(),
1980                empty
1981            );
1982        }
1983        for op in [
1984            Operator::Eq,
1985            Operator::NotEq,
1986            Operator::IsDistinctFrom,
1987            Operator::IsNotDistinctFrom,
1988        ] {
1989            assert_preimage_none(&source_type, &target_type, op, &literal);
1990        }
1991
1992        // A literal of the wrong unit or the wrong timezone is not converted.
1993        for literal in [
1994            ScalarValue::TimestampMicrosecond(Some(123_456), Some("UTC".into())),
1995            ScalarValue::TimestampNanosecond(Some(123_456_789), None),
1996            ScalarValue::Int64(Some(123_456_789)),
1997        ] {
1998            for op in [Operator::Eq, Operator::GtEq, Operator::LtEq] {
1999                assert_preimage_none(&source_type, &target_type, op, &literal);
2000            }
2001        }
2002
2003        // A source/target timezone change has no source-domain bound.
2004        assert_preimage_none(
2005            &source_type,
2006            &DataType::Timestamp(TimeUnit::Nanosecond, None),
2007            Operator::GtEq,
2008            &ScalarValue::TimestampNanosecond(Some(123_456_789), None),
2009        );
2010    }
2011
2012    #[test]
2013    fn test_cast_predicate_preimage_timestamp_null_literal() {
2014        let ts_ns = DataType::Timestamp(TimeUnit::Nanosecond, None);
2015        let ts_ms = DataType::Timestamp(TimeUnit::Millisecond, None);
2016        let null_ms = ScalarValue::TimestampMillisecond(None, None);
2017
2018        // Narrowing a typed NULL literal has no source-domain bucket.
2019        for op in [
2020            Operator::Eq,
2021            Operator::NotEq,
2022            Operator::IsDistinctFrom,
2023            Operator::IsNotDistinctFrom,
2024            Operator::Gt,
2025            Operator::LtEq,
2026        ] {
2027            assert_preimage_none(&ts_ns, &ts_ms, op, &null_ms);
2028        }
2029
2030        // Widening and same-unit casts keep the NULL result on the source side.
2031        // The literal must be typed in the target unit, as SQL coercion produces.
2032        for target_unit in [TimeUnit::Millisecond, TimeUnit::Nanosecond] {
2033            let target_type = DataType::Timestamp(target_unit, None);
2034            assert_eq!(
2035                cast_predicate_preimage(
2036                    &ts_ms,
2037                    &target_type,
2038                    Operator::Eq,
2039                    &timestamp_scalar(&target_unit, None, None),
2040                )
2041                .unwrap(),
2042                Some(CastPredicatePreimage::Exact(
2043                    ScalarValue::TimestampMillisecond(None, None)
2044                ))
2045            );
2046        }
2047    }
2048
2049    #[test]
2050    fn test_try_cast_to_string_type() {
2051        let scalars = vec![
2052            ScalarValue::from("string"),
2053            ScalarValue::LargeUtf8(Some("string".to_owned())),
2054        ];
2055
2056        for s1 in &scalars {
2057            for s2 in &scalars {
2058                let expected_value = ExpectedCast::Value(s2.clone());
2059
2060                expect_cast(s1.clone(), s2.data_type(), expected_value);
2061            }
2062        }
2063    }
2064
2065    #[test]
2066    fn test_try_cast_to_dictionary_type() {
2067        fn dictionary_type(t: DataType) -> DataType {
2068            DataType::Dictionary(Box::new(DataType::Int32), Box::new(t))
2069        }
2070        fn dictionary_value(value: ScalarValue) -> ScalarValue {
2071            ScalarValue::Dictionary(Box::new(DataType::Int32), Box::new(value))
2072        }
2073        let scalars = vec![
2074            ScalarValue::from("string"),
2075            ScalarValue::LargeUtf8(Some("string".to_owned())),
2076        ];
2077        for s in &scalars {
2078            expect_cast(
2079                s.clone(),
2080                dictionary_type(s.data_type()),
2081                ExpectedCast::Value(dictionary_value(s.clone())),
2082            );
2083            expect_cast(
2084                dictionary_value(s.clone()),
2085                s.data_type(),
2086                ExpectedCast::Value(s.clone()),
2087            )
2088        }
2089    }
2090
2091    #[test]
2092    fn test_try_cast_to_fixed_size_binary() {
2093        expect_cast(
2094            ScalarValue::Binary(Some(vec![1, 2, 3])),
2095            DataType::FixedSizeBinary(3),
2096            ExpectedCast::Value(ScalarValue::FixedSizeBinary(3, Some(vec![1, 2, 3]))),
2097        )
2098    }
2099
2100    #[test]
2101    fn test_numeric_boundary_values() {
2102        // Test exact boundary values for signed integers
2103        expect_cast(
2104            ScalarValue::Int8(Some(i8::MAX)),
2105            DataType::UInt8,
2106            ExpectedCast::Value(ScalarValue::UInt8(Some(i8::MAX as u8))),
2107        );
2108
2109        expect_cast(
2110            ScalarValue::Int8(Some(i8::MIN)),
2111            DataType::UInt8,
2112            ExpectedCast::NoValue,
2113        );
2114
2115        expect_cast(
2116            ScalarValue::UInt8(Some(u8::MAX)),
2117            DataType::Int8,
2118            ExpectedCast::NoValue,
2119        );
2120
2121        // Test cross-type boundary scenarios
2122        expect_cast(
2123            ScalarValue::Int32(Some(i32::MAX)),
2124            DataType::Int64,
2125            ExpectedCast::Value(ScalarValue::Int64(Some(i32::MAX as i64))),
2126        );
2127
2128        expect_cast(
2129            ScalarValue::Int64(Some(i64::MIN)),
2130            DataType::UInt64,
2131            ExpectedCast::NoValue,
2132        );
2133
2134        // Test unsigned to signed edge cases
2135        expect_cast(
2136            ScalarValue::UInt32(Some(u32::MAX)),
2137            DataType::Int32,
2138            ExpectedCast::NoValue,
2139        );
2140
2141        expect_cast(
2142            ScalarValue::UInt64(Some(u64::MAX)),
2143            DataType::Int64,
2144            ExpectedCast::NoValue,
2145        );
2146    }
2147
2148    #[test]
2149    fn test_decimal_precision_limits() {
2150        use arrow::datatypes::{
2151            MAX_DECIMAL128_FOR_EACH_PRECISION, MIN_DECIMAL128_FOR_EACH_PRECISION,
2152        };
2153
2154        // Test maximum precision values
2155        expect_cast(
2156            ScalarValue::Decimal128(Some(MAX_DECIMAL128_FOR_EACH_PRECISION[3]), 3, 0),
2157            DataType::Decimal128(5, 0),
2158            ExpectedCast::Value(ScalarValue::Decimal128(
2159                Some(MAX_DECIMAL128_FOR_EACH_PRECISION[3]),
2160                5,
2161                0,
2162            )),
2163        );
2164
2165        // Test minimum precision values
2166        expect_cast(
2167            ScalarValue::Decimal128(Some(MIN_DECIMAL128_FOR_EACH_PRECISION[3]), 3, 0),
2168            DataType::Decimal128(5, 0),
2169            ExpectedCast::Value(ScalarValue::Decimal128(
2170                Some(MIN_DECIMAL128_FOR_EACH_PRECISION[3]),
2171                5,
2172                0,
2173            )),
2174        );
2175
2176        // Test scale increase
2177        expect_cast(
2178            ScalarValue::Decimal128(Some(123), 3, 0),
2179            DataType::Decimal128(5, 2),
2180            ExpectedCast::Value(ScalarValue::Decimal128(Some(12300), 5, 2)),
2181        );
2182
2183        // Test precision overflow (value too large for target precision)
2184        expect_cast(
2185            ScalarValue::Decimal128(Some(MAX_DECIMAL128_FOR_EACH_PRECISION[10]), 10, 0),
2186            DataType::Decimal128(3, 0),
2187            ExpectedCast::NoValue,
2188        );
2189
2190        // Test non-divisible decimal conversion (should fail)
2191        expect_cast(
2192            ScalarValue::Decimal128(Some(12345), 5, 3), // 12.345
2193            DataType::Int32,
2194            ExpectedCast::NoValue, // Can't convert 12.345 to integer without loss
2195        );
2196
2197        // Test edge case: scale reduction with precision loss
2198        expect_cast(
2199            ScalarValue::Decimal128(Some(12345), 5, 2), // 123.45
2200            DataType::Decimal128(3, 0),                 // Can only hold up to 999
2201            ExpectedCast::NoValue,
2202        );
2203    }
2204
2205    #[test]
2206    fn test_timestamp_overflow_scenarios() {
2207        // Test overflow in timestamp conversions
2208        let max_seconds = i64::MAX / 1_000_000_000; // Avoid overflow when converting to nanos
2209
2210        // This should work - within safe range
2211        expect_cast(
2212            ScalarValue::TimestampSecond(Some(max_seconds), None),
2213            DataType::Timestamp(TimeUnit::Nanosecond, None),
2214            ExpectedCast::Value(ScalarValue::TimestampNanosecond(
2215                Some(max_seconds * 1_000_000_000),
2216                None,
2217            )),
2218        );
2219
2220        // Test very large nanosecond value conversion to smaller units
2221        expect_cast(
2222            ScalarValue::TimestampNanosecond(Some(i64::MAX), None),
2223            DataType::Timestamp(TimeUnit::Second, None),
2224            ExpectedCast::Value(ScalarValue::TimestampSecond(
2225                Some(i64::MAX / 1_000_000_000),
2226                None,
2227            )),
2228        );
2229
2230        // Test precision loss in downscaling
2231        expect_cast(
2232            ScalarValue::TimestampNanosecond(Some(1), None),
2233            DataType::Timestamp(TimeUnit::Second, None),
2234            ExpectedCast::Value(ScalarValue::TimestampSecond(Some(0), None)),
2235        );
2236
2237        expect_cast(
2238            ScalarValue::TimestampMicrosecond(Some(999), None),
2239            DataType::Timestamp(TimeUnit::Millisecond, None),
2240            ExpectedCast::Value(ScalarValue::TimestampMillisecond(Some(0), None)),
2241        );
2242    }
2243
2244    #[test]
2245    fn test_string_view() {
2246        // Test Utf8View to other string types
2247        expect_cast(
2248            ScalarValue::Utf8View(Some("test".to_string())),
2249            DataType::Utf8,
2250            ExpectedCast::Value(ScalarValue::Utf8(Some("test".to_string()))),
2251        );
2252
2253        expect_cast(
2254            ScalarValue::Utf8View(Some("test".to_string())),
2255            DataType::LargeUtf8,
2256            ExpectedCast::Value(ScalarValue::LargeUtf8(Some("test".to_string()))),
2257        );
2258
2259        // Test other string types to Utf8View
2260        expect_cast(
2261            ScalarValue::Utf8(Some("hello".to_string())),
2262            DataType::Utf8View,
2263            ExpectedCast::Value(ScalarValue::Utf8View(Some("hello".to_string()))),
2264        );
2265
2266        expect_cast(
2267            ScalarValue::LargeUtf8(Some("world".to_string())),
2268            DataType::Utf8View,
2269            ExpectedCast::Value(ScalarValue::Utf8View(Some("world".to_string()))),
2270        );
2271
2272        // Test empty string
2273        expect_cast(
2274            ScalarValue::Utf8(Some("".to_string())),
2275            DataType::Utf8View,
2276            ExpectedCast::Value(ScalarValue::Utf8View(Some("".to_string()))),
2277        );
2278
2279        // Test large string
2280        let large_string = "x".repeat(1000);
2281        expect_cast(
2282            ScalarValue::LargeUtf8(Some(large_string.clone())),
2283            DataType::Utf8View,
2284            ExpectedCast::Value(ScalarValue::Utf8View(Some(large_string))),
2285        );
2286    }
2287
2288    #[test]
2289    fn test_binary_size_edge_cases() {
2290        // Test size mismatch - too small
2291        expect_cast(
2292            ScalarValue::Binary(Some(vec![1, 2])),
2293            DataType::FixedSizeBinary(3),
2294            ExpectedCast::NoValue,
2295        );
2296
2297        // Test size mismatch - too large
2298        expect_cast(
2299            ScalarValue::Binary(Some(vec![1, 2, 3, 4])),
2300            DataType::FixedSizeBinary(3),
2301            ExpectedCast::NoValue,
2302        );
2303
2304        // Test empty binary
2305        expect_cast(
2306            ScalarValue::Binary(Some(vec![])),
2307            DataType::FixedSizeBinary(0),
2308            ExpectedCast::Value(ScalarValue::FixedSizeBinary(0, Some(vec![]))),
2309        );
2310
2311        // Test exact size match
2312        expect_cast(
2313            ScalarValue::Binary(Some(vec![1, 2, 3])),
2314            DataType::FixedSizeBinary(3),
2315            ExpectedCast::Value(ScalarValue::FixedSizeBinary(3, Some(vec![1, 2, 3]))),
2316        );
2317
2318        // Test single byte
2319        expect_cast(
2320            ScalarValue::Binary(Some(vec![42])),
2321            DataType::FixedSizeBinary(1),
2322            ExpectedCast::Value(ScalarValue::FixedSizeBinary(1, Some(vec![42]))),
2323        );
2324    }
2325
2326    #[test]
2327    fn test_dictionary_index_types() {
2328        // Test different dictionary index types
2329        let string_value = ScalarValue::Utf8(Some("test".to_string()));
2330
2331        // Int8 index dictionary
2332        let dict_int8 =
2333            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8));
2334        expect_cast(
2335            string_value.clone(),
2336            dict_int8,
2337            ExpectedCast::Value(ScalarValue::Dictionary(
2338                Box::new(DataType::Int8),
2339                Box::new(string_value.clone()),
2340            )),
2341        );
2342
2343        // Int16 index dictionary
2344        let dict_int16 =
2345            DataType::Dictionary(Box::new(DataType::Int16), Box::new(DataType::Utf8));
2346        expect_cast(
2347            string_value.clone(),
2348            dict_int16,
2349            ExpectedCast::Value(ScalarValue::Dictionary(
2350                Box::new(DataType::Int16),
2351                Box::new(string_value.clone()),
2352            )),
2353        );
2354
2355        // Int64 index dictionary
2356        let dict_int64 =
2357            DataType::Dictionary(Box::new(DataType::Int64), Box::new(DataType::Utf8));
2358        expect_cast(
2359            string_value.clone(),
2360            dict_int64,
2361            ExpectedCast::Value(ScalarValue::Dictionary(
2362                Box::new(DataType::Int64),
2363                Box::new(string_value.clone()),
2364            )),
2365        );
2366
2367        // Test dictionary unwrapping
2368        let dict_value = ScalarValue::Dictionary(
2369            Box::new(DataType::Int32),
2370            Box::new(ScalarValue::LargeUtf8(Some("unwrap_test".to_string()))),
2371        );
2372        expect_cast(
2373            dict_value,
2374            DataType::LargeUtf8,
2375            ExpectedCast::Value(ScalarValue::LargeUtf8(Some("unwrap_test".to_string()))),
2376        );
2377    }
2378
2379    #[test]
2380    fn test_type_support_functions() {
2381        // Test numeric type support
2382        assert!(is_supported_numeric_type(&DataType::Int8));
2383        assert!(is_supported_numeric_type(&DataType::UInt64));
2384        assert!(is_supported_numeric_type(&DataType::Decimal128(10, 2)));
2385        assert!(is_supported_numeric_type(&DataType::Timestamp(
2386            TimeUnit::Nanosecond,
2387            None
2388        )));
2389        assert!(!is_supported_numeric_type(&DataType::Float32));
2390        assert!(!is_supported_numeric_type(&DataType::Float64));
2391
2392        // Test string type support
2393        assert!(is_supported_string_type(&DataType::Utf8));
2394        assert!(is_supported_string_type(&DataType::LargeUtf8));
2395        assert!(is_supported_string_type(&DataType::Utf8View));
2396        assert!(!is_supported_string_type(&DataType::Binary));
2397
2398        // Test binary type support
2399        assert!(is_supported_binary_type(&DataType::Binary));
2400        assert!(is_supported_binary_type(&DataType::FixedSizeBinary(10)));
2401        assert!(!is_supported_binary_type(&DataType::Utf8));
2402
2403        // Test dictionary type support with nested types
2404        assert!(is_supported_dictionary_type(&DataType::Dictionary(
2405            Box::new(DataType::Int32),
2406            Box::new(DataType::Utf8)
2407        )));
2408        assert!(is_supported_dictionary_type(&DataType::Dictionary(
2409            Box::new(DataType::Int32),
2410            Box::new(DataType::Int64)
2411        )));
2412        assert!(!is_supported_dictionary_type(&DataType::Dictionary(
2413            Box::new(DataType::Int32),
2414            Box::new(DataType::List(Arc::new(Field::new(
2415                "item",
2416                DataType::Int32,
2417                true
2418            ))))
2419        )));
2420
2421        // Test overall type support
2422        assert!(is_supported_type(&DataType::Int32));
2423        assert!(is_supported_type(&DataType::Utf8));
2424        assert!(is_supported_type(&DataType::Binary));
2425        assert!(is_supported_type(&DataType::Dictionary(
2426            Box::new(DataType::Int32),
2427            Box::new(DataType::Utf8)
2428        )));
2429        assert!(!is_supported_type(&DataType::List(Arc::new(Field::new(
2430            "item",
2431            DataType::Int32,
2432            true
2433        )))));
2434        assert!(!is_supported_type(&DataType::Struct(Fields::empty())));
2435    }
2436
2437    #[test]
2438    fn test_error_conditions() {
2439        // Test unsupported source type
2440        expect_cast(
2441            ScalarValue::Float32(Some(1.5)),
2442            DataType::Int32,
2443            ExpectedCast::NoValue,
2444        );
2445
2446        // Test unsupported target type
2447        expect_cast(
2448            ScalarValue::Int32(Some(123)),
2449            DataType::Float64,
2450            ExpectedCast::NoValue,
2451        );
2452
2453        // Test both types unsupported
2454        expect_cast(
2455            ScalarValue::Float64(Some(1.5)),
2456            DataType::Float32,
2457            ExpectedCast::NoValue,
2458        );
2459
2460        // Test complex unsupported types
2461        let list_type =
2462            DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
2463        expect_cast(
2464            ScalarValue::Int32(Some(123)),
2465            list_type,
2466            ExpectedCast::NoValue,
2467        );
2468
2469        // Test dictionary with unsupported inner type
2470        let bad_dict = DataType::Dictionary(
2471            Box::new(DataType::Int32),
2472            Box::new(DataType::List(Arc::new(Field::new(
2473                "item",
2474                DataType::Int32,
2475                true,
2476            )))),
2477        );
2478        expect_cast(
2479            ScalarValue::Int32(Some(123)),
2480            bad_dict,
2481            ExpectedCast::NoValue,
2482        );
2483    }
2484
2485    #[test]
2486    fn test_cast_predicate_preimage_extreme_literals() {
2487        let ts_ns = DataType::Timestamp(TimeUnit::Nanosecond, None);
2488        let ts_ms = DataType::Timestamp(TimeUnit::Millisecond, None);
2489
2490        // These millisecond values expand beyond i64 range in nanoseconds, so
2491        // the bucket has no representable endpoint and the preimage is None
2492        // rather than a clamped or unbounded interval.
2493        for value in [i64::MAX, i64::MIN] {
2494            assert_preimage_none(
2495                &ts_ns,
2496                &ts_ms,
2497                Operator::Eq,
2498                &ScalarValue::TimestampMillisecond(Some(value), None),
2499            );
2500        }
2501
2502        // A widening literal at the i64 boundary produces a checked source
2503        // endpoint: `i64::MAX` ns floors to 9223372036s with a 854775807ns
2504        // remainder, so the empty-interval bound `floor + 1` is 9223372037s,
2505        // still a representable second.
2506        let source_type = DataType::Timestamp(TimeUnit::Second, None);
2507        let target_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
2508        let empty = Some(CastPredicatePreimage::Range(
2509            Interval::try_new(
2510                ScalarValue::TimestampSecond(Some(9_223_372_037), None),
2511                ScalarValue::TimestampSecond(Some(9_223_372_037), None),
2512            )
2513            .unwrap(),
2514        ));
2515        assert_eq!(
2516            cast_predicate_preimage(
2517                &source_type,
2518                &target_type,
2519                Operator::Lt,
2520                &ScalarValue::TimestampNanosecond(Some(i64::MAX), None),
2521            )
2522            .unwrap(),
2523            empty
2524        );
2525
2526        // A bucket whose upper endpoint is not representable in the source unit
2527        // yields `None` rather than a clamped or unbounded interval.
2528        assert_preimage_none(
2529            &ts_ns,
2530            &ts_ms,
2531            Operator::Eq,
2532            &ScalarValue::TimestampMillisecond(Some(9_223_372_036_854), None),
2533        );
2534    }
2535
2536    #[test]
2537    fn test_cast_predicate_preimage_timestamp_identity_anchors() {
2538        // Same-unit casts anchor both ends of the domain, zero and NULL: the
2539        // literal passes through untouched, including `i64::MAX`, whose exclusive
2540        // upper bound would not fit in an `i64`.
2541        for (unit, scalar) in [
2542            (TimeUnit::Second, Some(i64::MIN)),
2543            (TimeUnit::Second, None),
2544            (TimeUnit::Second, Some(0)),
2545            (TimeUnit::Second, Some(i64::MAX)),
2546            (TimeUnit::Millisecond, Some(i64::MIN)),
2547            (TimeUnit::Millisecond, Some(0)),
2548            (TimeUnit::Millisecond, Some(i64::MAX)),
2549            (TimeUnit::Microsecond, Some(i64::MIN)),
2550            (TimeUnit::Microsecond, Some(0)),
2551            (TimeUnit::Microsecond, Some(i64::MAX)),
2552            (TimeUnit::Nanosecond, Some(i64::MIN)),
2553            (TimeUnit::Nanosecond, Some(0)),
2554            (TimeUnit::Nanosecond, Some(i64::MAX)),
2555        ] {
2556            let data_type = DataType::Timestamp(unit, None);
2557            let literal = timestamp_scalar(&unit, None, scalar);
2558            assert_preimage_exact(
2559                &data_type,
2560                &data_type,
2561                Operator::Eq,
2562                &literal,
2563                literal.clone(),
2564            );
2565            assert_eq!(
2566                exact_preimage_cast(&data_type, &data_type, &literal),
2567                Some(literal)
2568            );
2569        }
2570    }
2571
2572    #[test]
2573    fn test_cast_predicate_preimage_timestamp_rejects_nested_wrapper() {
2574        let dict = |inner: ScalarValue| {
2575            ScalarValue::Dictionary(Box::new(DataType::Int32), Box::new(inner))
2576        };
2577        let source_type = DataType::Timestamp(TimeUnit::Millisecond, None);
2578        let target_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
2579        let literal = ScalarValue::TimestampNanosecond(Some(123_000_000), None);
2580
2581        // One dictionary level is unwrapped.
2582        assert_preimage_exact(
2583            &source_type,
2584            &target_type,
2585            Operator::Eq,
2586            &dict(literal.clone()),
2587            ScalarValue::TimestampMillisecond(Some(123), None),
2588        );
2589        // A second wrapper is rejected rather than recursively unwrapped.
2590        assert_preimage_none(
2591            &source_type,
2592            &target_type,
2593            Operator::Eq,
2594            &dict(dict(literal)),
2595        );
2596    }
2597
2598    #[test]
2599    fn test_cast_predicate_preimage_timezone_preservation() {
2600        let source_type =
2601            DataType::Timestamp(TimeUnit::Nanosecond, Some("+05:30".into()));
2602        let target_type = DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into()));
2603        let lit = ScalarValue::TimestampMillisecond(Some(1000), Some("UTC".into()));
2604
2605        let result =
2606            cast_predicate_preimage(&source_type, &target_type, Operator::Eq, &lit)
2607                .unwrap();
2608        assert_preimage_data_type(result.as_ref(), &source_type);
2609
2610        match result {
2611            Some(CastPredicatePreimage::Range(interval)) => {
2612                let (lower, upper) = interval.into_bounds();
2613                assert_eq!(
2614                    lower,
2615                    ScalarValue::TimestampNanosecond(
2616                        Some(1_000_000_000),
2617                        Some("+05:30".into())
2618                    ),
2619                    "lower bound should preserve source timezone +05:30"
2620                );
2621                assert_eq!(
2622                    upper,
2623                    ScalarValue::TimestampNanosecond(
2624                        Some(1_001_000_000),
2625                        Some("+05:30".into())
2626                    ),
2627                    "upper bound should preserve source timezone +05:30"
2628                );
2629            }
2630            other => panic!("Expected CastPredicatePreimage::Range but got {other:?}"),
2631        }
2632    }
2633
2634    #[test]
2635    fn test_cast_predicate_preimage_timestamp_dictionary() {
2636        let key_type = Box::new(DataType::Int32);
2637        let dict = |key: &DataType, inner: DataType| {
2638            DataType::Dictionary(Box::new(key.clone()), Box::new(inner))
2639        };
2640        let wrap = |value: ScalarValue| {
2641            ScalarValue::Dictionary(key_type.clone(), Box::new(value))
2642        };
2643        let source_tz: Option<Arc<str>> = Some("+05:30".into());
2644
2645        // The target dictionary key (`Int16`) differs from the source key
2646        // (`Int32`) so a leaked target key cannot go unnoticed.
2647        let source_type = dict(
2648            &DataType::Int32,
2649            DataType::Timestamp(TimeUnit::Nanosecond, source_tz.clone()),
2650        );
2651        let target_type = dict(
2652            &DataType::Int16,
2653            DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into())),
2654        );
2655        let lit = ScalarValue::TimestampMillisecond(Some(1000), Some("UTC".into()));
2656
2657        let result =
2658            cast_predicate_preimage(&source_type, &target_type, Operator::Eq, &lit)
2659                .unwrap();
2660        // `ScalarValue` equality ignores timestamp timezones, so the data type
2661        // (dictionary key + source unit + source timezone) is asserted too.
2662        assert_preimage_data_type(result.as_ref(), &source_type);
2663        assert_eq!(
2664            result,
2665            Some(CastPredicatePreimage::Range(
2666                Interval::try_new(
2667                    wrap(ScalarValue::TimestampNanosecond(
2668                        Some(1_000_000_000),
2669                        source_tz.clone(),
2670                    )),
2671                    wrap(ScalarValue::TimestampNanosecond(
2672                        Some(1_001_000_000),
2673                        source_tz,
2674                    )),
2675                )
2676                .unwrap()
2677            ))
2678        );
2679
2680        // Exact preimages are dictionary-wrapped the same way.
2681        let ms_source = dict(
2682            &DataType::Int32,
2683            DataType::Timestamp(TimeUnit::Millisecond, None),
2684        );
2685        let ns_target = dict(
2686            &DataType::Int16,
2687            DataType::Timestamp(TimeUnit::Nanosecond, None),
2688        );
2689        let result = cast_predicate_preimage(
2690            &ms_source,
2691            &ns_target,
2692            Operator::Eq,
2693            &ScalarValue::TimestampNanosecond(Some(123_000_000), None),
2694        )
2695        .unwrap();
2696        assert_preimage_data_type(result.as_ref(), &ms_source);
2697        assert_eq!(
2698            result,
2699            Some(CastPredicatePreimage::Exact(wrap(
2700                ScalarValue::TimestampMillisecond(Some(123), None)
2701            )))
2702        );
2703
2704        // A dictionary-wrapped literal is accepted for the same cast.
2705        let result = cast_predicate_preimage(
2706            &ms_source,
2707            &ns_target,
2708            Operator::Eq,
2709            &wrap(ScalarValue::TimestampNanosecond(Some(123_000_000), None)),
2710        )
2711        .unwrap();
2712        assert_preimage_data_type(result.as_ref(), &ms_source);
2713        assert_eq!(
2714            result,
2715            Some(CastPredicatePreimage::Exact(wrap(
2716                ScalarValue::TimestampMillisecond(Some(123), None)
2717            )))
2718        );
2719
2720        // `exact_preimage_cast` (the IN-list path) returns the same source-domain
2721        // scalar, still dictionary-wrapped with the source key.
2722        let scalar = exact_preimage_cast(
2723            &ms_source,
2724            &ns_target,
2725            &ScalarValue::TimestampNanosecond(Some(123_000_000), None),
2726        )
2727        .unwrap();
2728        assert_eq!(scalar.data_type(), ms_source);
2729        assert_eq!(
2730            scalar,
2731            wrap(ScalarValue::TimestampMillisecond(Some(123), None))
2732        );
2733    }
2734
2735    // ── Gate safety tests ──────────────────────────────────────────────
2736
2737    #[test]
2738    fn test_exact_predicate_gate_safe() {
2739        // integer widening
2740        assert_preimage_exact(
2741            &DataType::Int32,
2742            &DataType::Int64,
2743            Operator::Eq,
2744            &ScalarValue::Int64(Some(10)),
2745            ScalarValue::Int32(Some(10)),
2746        );
2747        // unsigned → wider signed
2748        assert_preimage_exact(
2749            &DataType::UInt32,
2750            &DataType::Int64,
2751            Operator::Eq,
2752            &ScalarValue::Int64(Some(100)),
2753            ScalarValue::UInt32(Some(100)),
2754        );
2755        // int → decimal scale-up
2756        assert_preimage_exact(
2757            &DataType::Int32,
2758            &DataType::Decimal128(12, 2),
2759            Operator::Eq,
2760            &ScalarValue::Decimal128(Some(10000), 12, 2),
2761            ScalarValue::Int32(Some(100)),
2762        );
2763        // uint → decimal at the same scale
2764        assert_preimage_exact(
2765            &DataType::UInt64,
2766            &DataType::Decimal128(20, 0),
2767            Operator::Eq,
2768            &ScalarValue::Decimal128(Some(123), 20, 0),
2769            ScalarValue::UInt64(Some(123)),
2770        );
2771        // decimal scale-up at sub-maximum precision
2772        assert_preimage_exact(
2773            &DataType::Decimal128(10, 2),
2774            &DataType::Decimal128(18, 4),
2775            Operator::Eq,
2776            &ScalarValue::Decimal128(Some(1230000), 18, 4),
2777            ScalarValue::Decimal128(Some(12300), 10, 2),
2778        );
2779        // Date32 ↔ Int32
2780        assert_preimage_exact(
2781            &DataType::Date32,
2782            &DataType::Int32,
2783            Operator::Eq,
2784            &ScalarValue::Int32(Some(19000)),
2785            ScalarValue::Date32(Some(19000)),
2786        );
2787        assert_preimage_exact(
2788            &DataType::Int32,
2789            &DataType::Date32,
2790            Operator::Eq,
2791            &ScalarValue::Date32(Some(19000)),
2792            ScalarValue::Int32(Some(19000)),
2793        );
2794        // Date32 → Date64 is injective; literals must still land on a day
2795        // boundary to be exactly convertible back to the source type.
2796        assert_preimage_exact(
2797            &DataType::Date32,
2798            &DataType::Date64,
2799            Operator::Eq,
2800            &ScalarValue::Date64(Some(1_641_600_000_000)),
2801            ScalarValue::Date32(Some(19000)),
2802        );
2803        // FixedSizeBinary(n) → Binary
2804        assert_preimage_exact(
2805            &DataType::FixedSizeBinary(4),
2806            &DataType::Binary,
2807            Operator::Eq,
2808            &ScalarValue::Binary(Some(vec![1, 2, 3, 4])),
2809            ScalarValue::FixedSizeBinary(4, Some(vec![1, 2, 3, 4])),
2810        );
2811    }
2812
2813    #[test]
2814    fn test_exact_predicate_gate_blocked() {
2815        // numeric narrowing
2816        assert_preimage_none(
2817            &DataType::Int64,
2818            &DataType::Int32,
2819            Operator::Eq,
2820            &ScalarValue::Int32(Some(10)),
2821        );
2822        // signed → unsigned (even small values)
2823        assert_preimage_none(
2824            &DataType::Int32,
2825            &DataType::UInt32,
2826            Operator::Eq,
2827            &ScalarValue::UInt32(Some(10)),
2828        );
2829        // unsigned → narrower signed
2830        assert_preimage_none(
2831            &DataType::UInt64,
2832            &DataType::Int64,
2833            Operator::Eq,
2834            &ScalarValue::Int64(Some(10)),
2835        );
2836        // decimal → int
2837        assert_preimage_none(
2838            &DataType::Decimal128(18, 2),
2839            &DataType::Int64,
2840            Operator::Eq,
2841            &ScalarValue::Int64(Some(123)),
2842        );
2843        // decimal scale narrowing
2844        assert_preimage_none(
2845            &DataType::Decimal128(18, 2),
2846            &DataType::Decimal128(18, 1),
2847            Operator::Eq,
2848            &ScalarValue::Decimal128(Some(1230), 18, 1),
2849        );
2850        // negative decimal scale is not accepted for exact predicate rewrites
2851        assert_preimage_none(
2852            &DataType::Decimal128(10, -1),
2853            &DataType::Decimal128(18, 0),
2854            Operator::Eq,
2855            &ScalarValue::Decimal128(Some(120), 18, 0),
2856        );
2857        assert_preimage_none(
2858            &DataType::Int32,
2859            &DataType::Decimal128(12, -1),
2860            Operator::Eq,
2861            &ScalarValue::Decimal128(Some(120), 12, -1),
2862        );
2863        // Binary → FixedSizeBinary (not a family-safe source cast)
2864        assert_preimage_none(
2865            &DataType::Binary,
2866            &DataType::FixedSizeBinary(4),
2867            Operator::Eq,
2868            &ScalarValue::FixedSizeBinary(4, Some(vec![1, 2, 3, 4])),
2869        );
2870    }
2871
2872    #[test]
2873    fn test_decimal_scale_up_preimages() {
2874        let ops = [
2875            Operator::Eq,
2876            Operator::NotEq,
2877            Operator::Lt,
2878            Operator::LtEq,
2879            Operator::Gt,
2880            Operator::GtEq,
2881            Operator::IsDistinctFrom,
2882            Operator::IsNotDistinctFrom,
2883        ];
2884
2885        // One same-variant representative per decimal variant. Positive,
2886        // negative and zero literals use all eight comparison operators, and a
2887        // NULL literal casts to a NULL preimage.
2888        let cases = [
2889            (
2890                DataType::Decimal32(9, 1),
2891                DataType::Decimal32(9, 2),
2892                ScalarValue::Decimal32(Some(1200), 9, 2),
2893                ScalarValue::Decimal32(Some(120), 9, 1),
2894            ),
2895            (
2896                DataType::Decimal64(18, 1),
2897                DataType::Decimal64(18, 2),
2898                ScalarValue::Decimal64(Some(1200), 18, 2),
2899                ScalarValue::Decimal64(Some(120), 18, 1),
2900            ),
2901            (
2902                DataType::Decimal128(38, 1),
2903                DataType::Decimal128(38, 2),
2904                ScalarValue::Decimal128(Some(1200), 38, 2),
2905                ScalarValue::Decimal128(Some(120), 38, 1),
2906            ),
2907        ];
2908        for (source, target, literal, expected) in &cases {
2909            for op in ops {
2910                assert_preimage_exact(source, target, op, literal, expected.clone());
2911            }
2912            let (negative, negative_expected, zero, zero_expected) = match source {
2913                DataType::Decimal32(_, _) => (
2914                    ScalarValue::Decimal32(Some(-1200), 9, 2),
2915                    ScalarValue::Decimal32(Some(-120), 9, 1),
2916                    ScalarValue::Decimal32(Some(0), 9, 2),
2917                    ScalarValue::Decimal32(Some(0), 9, 1),
2918                ),
2919                DataType::Decimal64(_, _) => (
2920                    ScalarValue::Decimal64(Some(-1200), 18, 2),
2921                    ScalarValue::Decimal64(Some(-120), 18, 1),
2922                    ScalarValue::Decimal64(Some(0), 18, 2),
2923                    ScalarValue::Decimal64(Some(0), 18, 1),
2924                ),
2925                _ => (
2926                    ScalarValue::Decimal128(Some(-1200), 38, 2),
2927                    ScalarValue::Decimal128(Some(-120), 38, 1),
2928                    ScalarValue::Decimal128(Some(0), 38, 2),
2929                    ScalarValue::Decimal128(Some(0), 38, 1),
2930                ),
2931            };
2932            for (literal, expected) in
2933                [(negative, negative_expected), (zero, zero_expected)]
2934            {
2935                for op in ops {
2936                    assert_preimage_exact(source, target, op, &literal, expected.clone());
2937                }
2938            }
2939            let null = ScalarValue::try_from(target).unwrap();
2940            assert_preimage_exact(
2941                source,
2942                target,
2943                Operator::Eq,
2944                &null,
2945                ScalarValue::try_from(source).unwrap(),
2946            );
2947        }
2948
2949        // Additional shapes admitted by the scale-only rule: the motivating
2950        // sub-maximum 30,2 / 28,0 / 36,4 sources, a precision-37 target,
2951        // cross-width scale-up, cross-variant widening and signed / unsigned
2952        // integer sources.
2953        let extra_cases = [
2954            (
2955                DataType::Decimal128(30, 2),
2956                DataType::Decimal128(38, 15),
2957                ScalarValue::Decimal128(Some(4 * 10_i128.pow(15)), 38, 15),
2958                ScalarValue::Decimal128(Some(400), 30, 2),
2959            ),
2960            (
2961                DataType::Decimal128(28, 0),
2962                DataType::Decimal128(38, 15),
2963                ScalarValue::Decimal128(Some(4 * 10_i128.pow(15)), 38, 15),
2964                ScalarValue::Decimal128(Some(4), 28, 0),
2965            ),
2966            (
2967                DataType::Decimal128(36, 4),
2968                DataType::Decimal128(38, 15),
2969                ScalarValue::Decimal128(Some(4 * 10_i128.pow(15)), 38, 15),
2970                ScalarValue::Decimal128(Some(40_000), 36, 4),
2971            ),
2972            (
2973                DataType::Decimal128(37, 0),
2974                DataType::Decimal128(38, 2),
2975                ScalarValue::Decimal128(Some(1200), 38, 2),
2976                ScalarValue::Decimal128(Some(12), 37, 0),
2977            ),
2978            (
2979                DataType::Decimal128(38, 1),
2980                DataType::Decimal128(37, 2),
2981                ScalarValue::Decimal128(Some(1200), 37, 2),
2982                ScalarValue::Decimal128(Some(120), 38, 1),
2983            ),
2984            (
2985                DataType::Decimal64(18, 0),
2986                DataType::Decimal128(38, 30),
2987                ScalarValue::Decimal128(Some(10_i128.pow(30)), 38, 30),
2988                ScalarValue::Decimal64(Some(1), 18, 0),
2989            ),
2990            (
2991                DataType::Decimal128(38, 1),
2992                DataType::Decimal64(18, 2),
2993                ScalarValue::Decimal64(Some(1200), 18, 2),
2994                ScalarValue::Decimal128(Some(120), 38, 1),
2995            ),
2996            (
2997                DataType::Int32,
2998                DataType::Decimal128(10, 2),
2999                ScalarValue::Decimal128(Some(10000), 10, 2),
3000                ScalarValue::Int32(Some(100)),
3001            ),
3002            (
3003                DataType::UInt64,
3004                DataType::Decimal128(20, 2),
3005                ScalarValue::Decimal128(Some(12300), 20, 2),
3006                ScalarValue::UInt64(Some(123)),
3007            ),
3008        ];
3009        for (source, target, literal, expected) in &extra_cases {
3010            for op in ops {
3011                assert_preimage_exact(source, target, op, literal, expected.clone());
3012            }
3013        }
3014
3015        // The scale-only rule still rejects reduced or negative target scales,
3016        // nonaligned literals, decimal → integer and Decimal256.
3017        assert_preimage_none(
3018            &DataType::Decimal128(38, 1),
3019            &DataType::Decimal128(38, 0),
3020            Operator::Eq,
3021            &ScalarValue::Decimal128(Some(12), 38, 0),
3022        );
3023        assert_preimage_none(
3024            &DataType::Decimal128(18, 0),
3025            &DataType::Decimal128(10, -1),
3026            Operator::Eq,
3027            &ScalarValue::Decimal128(Some(12), 10, -1),
3028        );
3029        // Negative source scales are rejected by the gate instead of reaching
3030        // the scale arithmetic: both plain and one-level dictionary identity
3031        // return None.
3032        let negative_scale = DataType::Decimal128(10, -1);
3033        assert_preimage_none(
3034            &negative_scale,
3035            &negative_scale,
3036            Operator::Eq,
3037            &ScalarValue::Decimal128(Some(12), 10, -1),
3038        );
3039        let dict_negative_scale =
3040            DataType::Dictionary(Box::new(DataType::Int32), Box::new(negative_scale));
3041        assert_preimage_none(
3042            &dict_negative_scale,
3043            &dict_negative_scale,
3044            Operator::Eq,
3045            &ScalarValue::Decimal128(Some(12), 10, -1),
3046        );
3047        for literal in [
3048            ScalarValue::Decimal128(Some(1201), 38, 2),
3049            ScalarValue::Decimal128(Some(-1201), 38, 2),
3050        ] {
3051            assert_preimage_none(
3052                &DataType::Decimal128(38, 1),
3053                &DataType::Decimal128(38, 2),
3054                Operator::Eq,
3055                &literal,
3056            );
3057        }
3058        assert_preimage_none(
3059            &DataType::Decimal128(18, 2),
3060            &DataType::Int64,
3061            Operator::Eq,
3062            &ScalarValue::Int64(Some(123)),
3063        );
3064        assert_preimage_none(
3065            &DataType::Decimal256(76, 1),
3066            &DataType::Decimal256(76, 2),
3067            Operator::Eq,
3068            &ScalarValue::Decimal256(Some(1200.into()), 76, 2),
3069        );
3070
3071        // The literal still has to convert exactly into the source type and
3072        // into its range: a negative literal is not a UInt64 preimage, and a
3073        // cross-width decimal literal with sub-unit digits has no decimal128
3074        // preimage at the source scale.
3075        assert_preimage_none(
3076            &DataType::UInt64,
3077            &DataType::Decimal128(20, 2),
3078            Operator::Eq,
3079            &ScalarValue::Decimal128(Some(-12300), 20, 2),
3080        );
3081        assert_preimage_none(
3082            &DataType::Decimal128(38, 1),
3083            &DataType::Decimal64(18, 2),
3084            Operator::Eq,
3085            &ScalarValue::Decimal64(Some(1201), 18, 2),
3086        );
3087
3088        // Arrow's strict cast errors and TRY_CAST returns NULL when this valid
3089        // Decimal128 source exceeds the target's integer capacity.
3090        let target_type = DataType::Decimal128(38, 2);
3091        let source = ScalarValue::Decimal128(Some(i128::MAX / 10), 38, 1);
3092        let array = source.to_array_of_size(1).unwrap();
3093        assert!(
3094            cast_with_options(
3095                &array,
3096                &target_type,
3097                &CastOptions {
3098                    safe: false,
3099                    ..Default::default()
3100                },
3101            )
3102            .is_err()
3103        );
3104        assert_eq!(
3105            cast_with_options(&array, &target_type, &CastOptions::default())
3106                .unwrap()
3107                .null_count(),
3108            1,
3109        );
3110
3111        // Newly admitted integer source: i32::MAX is a valid Int32 value but
3112        // overflows decimal(10, 2). The rewritten predicate compares the
3113        // integer preimage instead, so an out-of-range row is simply FALSE for
3114        // `=` rather than an error or NULL.
3115        let int_target = DataType::Decimal128(10, 2);
3116        let int_literal = ScalarValue::Decimal128(Some(10000), 10, 2);
3117        let int_preimage =
3118            exact_preimage_cast(&DataType::Int32, &int_target, &int_literal)
3119                .expect("integer scale-up preimage");
3120        assert_eq!(int_preimage, ScalarValue::Int32(Some(100)));
3121        let int_max = ScalarValue::Int32(Some(i32::MAX));
3122        let int_max_array = int_max.to_array_of_size(1).unwrap();
3123        assert!(
3124            cast_with_options(
3125                &int_max_array,
3126                &int_target,
3127                &CastOptions {
3128                    safe: false,
3129                    ..Default::default()
3130                },
3131            )
3132            .is_err()
3133        );
3134        assert_eq!(
3135            cast_with_options(&int_max_array, &int_target, &CastOptions::default())
3136                .unwrap()
3137                .null_count(),
3138            1,
3139        );
3140        assert_eq!(int_max.partial_cmp(&int_preimage), Some(Ordering::Greater));
3141
3142        // Newly admitted sub-maximum decimal source: a valid decimal(30, 2)
3143        // value outside decimal(38, 15)'s integer capacity errors under a
3144        // strict cast and is NULL under TRY_CAST, while the rewritten equality
3145        // predicate is a boolean.
3146        let wide_source = DataType::Decimal128(30, 2);
3147        let wide_target = DataType::Decimal128(38, 15);
3148        let wide_literal = ScalarValue::Decimal128(Some(4 * 10_i128.pow(15)), 38, 15);
3149        let wide_preimage =
3150            exact_preimage_cast(&wide_source, &wide_target, &wide_literal)
3151                .expect("sub-maximum scale-up preimage");
3152        assert_eq!(wide_preimage, ScalarValue::Decimal128(Some(400), 30, 2));
3153        let out_of_range = ScalarValue::Decimal128(Some(10_i128.pow(25)), 30, 2);
3154        let out_of_range_array = out_of_range.to_array_of_size(1).unwrap();
3155        assert!(
3156            cast_with_options(
3157                &out_of_range_array,
3158                &wide_target,
3159                &CastOptions {
3160                    safe: false,
3161                    ..Default::default()
3162                },
3163            )
3164            .is_err()
3165        );
3166        assert_eq!(
3167            cast_with_options(&out_of_range_array, &wide_target, &CastOptions::default())
3168                .unwrap()
3169                .null_count(),
3170            1,
3171        );
3172        assert_eq!(
3173            out_of_range.partial_cmp(&wide_preimage),
3174            Some(Ordering::Greater)
3175        );
3176
3177        // Newly admitted cross-width decimal source: decimal128 to a narrower
3178        // decimal64, where a large but valid source value overflows.
3179        let cross_source = ScalarValue::Decimal128(Some(i128::MAX / 10), 38, 1);
3180        let cross_target = DataType::Decimal64(18, 2);
3181        let cross_preimage = exact_preimage_cast(
3182            &cross_source.data_type(),
3183            &cross_target,
3184            &ScalarValue::Decimal64(Some(1200), 18, 2),
3185        )
3186        .expect("cross-width scale-up preimage");
3187        assert_eq!(cross_preimage, ScalarValue::Decimal128(Some(120), 38, 1));
3188        let cross_array = cross_source.to_array_of_size(1).unwrap();
3189        assert!(
3190            cast_with_options(
3191                &cross_array,
3192                &cross_target,
3193                &CastOptions {
3194                    safe: false,
3195                    ..Default::default()
3196                },
3197            )
3198            .is_err()
3199        );
3200        assert_eq!(
3201            cast_with_options(&cross_array, &cross_target, &CastOptions::default())
3202                .unwrap()
3203                .null_count(),
3204            1,
3205        );
3206        assert_eq!(
3207            cross_source.partial_cmp(&cross_preimage),
3208            Some(Ordering::Greater)
3209        );
3210
3211        // This larger-scale Decimal128 value overflows the physical i128
3212        // representation during the cast, not only the target precision.
3213        let extreme = ScalarValue::Decimal128(Some(10_i128.pow(37)), 38, 2);
3214        let extreme_array = extreme.to_array_of_size(1).unwrap();
3215        let extreme_target = DataType::Decimal128(38, 15);
3216        assert_preimage_exact(
3217            &DataType::Decimal128(38, 2),
3218            &extreme_target,
3219            Operator::Eq,
3220            &ScalarValue::Decimal128(Some(4 * 10_i128.pow(15)), 38, 15),
3221            ScalarValue::Decimal128(Some(400), 38, 2),
3222        );
3223        assert!(
3224            cast_with_options(
3225                &extreme_array,
3226                &extreme_target,
3227                &CastOptions {
3228                    safe: false,
3229                    ..Default::default()
3230                },
3231            )
3232            .is_err()
3233        );
3234        assert_eq!(
3235            cast_with_options(&extreme_array, &extreme_target, &CastOptions::default())
3236                .unwrap()
3237                .null_count(),
3238            1,
3239        );
3240    }
3241
3242    // ── Integer → string distinctness tests ─────────────────────────────
3243
3244    #[test]
3245    fn test_cast_to_string_is_distinct_from_round_trip() {
3246        // IS DISTINCT FROM with round-trippable string
3247        assert_preimage_exact(
3248            &DataType::Int32,
3249            &DataType::Utf8,
3250            Operator::IsDistinctFrom,
3251            &ScalarValue::Utf8(Some("123".to_string())),
3252            ScalarValue::Int32(Some(123)),
3253        );
3254        // IS NOT DISTINCT FROM with round-trippable string
3255        assert_preimage_exact(
3256            &DataType::Int32,
3257            &DataType::Utf8,
3258            Operator::IsNotDistinctFrom,
3259            &ScalarValue::Utf8(Some("123".to_string())),
3260            ScalarValue::Int32(Some(123)),
3261        );
3262        // IS NOT DISTINCT FROM with non-round-trippable string (leading zero)
3263        assert_preimage_none(
3264            &DataType::Int32,
3265            &DataType::Utf8,
3266            Operator::IsNotDistinctFrom,
3267            &ScalarValue::Utf8(Some("0123".to_string())),
3268        );
3269        // IS DISTINCT FROM with non-round-trippable string
3270        assert_preimage_none(
3271            &DataType::Int32,
3272            &DataType::Utf8,
3273            Operator::IsDistinctFrom,
3274            &ScalarValue::Utf8(Some("0123".to_string())),
3275        );
3276    }
3277
3278    // ── Helpers ─────────────────────────────────────────────────────────
3279
3280    fn assert_preimage_exact(
3281        source_type: &DataType,
3282        target_type: &DataType,
3283        op: Operator,
3284        lit_value: &ScalarValue,
3285        expected_source: ScalarValue,
3286    ) {
3287        let result =
3288            cast_predicate_preimage(source_type, target_type, op, lit_value).unwrap();
3289        // The preimage must be a source-domain value: same unit, timezone and
3290        // dictionary key as the source, never the target.
3291        assert_preimage_data_type(result.as_ref(), source_type);
3292        assert_eq!(
3293            result,
3294            Some(CastPredicatePreimage::Exact(expected_source)),
3295            "expected Exact preimage for {source_type:?} → {target_type:?} {op:?} {lit_value:?}"
3296        );
3297    }
3298
3299    fn assert_preimage_none(
3300        source_type: &DataType,
3301        target_type: &DataType,
3302        op: Operator,
3303        lit_value: &ScalarValue,
3304    ) {
3305        let result =
3306            cast_predicate_preimage(source_type, target_type, op, lit_value).unwrap();
3307        assert_eq!(
3308            result, None,
3309            "expected None preimage for {source_type:?} → {target_type:?} {op:?} {lit_value:?}"
3310        );
3311    }
3312
3313    /// Asserts that every endpoint of a preimage has the expected data type.
3314    ///
3315    /// [`ScalarValue`] equality ignores a timestamp's timezone metadata, and a
3316    /// dictionary wrapper is compared only by key type plus inner value, so
3317    /// value-based assertions alone cannot catch a leaked target timezone, unit
3318    /// or dictionary key. This check must accompany them.
3319    fn assert_preimage_data_type(
3320        preimage: Option<&CastPredicatePreimage>,
3321        expected: &DataType,
3322    ) {
3323        let (lower, upper) = match preimage {
3324            Some(CastPredicatePreimage::Exact(value)) => (value, value),
3325            Some(CastPredicatePreimage::Range(interval)) => {
3326                (interval.lower(), interval.upper())
3327            }
3328            None => return,
3329        };
3330        assert_eq!(&lower.data_type(), expected);
3331        assert_eq!(&upper.data_type(), expected);
3332    }
3333
3334    /// Asserts the widening preimage shapes for a `source → target` unit pair
3335    /// with `target` finer than `source`.
3336    fn assert_timestamp_widening_ordered(source_unit: TimeUnit, target_unit: TimeUnit) {
3337        let source_type = DataType::Timestamp(source_unit, None);
3338        let target_type = DataType::Timestamp(target_unit, None);
3339        let quotient = i128::from(timestamp_unit_scale(&target_unit))
3340            / i128::from(timestamp_unit_scale(&source_unit));
3341        assert!(quotient > 1, "expected a widening unit pair");
3342
3343        // Aligned literals have a singleton preimage for every operator.
3344        let aligned = timestamp_scalar(
3345            &target_unit,
3346            None,
3347            Some(i64::try_from(123 * quotient).unwrap()),
3348        );
3349        for op in [
3350            Operator::Eq,
3351            Operator::NotEq,
3352            Operator::IsDistinctFrom,
3353            Operator::IsNotDistinctFrom,
3354            Operator::GtEq,
3355            Operator::Gt,
3356            Operator::Lt,
3357            Operator::LtEq,
3358        ] {
3359            assert_preimage_exact(
3360                &source_type,
3361                &target_type,
3362                op,
3363                &aligned,
3364                timestamp_scalar(&source_unit, None, Some(123)),
3365            );
3366        }
3367
3368        // A non-aligned literal has no singleton preimage: ordered comparisons
3369        // get the empty interval `[floor + 1, floor + 1)` and equality-like ones
3370        // keep the cast. The bounds are checked real source-unit values, so the
3371        // extreme literal is covered without any clamping.
3372        for target_value in [
3373            quotient + 1,
3374            1 - quotient,
3375            i128::from(i64::MAX),
3376            i128::from(i64::MIN),
3377        ] {
3378            let literal = timestamp_scalar(&target_unit, None, Some(target_value as i64));
3379            let bound = i64::try_from(target_value.div_euclid(quotient) + 1).unwrap();
3380            let empty = Some(CastPredicatePreimage::Range(
3381                Interval::try_new(
3382                    timestamp_scalar(&source_unit, None, Some(bound)),
3383                    timestamp_scalar(&source_unit, None, Some(bound)),
3384                )
3385                .unwrap(),
3386            ));
3387
3388            for op in [Operator::GtEq, Operator::Gt, Operator::Lt, Operator::LtEq] {
3389                let result =
3390                    cast_predicate_preimage(&source_type, &target_type, op, &literal)
3391                        .unwrap();
3392                assert_preimage_data_type(result.as_ref(), &source_type);
3393                assert_eq!(
3394                    result, empty,
3395                    "unexpected preimage for {source_unit:?} → {target_unit:?} {op:?} {target_value}"
3396                );
3397            }
3398            for op in [
3399                Operator::Eq,
3400                Operator::NotEq,
3401                Operator::IsDistinctFrom,
3402                Operator::IsNotDistinctFrom,
3403            ] {
3404                assert_preimage_none(&source_type, &target_type, op, &literal);
3405            }
3406        }
3407    }
3408
3409    /// Asserts the truncation bucket `[lower, upper)` of a narrowing cast.
3410    fn assert_timestamp_narrowing_range(
3411        source_unit: TimeUnit,
3412        target_unit: TimeUnit,
3413        lit: i64,
3414        lower: i64,
3415        upper: i64,
3416    ) {
3417        let source_type = DataType::Timestamp(source_unit, None);
3418        let target_type = DataType::Timestamp(target_unit, None);
3419        let expected = Some(CastPredicatePreimage::Range(
3420            Interval::try_new(
3421                timestamp_scalar(&source_unit, None, Some(lower)),
3422                timestamp_scalar(&source_unit, None, Some(upper)),
3423            )
3424            .unwrap(),
3425        ));
3426        let result = cast_predicate_preimage(
3427            &source_type,
3428            &target_type,
3429            Operator::Eq,
3430            &timestamp_scalar(&target_unit, None, Some(lit)),
3431        )
3432        .unwrap();
3433        assert_preimage_data_type(result.as_ref(), &source_type);
3434        assert_eq!(
3435            result, expected,
3436            "unexpected narrowing bucket for {source_unit:?} → {target_unit:?} {lit}"
3437        );
3438    }
3439}