Skip to content

Apache DataFusion SQL Query Engine

fix nth_value window function negates i64::MIN (#22304)

Zhen Chene2db7668f621
diff --git a/datafusion/functions-window/src/nth_value.rs b/datafusion/functions-window/src/nth_value.rs
index 437b4ecdb3..df72377216 100644
--- a/datafusion/functions-window/src/nth_value.rs
+++ b/datafusion/functions-window/src/nth_value.rs
@@ -125,6 +125,14 @@ impl NthValue {
}
}
+fn validate_nth_value_n(n: i64) -> Result<i64> {
+ if n == i64::MIN {
+ return exec_err!("The second argument of nth_value must not be i64::MIN");
+ }
+
+ Ok(n)
+}
+
static FIRST_VALUE_DOCUMENTATION: LazyLock<Documentation> = LazyLock::new(|| {
Documentation::builder(
DOC_SECTION_ANALYTICAL,
@@ -287,6 +295,7 @@ impl WindowUDFImpl for NthValue {
.map(|v| get_signed_integer(&v))
{
Some(Ok(n)) => {
+ let n = validate_nth_value_n(n)?;
if partition_evaluator_args.is_reversed() {
-n
} else {
@@ -660,4 +669,24 @@ mod tests {
)?;
Ok(())
}
+
+ #[test]
+ fn nth_value_i64_min_returns_error() {
+ let expr = Arc::new(Column::new("c3", 0)) as Arc<dyn PhysicalExpr>;
+ let n_value = Arc::new(Literal::new(ScalarValue::Int64(Some(i64::MIN))))
+ as Arc<dyn PhysicalExpr>;
+
+ let err = NthValue::nth()
+ .partition_evaluator(PartitionEvaluatorArgs::new(
+ &[expr, n_value],
+ &[Field::new("f", DataType::Int32, true).into()],
+ false,
+ false,
+ ))
+ .unwrap_err();
+
+ assert!(err.to_string().starts_with(
+ "Execution error: The second argument of nth_value must not be i64::MIN"
+ ));
+ }
}
diff --git a/datafusion/sqllogictest/test_files/window.slt b/datafusion/sqllogictest/test_files/window.slt
index 1c614f6a22..bc2f1bfcbc 100644
--- a/datafusion/sqllogictest/test_files/window.slt
+++ b/datafusion/sqllogictest/test_files/window.slt
@@ -1215,6 +1215,10 @@ NULL 3917
-1114 -1114
15673 15673
+statement error Execution error: The second argument of nth_value must not be i64::MIN
+SELECT nth_value(x, -9223372036854775808) OVER (ORDER BY x)
+FROM (VALUES (1)) AS t(x);
+