refactor: Use cast preimages for cast predicate rewrites (#22906) ## Which issue does this PR close? - Closes #22142. ## Rationale for this change The previous cast-unwrap path could only move the original comparison operator from `CAST(expr AS target_type) OP literal` to `expr OP casted_literal`. That is not correct for many-to-one casts such as timestamp precision narrowing, where the source-domain preimage of one target value is a range rather than a singleton. For example, `CAST(ts_ns AS Timestamp(ms)) > 1000ms` must not become `ts_ns > 1_000_000_000ns`; its exact source boundary is `ts_ns >= 1_001_000_000ns`. Timestamp precision widening has a related ordered-comparison case. A non-aligned target literal has no singleton equality preimage, but it does have an exact source-unit boundary for an ordered predicate. For example: ```text CAST(ts_ms AS Timestamp(ns)) >= 123_456_789ns ``` becomes: ```text ts_ms >= 124ms ``` This PR also makes exact cast rewrites closed-by-default: exact rewrites require a supported value-preserving cast family. Many-to-one or source-domain-reducing casts either use an explicit range/boundary preimage or remain unchanged. The ordered timestamp-widening rewrite deliberately follows the existing widening policy used by this work. At extreme source values where widening overflows, ordinary `CAST` can error and `TRY_CAST` can return `NULL`, while the rewritten source-unit comparison returns a Boolean. This is not a claim of full-domain equivalence for those overflow cases; a guarded/error-aware preimage representation is outside this PR's scope. ## What changes are included in this PR? - Add a shared `CastPredicatePreimage` abstraction in `datafusion-expr-common`: - `Exact(ScalarValue)` for a same-operator source literal or boundary. - `Range(Interval)` for a half-open source-domain interval. - Share cast-preimage computation between logical and physical simplifiers. - Organize preimage computation into explicit range, special exact, generic exact, and ordered timestamp-widening paths. - Implement timestamp precision narrowing preimages using half-open buckets with truncation-toward-zero semantics, including negative timestamps. - Implement non-aligned ordered timestamp-widening boundaries using Euclidean floor/ceil arithmetic in `i128`: - `>= L` and `< L` use `ceil(L / q)`. - `> L` and `<= L` use `floor(L / q)`. - Support all timestamp precision-widening unit pairs with matching timezone metadata, including `CAST`, `TRY_CAST`, and literal-left comparisons. - Keep non-aligned equality, distinctness, and `IN` predicates unchanged. - Keep timestamp precision narrowing out of `IN` rewrites because its preimage is a range rather than a singleton. - Add conservative exact-cast family gates, including date, integer, signedness, decimal precision/scale, and canonical integer/string checks. - Replace the logical optimizer's cast-unwrap module with a cast-preimage module and update the physical simplifier to use the same helper. ### Behavior changes compared to `main` | Expression | Behavior after this PR | Why | |---|---|---| | `CAST(c1:Int32 AS Int64) < 10` | `c1 < Int32(10)` | Integer widening is value-preserving. | | `CAST(c2:Int64 AS Int32) = 5` | kept | Integer narrowing reduces the source domain. | | `CAST(c1:Int32 AS UInt32) = 5` | kept | Signed-to-unsigned is not full-domain safe. | | `CAST(c1:Int32 AS Utf8) = '123'` | `c1 = Int32(123)` | The literal round-trips canonically. | | `CAST(c1:Int32 AS Utf8) = '0123'` | kept | `'0123' -> 123 -> '123'` does not round-trip. | | `CAST(c1:Int32 AS Utf8) < '123'` | kept | String ordering is not integer ordering. | | `CAST(c1:Int32 AS Decimal(12,2)) = 123.00` | `c1 = Int32(123)` | The target decimal represents the full source domain. | | `CAST(c1:Int32 AS Decimal(10,2)) = 123.00` | kept | The target has insufficient integer digits. | | `CAST(c3:Decimal(10,2) AS Decimal(18,4)) = 123.0000` | exact rewrite | Precision/scale widening is value-preserving. | | `CAST(c3:Decimal(18,2) AS Decimal(18,1)) = 123.0` | kept | Scale narrowing is many-to-one. | | `CAST(ts_ns AS timestamp(ms)) = 1000ms` | `ts_ns >= 1_000_000_000ns AND ts_ns < 1_001_000_000ns` | Equality preimage is a timestamp bucket. | | `CAST(ts_ns AS timestamp(ms)) > 1000ms` | `ts_ns >= 1_001_000_000ns` | Uses the bucket's upper boundary. | | `CAST(ts_ns AS timestamp(ms)) <= 0ms` | `ts_ns < 1_000_000ns` | The zero bucket follows truncation toward zero. | | `CAST(ts_ns AS timestamp(ms)) = -1ms` | `ts_ns >= -1_999_999ns AND ts_ns < -999_999ns` | Negative buckets follow truncation toward zero. | | `CAST(ts_ns AS timestamp(ms)) != 1000ms` | range-complement rewrite | Complements the timestamp bucket. | | `CAST(ts_ns AS timestamp(ms)) IN (1000ms)` | kept | `IN` currently supports only singleton exact preimages. | | `CAST(ts_ms AS timestamp(ns)) = 123_000_000ns` | `ts_ms = 123ms` | The aligned widening literal round-trips. | | `CAST(ts_ms AS timestamp(ns)) = 123_456_789ns` | kept | A non-aligned literal has no equality preimage. | | `CAST(ts_ms AS timestamp(ns)) >= 123_456_789ns` | `ts_ms >= 124ms` | Ordered widening uses the exact Euclidean source boundary under the documented overflow policy. | | `123_456_789ns < TRY_CAST(ts_ms AS timestamp(ns))` | `ts_ms > 123ms` | Literal-left operators are swapped before computing the same boundary. | | `CAST(Date64_col AS Date32) = ...` | kept | Date precision narrowing is not exact-safe. | | `CAST(Date32_col AS Date64) = aligned_midnight` | exact rewrite | Date widening is injective when the literal is on a day boundary. | ## Are these changes tested? Yes. Tests cover: - exact and range preimages and conservative cast-family gating, - timestamp narrowing for positive, zero, and negative values, - all timestamp widening unit pairs, - aligned and non-aligned widening literals, - all four ordered operators with positive and negative values, - `CAST`, `TRY_CAST`, and literal-left forms, - timezone/type/NULL rejection and `i64` boundary literals, - equality, distinctness, and `IN` remaining unchanged where required, - logical, physical, and sqllogictest plan output. Validated locally with: ```bash cargo test -p datafusion-expr-common --lib cast_predicate cargo test -p datafusion-optimizer --lib cast_preimage cargo test -p datafusion-physical-expr --lib unwrap_cast cargo test -p datafusion-sqllogictest --test sqllogictests -- simplify_expr cargo fmt --all -- --check cargo clippy --all-targets --all-features -- -D warnings ``` ## Are there any user-facing changes? There are no public API changes. Optimized plans may now use exact source-domain ranges or boundaries for cast predicates, and previously unsafe exact rewrites may remain unchanged. Ordered timestamp-widening comparisons also follow the explicit overflow policy described above. --------- Signed-off-by: discord9 <discord9@163.com> Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
DataFusion is an extensible query engine written in Rust that uses Apache Arrow as its in-memory format.
This crate provides libraries and binaries for developers building fast and feature-rich database and analytic systems, customized for particular workloads. See use cases for examples. The following related subprojects target end users:
“Out of the box,” DataFusion offers SQL and DataFrame APIs, excellent performance, built-in support for CSV, Parquet, JSON, and Avro, extensive customization, and a great community.
DataFusion features a full query planner, a columnar, streaming, multi-threaded, vectorized execution engine, and partitioned data sources. You can customize DataFusion at almost all points including additional data sources, query languages, functions, custom operators and more. See the Architecture section for more details.
Here are links to important resources:
DataFusion is great for building projects such as domain-specific query engines, new database platforms and data pipelines, query languages and more. It lets you start quickly from a fully working engine, and then customize those features specific to your needs. See the list of known users.
Please see the contributor guide and communication pages for more information.
We discuss our roadmap via GitHub issues and invite you to join the conversation. The current discussion is the DataFusion 2026 Q3-Q4 Roadmap Discussion.
This crate has several features which can be specified in your Cargo.toml.
Default features:
nested_expressions: functions for working with nested types such as array_to_stringcompression: reading files compressed with xz2, bzip2, flate2, and zstdcrypto_expressions: cryptographic functions such as md5 and sha256datetime_expressions: date and time functions such as to_timestampencoding_expressions: encode and decode functionsparquet: support for reading the Apache Parquet formatsql: support for SQL parsing and planningregex_expressions: regular expression functions, such as regexp_matchunicode_expressions: include Unicode-aware functions such as character_lengthunparser: enables support to reverse LogicalPlans back into SQLrecursive_protection: uses recursive for stack overflow protection.Optional features:
avro: support for reading the Apache Avro formatbacktrace: include backtrace information in error messagesparquet_encryption: support for using Parquet Modular Encryptionserde: enable arrow-schema's serde featurePublic methods in Apache DataFusion evolve over time: while we try to maintain a stable API, we also improve the API over time. As a result, we typically deprecate methods before removing them, according to the deprecation guidelines.
Cargo.lockFollowing the guidance on committing Cargo.lock files, this project commits its Cargo.lock file.
CI uses the committed Cargo.lock file, and dependencies are updated regularly using Dependabot PRs.