Skip to content

Apache DataFusion SQL Query Engine

fixing factorial negative values (#22278)

Raushan Prabhakar2d1d53e2afe1
diff --git a/datafusion/functions/src/math/factorial.rs b/datafusion/functions/src/math/factorial.rs
index b4c41838e1..3b4f973f19 100644
--- a/datafusion/functions/src/math/factorial.rs
+++ b/datafusion/functions/src/math/factorial.rs
@@ -32,7 +32,7 @@ use datafusion_macros::user_doc;
#[user_doc(
doc_section(label = "Math Functions"),
- description = "Factorial. Returns 1 if value is less than 2.",
+ description = "Factorial of a non-negative integer. Errors if the argument is negative or the result overflows.",
syntax_example = "factorial(numeric_expression)",
sql_example = r#"```sql
> SELECT factorial(5);
@@ -143,7 +143,7 @@ const FACTORIALS: [i64; 21] = [
fn compute_factorial(n: i64) -> Result<i64> {
if n < 0 {
- Ok(1)
+ exec_err!("factorial of a negative number is undefined")
} else if n < FACTORIALS.len() as i64 {
Ok(FACTORIALS[n as usize])
} else {
diff --git a/datafusion/sqllogictest/test_files/math.slt b/datafusion/sqllogictest/test_files/math.slt
index e00edf47c1..8f7245365f 100644
--- a/datafusion/sqllogictest/test_files/math.slt
+++ b/datafusion/sqllogictest/test_files/math.slt
@@ -826,6 +826,10 @@ select
----
39 Decimal128(2, 1)
+# factorial negative (PostgreSQL-compatible domain error)
+query error DataFusion error: Execution error: factorial of a negative number is undefined
+select factorial(-1);
+
# factorial overflow
query error DataFusion error: Execution error: Overflow happened on FACTORIAL\(350943270\)
select FACTORIAL(350943270);
diff --git a/docs/source/user-guide/sql/scalar_functions.md b/docs/source/user-guide/sql/scalar_functions.md
index 7010a2b7c1..4786163cb5 100644
--- a/docs/source/user-guide/sql/scalar_functions.md
+++ b/docs/source/user-guide/sql/scalar_functions.md
@@ -420,7 +420,7 @@ exp(numeric_expression)
### `factorial`
-Factorial. Returns 1 if value is less than 2.
+Factorial of a non-negative integer. Errors if the argument is negative or the result overflows.
```sql
factorial(numeric_expression)