You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/23 06:55:53 UTC

(datafusion) 01/01: fix: keep decimal and temporal types in nvl and ifnull (#25964)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-25964-3c83711c66652560ad4b4d9a66617d3951ecf308
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit a893f40cfa8bdd2d8d8aed9af550befbb02d13e2
Author: Stefan Wang <1f...@gmail.com>
AuthorDate: Fri Oct 23 06:11:21 2026 +0000

    fix: keep decimal and temporal types in nvl and ifnull (#25964)
    
    ## Which issue does this PR close?
    
    - Closes https://github.com/apache/datafusion/issues/25947.
    
    ## Rationale for this change
    
    nvl and ifnull lose decimal digits and convert dates and timestamps to
    strings, unlike coalesce. That also breaks timestamp arithmetic after
    ifnull. Their signature omits these types, so the planner coerces them
    to numbers or strings.
    
    ## What changes are included in this PR?
    
    The planner uses coalesce's type union for those types and retains
    existing coercion for primitive arguments and unsupported unions. This
    preserves accepted integer/boolean calls but also retains mixed-integer
    Float32 rounding. The shared helper validates argument counts;
    evaluation is unchanged.
    
    ## What is the testing strategy for this PR?
    
    SQL regressions cover decimal values, date and timestamp types,
    timestamp arithmetic and compatibility pairs. The public UDF and SQL
    tests also cover wrong argument counts.
    
    ### Testing Done
    
    | Scenario | Command | Result |
    |---|---|---|
    | Decimal, date and timestamp results | target/ci/datafusion-cli -f
    datafusion-25947.sql | Values and types retained; timestamp arithmetic
    succeeds |
    | Existing coercion | target/ci/datafusion-cli -f nvl-kept-types.sql |
    Unchanged |
    | Argument count | target/ci/datafusion-cli -q --format json -c 'SELECT
    nvl(1);' | Standard arity error |
    
    datafusion-cli built with cargo build --profile ci -p datafusion-cli on
    main (416002a5b) and on this branch, running the issue's queries:
    
    ```shell
    target/ci/datafusion-cli -f datafusion-25947.sql
    ```
    
    On main, nvl returns Float64 for the decimals and Utf8View for the
    timestamp and date, and the interval addition fails:
    
    ```text
    DataFusion CLI v55.1.0
    0 row(s) fetched.
    Elapsed 0.019 seconds.
    
    +-----------------------+----------------------------------------+
    | nvl_big               | coalesce_big                           |
    +-----------------------+----------------------------------------+
    | 1.2345678901234568e37 | 12345678901234567890123456789012345678 |
    +-----------------------+----------------------------------------+
    1 row(s) fetched.
    Elapsed 0.004 seconds.
    
    +---------+----------+------------------+
    | nvl_d   | ifnull_d | coalesce_d       |
    +---------+----------+------------------+
    | Float64 | Float64  | Decimal128(5, 2) |
    +---------+----------+------------------+
    1 row(s) fetched.
    Elapsed 0.003 seconds.
    
    +----------+-----------+---------------+
    | nvl_ts   | ifnull_ts | coalesce_ts   |
    +----------+-----------+---------------+
    | Utf8View | Utf8View  | Timestamp(ns) |
    +----------+-----------+---------------+
    1 row(s) fetched.
    Elapsed 0.003 seconds.
    
    +----------+-------------+
    | nvl_dt   | coalesce_dt |
    +----------+-------------+
    | Utf8View | Date32      |
    +----------+-------------+
    1 row(s) fetched.
    Elapsed 0.002 seconds.
    
    Error during planning: Cannot coerce arithmetic expression Utf8View + Interval(MonthDayNano) to valid types
    ```
    
    For these decimal, date and timestamp queries, nvl and ifnull retain the
    values and types, and timestamp arithmetic succeeds:
    
    ```text
    DataFusion CLI v55.1.0
    0 row(s) fetched.
    Elapsed 0.152 seconds.
    
    +----------------------------------------+----------------------------------------+
    | nvl_big                                | coalesce_big                           |
    +----------------------------------------+----------------------------------------+
    | 12345678901234567890123456789012345678 | 12345678901234567890123456789012345678 |
    +----------------------------------------+----------------------------------------+
    1 row(s) fetched.
    Elapsed 0.019 seconds.
    
    +------------------+------------------+------------------+
    | nvl_d            | ifnull_d         | coalesce_d       |
    +------------------+------------------+------------------+
    | Decimal128(5, 2) | Decimal128(5, 2) | Decimal128(5, 2) |
    +------------------+------------------+------------------+
    1 row(s) fetched.
    Elapsed 0.005 seconds.
    
    +---------------+---------------+---------------+
    | nvl_ts        | ifnull_ts     | coalesce_ts   |
    +---------------+---------------+---------------+
    | Timestamp(ns) | Timestamp(ns) | Timestamp(ns) |
    +---------------+---------------+---------------+
    1 row(s) fetched.
    Elapsed 0.003 seconds.
    
    +--------+-------------+
    | nvl_dt | coalesce_dt |
    +--------+-------------+
    | Date32 | Date32      |
    +--------+-------------+
    1 row(s) fetched.
    Elapsed 0.002 seconds.
    
    +---------------------+
    | ifnull_plus         |
    +---------------------+
    | 2024-01-01T11:00:00 |
    +---------------------+
    1 row(s) fetched.
    Elapsed 0.006 seconds.
    ```
    
    Argument types the signature already listed keep their result types,
    including pairs coalesce rejects or resolves differently, and a
    timestamp with a string still falls back to the original coercion:
    
    ```shell
    target/ci/datafusion-cli -f nvl-kept-types.sql
    ```
    
    On main:
    
    ```text
    DataFusion CLI v55.1.0
    0 row(s) fetched.
    Elapsed 0.004 seconds.
    
    +----------+----------+-------------+-----------+----------+
    | int_bool | int_utf8 | int8_uint64 | null_null | ts_utf8  |
    +----------+----------+-------------+-----------+----------+
    | Utf8View | Utf8View | Float32     | Boolean   | Utf8View |
    +----------+----------+-------------+-----------+----------+
    1 row(s) fetched.
    Elapsed 0.004 seconds.
    
    +-----------------+
    | ifnull_int_bool |
    +-----------------+
    | 1               |
    +-----------------+
    1 row(s) fetched.
    Elapsed 0.001 seconds.
    ```
    
    On this branch:
    
    ```text
    DataFusion CLI v55.1.0
    0 row(s) fetched.
    Elapsed 0.005 seconds.
    
    +----------+----------+-------------+-----------+----------+
    | int_bool | int_utf8 | int8_uint64 | null_null | ts_utf8  |
    +----------+----------+-------------+-----------+----------+
    | Utf8View | Utf8View | Float32     | Boolean   | Utf8View |
    +----------+----------+-------------+-----------+----------+
    1 row(s) fetched.
    Elapsed 0.008 seconds.
    
    +-----------------+
    | ifnull_int_bool |
    +-----------------+
    | 1               |
    +-----------------+
    1 row(s) fetched.
    Elapsed 0.001 seconds.
    ```
    
    The argument-count regressions now use the standard message:
    
    ```shell
    target/ci/datafusion-cli -q --format json -c 'SELECT nvl(1);'
    ```
    
    ```text
    Error: Error during planning: Execution error: Function 'nvl' user-defined coercion failed with: Execution error: nvl function requires 2 arguments, got 1. No function matches the given name and argument types 'nvl(Int64)'. You might need to add explicit type casts.
            Candidate functions:
            nvl(UserDefined)
    EXIT_CODE=1
    ```
    
    <details>
    <summary>Reproducer source: datafusion-25947.sql</summary>
    
    ```sql
    CREATE TABLE t AS SELECT
      CAST('12345678901234567890123456789012345678' AS DECIMAL(38,0)) AS big,
      CAST(1.23 AS DECIMAL(5,2)) AS d,
      TIMESTAMP '2024-01-01 10:00:00' AS ts,
      DATE '2024-01-01' AS dt;
    
    SELECT nvl(big, 0) AS nvl_big, coalesce(big, 0) AS coalesce_big FROM t;
    
    SELECT
      arrow_typeof(nvl(d, d)) AS nvl_d,
      arrow_typeof(ifnull(d, d)) AS ifnull_d,
      arrow_typeof(coalesce(d, d)) AS coalesce_d
    FROM t;
    
    SELECT
      arrow_typeof(nvl(ts, ts)) AS nvl_ts,
      arrow_typeof(ifnull(ts, ts)) AS ifnull_ts,
      arrow_typeof(coalesce(ts, ts)) AS coalesce_ts
    FROM t;
    
    SELECT
      arrow_typeof(nvl(dt, dt)) AS nvl_dt,
      arrow_typeof(coalesce(dt, dt)) AS coalesce_dt
    FROM t;
    
    SELECT ifnull(ts, ts) + INTERVAL '1 hour' AS ifnull_plus FROM t;
    ```
    
    </details>
    
    <details>
    <summary>Reproducer source: nvl-kept-types.sql</summary>
    
    ```sql
    CREATE TABLE t AS SELECT TIMESTAMP '2024-01-01 10:00:00' AS ts;
    
    SELECT
      arrow_typeof(nvl(arrow_cast(1, 'Int64'), false)) AS int_bool,
      arrow_typeof(nvl(arrow_cast(1, 'Int64'), arrow_cast('x', 'Utf8'))) AS int_utf8,
      arrow_typeof(nvl(arrow_cast(1, 'Int8'), arrow_cast(2, 'UInt64'))) AS int8_uint64,
      arrow_typeof(nvl(NULL, NULL)) AS null_null,
      arrow_typeof(nvl(ts, '2024-01-01T00:00:00')) AS ts_utf8
    FROM t;
    
    SELECT ifnull(arrow_cast(1, 'Int64'), false) AS ifnull_int_bool;
    ```
    
    </details>
    
    ## Are there any user-facing changes?
    
    Yes. Decimal, date and timestamp results retain their types; existing
    primitive-type coercion remains unchanged.
    
    ---------
    
    Signed-off-by: 1fanwang <1f...@gmail.com>
---
 datafusion/functions/src/core/nvl.rs       | 80 ++++++++++++++++++++++++++----
 datafusion/sqllogictest/test_files/nvl.slt | 76 ++++++++++++++++++++++++++++
 2 files changed, 145 insertions(+), 11 deletions(-)

diff --git a/datafusion/functions/src/core/nvl.rs b/datafusion/functions/src/core/nvl.rs
index 1516f12ed9..393de99221 100644
--- a/datafusion/functions/src/core/nvl.rs
+++ b/datafusion/functions/src/core/nvl.rs
@@ -15,12 +15,15 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::sync::Arc;
+
 use crate::core::coalesce::CoalesceFunc;
-use arrow::datatypes::{DataType, FieldRef};
-use datafusion_common::Result;
+use arrow::datatypes::{DataType, Field, FieldRef};
+use datafusion_common::{Result, utils::take_function_args};
 use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext};
+use datafusion_expr::type_coercion::functions::fields_with_udf;
 use datafusion_expr::{
-    ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs,
+    ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF,
     ScalarUDFImpl, Signature, Volatility,
 };
 use datafusion_macros::user_doc;
@@ -59,9 +62,9 @@ pub struct NVLFunc {
     aliases: Vec<String>,
 }
 
-/// Currently supported types by the nvl/ifnull function.
-/// The order of these types correspond to the order on which coercion applies
-/// This should thus be from least informative to most informative
+/// Argument types that keep nvl's original coercion, ordered from least to
+/// most informative. Other argument types are coerced the way coalesce does,
+/// falling back to the original coercion when coalesce cannot unify them.
 static SUPPORTED_NVL_TYPES: &[DataType] = &[
     DataType::Boolean,
     DataType::UInt8,
@@ -79,6 +82,26 @@ static SUPPORTED_NVL_TYPES: &[DataType] = &[
     DataType::LargeUtf8,
 ];
 
+/// nvl's original coercion: both arguments become the first type in
+/// [`SUPPORTED_NVL_TYPES`] that both can be coerced to.
+fn uniform_coercion(arg_types: &[DataType]) -> Result<Vec<DataType>> {
+    let uniform = ScalarUDF::new_from_impl(CoalesceFunc {
+        signature: Signature::uniform(
+            2,
+            SUPPORTED_NVL_TYPES.to_vec(),
+            Volatility::Immutable,
+        ),
+    });
+    let fields: Vec<FieldRef> = arg_types
+        .iter()
+        .map(|t| Arc::new(Field::new("", t.clone(), true)))
+        .collect();
+    Ok(fields_with_udf(&fields, &uniform)?
+        .iter()
+        .map(|f| f.data_type().clone())
+        .collect())
+}
+
 impl Default for NVLFunc {
     fn default() -> Self {
         Self::new()
@@ -89,11 +112,7 @@ impl NVLFunc {
     pub fn new() -> Self {
         Self {
             coalesce: CoalesceFunc {
-                signature: Signature::uniform(
-                    2,
-                    SUPPORTED_NVL_TYPES.to_vec(),
-                    Volatility::Immutable,
-                ),
+                signature: Signature::user_defined(Volatility::Immutable),
             },
             aliases: vec![String::from("ifnull")],
         }
@@ -140,6 +159,21 @@ impl ScalarUDFImpl for NVLFunc {
         self.coalesce.short_circuits()
     }
 
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        let [_, _] = take_function_args(self.name(), arg_types)?;
+
+        // Preserve accepted pairs: (Int8, UInt64) stays Float32, and
+        // (Int64, Boolean) stays Utf8View instead of being rejected by COALESCE.
+        let listed = arg_types
+            .iter()
+            .all(|t| t.is_null() || SUPPORTED_NVL_TYPES.contains(t));
+        if !listed && let Ok(coerced) = self.coalesce.coerce_types(arg_types) {
+            return Ok(coerced);
+        }
+
+        uniform_coercion(arg_types)
+    }
+
     fn aliases(&self) -> &[String] {
         &self.aliases
     }
@@ -148,3 +182,27 @@ impl ScalarUDFImpl for NVLFunc {
         self.doc()
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use arrow::datatypes::DataType;
+
+    #[test]
+    fn rejects_wrong_argument_counts_through_public_udf() {
+        let nvl = crate::core::nvl();
+        for count in [0, 1, 3, 4, 8] {
+            let error = nvl.coerce_types(&vec![DataType::Int64; count]).unwrap_err();
+            assert_eq!(
+                error.strip_backtrace(),
+                format!(
+                    "Execution error: nvl function requires 2 arguments, got {count}"
+                )
+            );
+        }
+        assert_eq!(
+            nvl.coerce_types(&[DataType::Int64, DataType::Int64])
+                .unwrap(),
+            vec![DataType::Int64, DataType::Int64]
+        );
+    }
+}
diff --git a/datafusion/sqllogictest/test_files/nvl.slt b/datafusion/sqllogictest/test_files/nvl.slt
index a6637cadf3..27165cb618 100644
--- a/datafusion/sqllogictest/test_files/nvl.slt
+++ b/datafusion/sqllogictest/test_files/nvl.slt
@@ -183,3 +183,79 @@ physical_plan
 01)ProjectionExec: expr=[CASE WHEN __common_expr_1@0 IS NOT NULL THEN __common_expr_1@0 ELSE 9999 END as nvl(test.int_field,Int64(9999))]
 02)--ProjectionExec: expr=[CAST(int_field@0 AS Int64) as __common_expr_1]
 03)----DataSourceExec: partitions=1, partition_sizes=[1]
+
+statement ok
+CREATE TABLE nvl_type_coercion AS SELECT
+  CAST('12345678901234567890123456789012345678' AS DECIMAL(38,0)) AS big,
+  CAST(1.23 AS DECIMAL(5,2)) AS d,
+  TIMESTAMP '2024-01-01 10:00:00' AS ts,
+  DATE '2024-01-01' AS dt
+;
+
+query TR
+SELECT
+  arrow_typeof(nvl(big, 0)),
+  nvl(big, 0)
+FROM nvl_type_coercion;
+----
+Decimal128(38, 0) 12345678901234567890123456789012345678
+
+query TTT
+SELECT
+  arrow_typeof(nvl(d, d)),
+  arrow_typeof(ifnull(d, d)),
+  arrow_typeof(coalesce(d, d))
+FROM nvl_type_coercion;
+----
+Decimal128(5, 2) Decimal128(5, 2) Decimal128(5, 2)
+
+query TTT
+SELECT
+  arrow_typeof(nvl(ts, ts)),
+  arrow_typeof(ifnull(ts, ts)),
+  arrow_typeof(coalesce(ts, ts))
+FROM nvl_type_coercion;
+----
+Timestamp(ns) Timestamp(ns) Timestamp(ns)
+
+query TT
+SELECT
+  arrow_typeof(nvl(dt, dt)),
+  arrow_typeof(coalesce(dt, dt))
+FROM nvl_type_coercion;
+----
+Date32 Date32
+
+query P
+SELECT ifnull(ts, ts) + INTERVAL '1 hour' FROM nvl_type_coercion;
+----
+2024-01-01T11:00:00
+
+# Types the original signature listed keep its coercion, and types coalesce
+# cannot unify fall back to it.
+query TT
+SELECT
+  arrow_typeof(nvl(1, false)),
+  arrow_typeof(nvl(ts, '2024-01-01T00:00:00'))
+FROM nvl_type_coercion;
+----
+Utf8View Utf8View
+
+# Both names use the shared fixed-arity validation.
+query error nvl function requires 2 arguments, got 0
+SELECT nvl();
+
+query error nvl function requires 2 arguments, got 1
+SELECT nvl(1);
+
+query error nvl function requires 2 arguments, got 3
+SELECT nvl(1, 2, 3);
+
+query error nvl function requires 2 arguments, got 0
+SELECT ifnull();
+
+query error nvl function requires 2 arguments, got 1
+SELECT ifnull(1);
+
+query error nvl function requires 2 arguments, got 3
+SELECT ifnull(1, 2, 3);


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org