diff --git a/datafusion/functions/src/math/mod.rs b/datafusion/functions/src/math/mod.rs index 1754ccb43488a..1df52e16656b1 100644 --- a/datafusion/functions/src/math/mod.rs +++ b/datafusion/functions/src/math/mod.rs @@ -51,6 +51,16 @@ fn validate_sqrt_input(value: f64) -> Result<()> { } } +fn validate_ln_input(value: f64) -> Result<()> { + if value < 0.0 { + exec_err!("cannot take logarithm of a negative number") + } else if value == 0.0 { + exec_err!("cannot take logarithm of zero") + } else { + Ok(()) + } +} + // Create UDFs make_udf_function!(abs::AbsFunc, abs); make_math_unary_udf!( @@ -163,7 +173,8 @@ make_math_unary_udf!( ln, super::ln_order, super::bounds::unbounded_bounds, - super::get_ln_doc + super::get_ln_doc, + Some(super::validate_ln_input) ); make_math_unary_udf!( Log2Func, diff --git a/datafusion/sqllogictest/test_files/scalar.slt b/datafusion/sqllogictest/test_files/scalar.slt index 9dbf8f16d85ab..d25ac6ac8e242 100644 --- a/datafusion/sqllogictest/test_files/scalar.slt +++ b/datafusion/sqllogictest/test_files/scalar.slt @@ -593,21 +593,23 @@ select ln(null); ---- NULL -# ln scalar ops with zero edgecases -# please see https://github.com/apache/datafusion/pull/5245#issuecomment-1426828382 -query R rowsort +# ln(0) errors to match PostgreSQL behavior (issue #22271) +statement error cannot take logarithm of zero select ln(0); ----- --Infinity -# ln with columns (round is needed to normalize the outputs of different operating systems) +# ln of negative numbers errors to match PostgreSQL behavior (issue #22271) +statement error cannot take logarithm of a negative number +select ln(-1.0::double); + +statement error cannot take logarithm of a negative number +select ln(-0.5::double); + +# ln with positive values (array path) query RRR rowsort -select round(ln(a), 5), round(ln(b), 5), round(ln(c), 5) from signed_integers; +select round(ln(a::double), 5), round(ln(b::double), 5), round(ln(c::double), 5) +from (values (1, 2, 100)) as t(a, b, c); ---- -0.69315 NaN 4.81218 -1.38629 NULL NULL -NaN 4.60517 NaN -NaN 9.21034 NaN +0 0.69315 4.60517 ## log