Skip to content

Apache DataFusion SQL Query Engine

feat: LCM, GCD and Factorial (#6149)

Igor Izvekov7360260be8d8
diff --git a/datafusion/core/tests/sqllogictests/test_files/scalar.slt b/datafusion/core/tests/sqllogictests/test_files/scalar.slt
index 8b8ad80d5a..29801ea424 100644
--- a/datafusion/core/tests/sqllogictests/test_files/scalar.slt
+++ b/datafusion/core/tests/sqllogictests/test_files/scalar.slt
@@ -215,6 +215,18 @@ select exp(null);
----
NULL
+# factorial scalar function
+query III rowsort
+select factorial(0), factorial(10), factorial(15);
+----
+1 3628800 1307674368000
+
+# factorial scalar nulls
+query I rowsort
+select factorial(null);
+----
+NULL
+
# floor scalar function
query RRR rowsort
select floor(1.4), floor(1.5), floor(1.6);
@@ -227,6 +239,54 @@ select floor(null);
----
NULL
+# gcd scalar function
+query III rowsort
+select gcd(0, 0), gcd(2, 3), gcd(15, 10);
+----
+0 1 5
+
+# gcd scalar nulls
+query I rowsort
+select gcd(null, 64);
+----
+NULL
+
+# gcd scalar nulls 1
+query I rowsort
+select gcd(2, null);
+----
+NULL
+
+# gcd scalar nulls 2
+query I rowsort
+select gcd(null, null);
+----
+NULL
+
+# lcm scalar function
+query III rowsort
+select lcm(0, 0), lcm(2, 3), lcm(15, 10);
+----
+0 6 30
+
+# lcm scalar nulls
+query I rowsort
+select lcm(null, 64);
+----
+NULL
+
+# lcm scalar nulls 1
+query I rowsort
+select lcm(2, null);
+----
+NULL
+
+# lcm scalar nulls 2
+query I rowsort
+select lcm(null, null);
+----
+NULL
+
# ln scalar function
query RRR rowsort
select ln(1), ln(exp(1)), ln(3);
diff --git a/datafusion/expr/src/built_in_function.rs b/datafusion/expr/src/built_in_function.rs
index 524fe23a32..6633e4c0a9 100644
--- a/datafusion/expr/src/built_in_function.rs
+++ b/datafusion/expr/src/built_in_function.rs
@@ -58,8 +58,14 @@ pub enum BuiltinScalarFunction {
Digest,
/// exp
Exp,
+ /// factorial
+ Factorial,
/// floor
Floor,
+ /// gcd, Greatest common divisor
+ Gcd,
+ /// lcm, Least common multiple
+ Lcm,
/// ln, Natural logarithm
Ln,
/// log, same as log10
@@ -228,7 +234,10 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::Cosh => Volatility::Immutable,
BuiltinScalarFunction::Degrees => Volatility::Immutable,
BuiltinScalarFunction::Exp => Volatility::Immutable,
+ BuiltinScalarFunction::Factorial => Volatility::Immutable,
BuiltinScalarFunction::Floor => Volatility::Immutable,
+ BuiltinScalarFunction::Gcd => Volatility::Immutable,
+ BuiltinScalarFunction::Lcm => Volatility::Immutable,
BuiltinScalarFunction::Ln => Volatility::Immutable,
BuiltinScalarFunction::Log => Volatility::Immutable,
BuiltinScalarFunction::Log10 => Volatility::Immutable,
@@ -331,7 +340,10 @@ impl FromStr for BuiltinScalarFunction {
"cosh" => BuiltinScalarFunction::Cosh,
"degrees" => BuiltinScalarFunction::Degrees,
"exp" => BuiltinScalarFunction::Exp,
+ "factorial" => BuiltinScalarFunction::Factorial,
"floor" => BuiltinScalarFunction::Floor,
+ "gcd" => BuiltinScalarFunction::Gcd,
+ "lcm" => BuiltinScalarFunction::Lcm,
"ln" => BuiltinScalarFunction::Ln,
"log" => BuiltinScalarFunction::Log,
"log10" => BuiltinScalarFunction::Log10,
diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rs
index a9c0b1fcaf..86984c7b46 100644
--- a/datafusion/expr/src/expr_fn.rs
+++ b/datafusion/expr/src/expr_fn.rs
@@ -474,6 +474,7 @@ scalar_expr!(Atan, atan, num, "inverse tangent");
scalar_expr!(Asinh, asinh, num, "inverse hyperbolic sine");
scalar_expr!(Acosh, acosh, num, "inverse hyperbolic cosine");
scalar_expr!(Atanh, atanh, num, "inverse hyperbolic tangent");
+scalar_expr!(Factorial, factorial, num, "factorial");
scalar_expr!(
Floor,
floor,
@@ -493,6 +494,8 @@ scalar_expr!(Trunc, trunc, num, "truncate toward zero");
scalar_expr!(Abs, abs, num, "absolute value");
scalar_expr!(Signum, signum, num, "sign of the argument (-1, 0, +1) ");
scalar_expr!(Exp, exp, num, "exponential");
+scalar_expr!(Gcd, gcd, arg_1 arg_2, "greatest common divisor");
+scalar_expr!(Lcm, lcm, arg_1 arg_2, "least common multiple");
scalar_expr!(Log2, log2, num, "base 2 logarithm");
scalar_expr!(Log10, log10, num, "base 10 logarithm");
scalar_expr!(Ln, ln, num, "natural logarithm");
@@ -797,6 +800,7 @@ mod test {
test_unary_scalar_expr!(Asinh, asinh);
test_unary_scalar_expr!(Acosh, acosh);
test_unary_scalar_expr!(Atanh, atanh);
+ test_unary_scalar_expr!(Factorial, factorial);
test_unary_scalar_expr!(Floor, floor);
test_unary_scalar_expr!(Ceil, ceil);
test_unary_scalar_expr!(Degrees, degrees);
@@ -819,6 +823,8 @@ mod test {
test_scalar_expr!(CharacterLength, character_length, string);
test_scalar_expr!(Chr, chr, string);
test_scalar_expr!(Digest, digest, string, algorithm);
+ test_scalar_expr!(Gcd, gcd, arg_1, arg_2);
+ test_scalar_expr!(Lcm, lcm, arg_1, arg_2);
test_scalar_expr!(InitCap, initcap, string);
test_scalar_expr!(Left, left, string, count);
test_scalar_expr!(Lower, lower, string);
diff --git a/datafusion/expr/src/function.rs b/datafusion/expr/src/function.rs
index 69d274f379..fa3d94cbff 100644
--- a/datafusion/expr/src/function.rs
+++ b/datafusion/expr/src/function.rs
@@ -257,6 +257,10 @@ pub fn return_type(
}
}),
+ BuiltinScalarFunction::Factorial
+ | BuiltinScalarFunction::Gcd
+ | BuiltinScalarFunction::Lcm => Ok(DataType::Int64),
+
BuiltinScalarFunction::Power => match &input_expr_types[0] {
DataType::Int64 => Ok(DataType::Int64),
_ => Ok(DataType::Float64),
@@ -673,6 +677,12 @@ pub fn signature(fun: &BuiltinScalarFunction) -> Signature {
],
fun.volatility(),
),
+ BuiltinScalarFunction::Factorial => {
+ Signature::uniform(1, vec![DataType::Int64], fun.volatility())
+ }
+ BuiltinScalarFunction::Gcd | BuiltinScalarFunction::Lcm => {
+ Signature::uniform(2, vec![DataType::Int64], fun.volatility())
+ }
BuiltinScalarFunction::ArrowTypeof => Signature::any(1, fun.volatility()),
BuiltinScalarFunction::Abs
| BuiltinScalarFunction::Acos
diff --git a/datafusion/physical-expr/src/functions.rs b/datafusion/physical-expr/src/functions.rs
index 352ec08166..2dbf4559dd 100644
--- a/datafusion/physical-expr/src/functions.rs
+++ b/datafusion/physical-expr/src/functions.rs
@@ -347,7 +347,16 @@ pub fn create_physical_fun(
BuiltinScalarFunction::Cosh => Arc::new(math_expressions::cosh),
BuiltinScalarFunction::Degrees => Arc::new(math_expressions::to_degrees),
BuiltinScalarFunction::Exp => Arc::new(math_expressions::exp),
+ BuiltinScalarFunction::Factorial => {
+ Arc::new(|args| make_scalar_function(math_expressions::factorial)(args))
+ }
BuiltinScalarFunction::Floor => Arc::new(math_expressions::floor),
+ BuiltinScalarFunction::Gcd => {
+ Arc::new(|args| make_scalar_function(math_expressions::gcd)(args))
+ }
+ BuiltinScalarFunction::Lcm => {
+ Arc::new(|args| make_scalar_function(math_expressions::lcm)(args))
+ }
BuiltinScalarFunction::Ln => Arc::new(math_expressions::ln),
BuiltinScalarFunction::Log10 => Arc::new(math_expressions::log10),
BuiltinScalarFunction::Log2 => Arc::new(math_expressions::log2),
diff --git a/datafusion/physical-expr/src/math_expressions.rs b/datafusion/physical-expr/src/math_expressions.rs
index 1af9f29805..fbfb82814e 100644
--- a/datafusion/physical-expr/src/math_expressions.rs
+++ b/datafusion/physical-expr/src/math_expressions.rs
@@ -27,6 +27,7 @@ use datafusion_expr::ColumnarValue;
use rand::{thread_rng, Rng};
use std::any::type_name;
use std::iter;
+use std::mem::swap;
use std::sync::Arc;
macro_rules! downcast_compute_op {
@@ -167,6 +168,98 @@ math_unary_function!("log10", log10);
math_unary_function!("degrees", to_degrees);
math_unary_function!("radians", to_radians);
+/// Factorial SQL function
+pub fn factorial(args: &[ArrayRef]) -> Result<ArrayRef> {
+ match args[0].data_type() {
+ DataType::Int64 => Ok(Arc::new(make_function_scalar_inputs!(
+ &args[0],
+ "value",
+ Int64Array,
+ { |value: i64| { (1..=value).product() } }
+ )) as ArrayRef),
+ other => Err(DataFusionError::Internal(format!(
+ "Unsupported data type {other:?} for function factorial."
+ ))),
+ }
+}
+
+/// Computes greatest common divisor using Binary GCD algorithm.
+fn compute_gcd(x: i64, y: i64) -> i64 {
+ let mut a = x.wrapping_abs();
+ let mut b = y.wrapping_abs();
+
+ if a == 0 {
+ return b;
+ }
+ if b == 0 {
+ return a;
+ }
+
+ let shift = (a | b).trailing_zeros();
+ a >>= shift;
+ b >>= shift;
+ a >>= a.trailing_zeros();
+
+ loop {
+ b >>= b.trailing_zeros();
+ if a > b {
+ swap(&mut a, &mut b);
+ }
+
+ b -= a;
+
+ if b == 0 {
+ return a << shift;
+ }
+ }
+}
+
+/// Gcd SQL function
+pub fn gcd(args: &[ArrayRef]) -> Result<ArrayRef> {
+ match args[0].data_type() {
+ DataType::Int64 => Ok(Arc::new(make_function_inputs2!(
+ &args[0],
+ &args[1],
+ "x",
+ "y",
+ Int64Array,
+ Int64Array,
+ { compute_gcd }
+ )) as ArrayRef),
+ other => Err(DataFusionError::Internal(format!(
+ "Unsupported data type {other:?} for function gcd"
+ ))),
+ }
+}
+
+/// Lcm SQL function
+pub fn lcm(args: &[ArrayRef]) -> Result<ArrayRef> {
+ let compute_lcm = |x: i64, y: i64| {
+ let a = x.wrapping_abs();
+ let b = y.wrapping_abs();
+
+ if a == 0 || b == 0 {
+ return 0;
+ }
+ a / compute_gcd(a, b) * b
+ };
+
+ match args[0].data_type() {
+ DataType::Int64 => Ok(Arc::new(make_function_inputs2!(
+ &args[0],
+ &args[1],
+ "x",
+ "y",
+ Int64Array,
+ Int64Array,
+ { compute_lcm }
+ )) as ArrayRef),
+ other => Err(DataFusionError::Internal(format!(
+ "Unsupported data type {other:?} for function lcm"
+ ))),
+ }
+}
+
/// Pi SQL function
pub fn pi(args: &[ColumnarValue]) -> Result<ColumnarValue> {
if !matches!(&args[0], ColumnarValue::Array(_)) {
@@ -597,4 +690,53 @@ mod tests {
assert_eq!(floats, &expected);
}
+
+ #[test]
+ fn test_factorial_i64() {
+ let args: Vec<ArrayRef> = vec![
+ Arc::new(Int64Array::from(vec![0, 1, 2, 4])), // input
+ ];
+
+ let result = factorial(&args).expect("failed to initialize function factorial");
+ let ints =
+ as_int64_array(&result).expect("failed to initialize function factorial");
+
+ let expected = Int64Array::from(vec![1, 1, 2, 24]);
+
+ assert_eq!(ints, &expected);
+ }
+
+ #[test]
+ fn test_gcd_i64() {
+ let args: Vec<ArrayRef> = vec![
+ Arc::new(Int64Array::from(vec![0, 3, 25, -16])), // x
+ Arc::new(Int64Array::from(vec![0, -2, 15, 8])), // y
+ ];
+
+ let result = gcd(&args).expect("failed to initialize function gcd");
+ let ints = as_int64_array(&result).expect("failed to initialize function gcd");
+
+ assert_eq!(ints.len(), 4);
+ assert_eq!(ints.value(0), 0);
+ assert_eq!(ints.value(1), 1);
+ assert_eq!(ints.value(2), 5);
+ assert_eq!(ints.value(3), 8);
+ }
+
+ #[test]
+ fn test_lcm_i64() {
+ let args: Vec<ArrayRef> = vec![
+ Arc::new(Int64Array::from(vec![0, 3, 25, -16])), // x
+ Arc::new(Int64Array::from(vec![0, -2, 15, 8])), // y
+ ];
+
+ let result = lcm(&args).expect("failed to initialize function lcm");
+ let ints = as_int64_array(&result).expect("failed to initialize function lcm");
+
+ assert_eq!(ints.len(), 4);
+ assert_eq!(ints.value(0), 0);
+ assert_eq!(ints.value(1), 6);
+ assert_eq!(ints.value(2), 75);
+ assert_eq!(ints.value(3), 16);
+ }
}
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 7d02fda86c..f2a6176bf2 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -534,6 +534,9 @@ enum ScalarFunction {
Pi = 80;
Degrees = 81;
Radians = 82;
+ Factorial = 83;
+ Lcm = 84;
+ Gcd = 85;
}
message ScalarFunctionNode {
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index 553f3f2911..405fa04bce 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -17340,6 +17340,9 @@ impl serde::Serialize for ScalarFunction {
Self::Pi => "Pi",
Self::Degrees => "Degrees",
Self::Radians => "Radians",
+ Self::Factorial => "Factorial",
+ Self::Lcm => "Lcm",
+ Self::Gcd => "Gcd",
};
serializer.serialize_str(variant)
}
@@ -17434,6 +17437,9 @@ impl<'de> serde::Deserialize<'de> for ScalarFunction {
"Pi",
"Degrees",
"Radians",
+ "Factorial",
+ "Lcm",
+ "Gcd",
];
struct GeneratedVisitor;
@@ -17559,6 +17565,9 @@ impl<'de> serde::Deserialize<'de> for ScalarFunction {
"Pi" => Ok(ScalarFunction::Pi),
"Degrees" => Ok(ScalarFunction::Degrees),
"Radians" => Ok(ScalarFunction::Radians),
+ "Factorial" => Ok(ScalarFunction::Factorial),
+ "Lcm" => Ok(ScalarFunction::Lcm),
+ "Gcd" => Ok(ScalarFunction::Gcd),
_ => Err(serde::de::Error::unknown_variant(value, FIELDS)),
}
}
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index fd3cdc1292..58cc0b312a 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -2167,6 +2167,9 @@ pub enum ScalarFunction {
Pi = 80,
Degrees = 81,
Radians = 82,
+ Factorial = 83,
+ Lcm = 84,
+ Gcd = 85,
}
impl ScalarFunction {
/// String value of the enum field names used in the ProtoBuf definition.
@@ -2258,6 +2261,9 @@ impl ScalarFunction {
ScalarFunction::Pi => "Pi",
ScalarFunction::Degrees => "Degrees",
ScalarFunction::Radians => "Radians",
+ ScalarFunction::Factorial => "Factorial",
+ ScalarFunction::Lcm => "Lcm",
+ ScalarFunction::Gcd => "Gcd",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -2346,6 +2352,9 @@ impl ScalarFunction {
"Pi" => Some(Self::Pi),
"Degrees" => Some(Self::Degrees),
"Radians" => Some(Self::Radians),
+ "Factorial" => Some(Self::Factorial),
+ "Lcm" => Some(Self::Lcm),
+ "Gcd" => Some(Self::Gcd),
_ => None,
}
}
diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rs
index c66fbc0e7d..23fae1cd1d 100644
--- a/datafusion/proto/src/logical_plan/from_proto.rs
+++ b/datafusion/proto/src/logical_plan/from_proto.rs
@@ -39,7 +39,7 @@ use datafusion_expr::{
cbrt, ceil, character_length, chr, coalesce, concat_expr, concat_ws_expr, cos, cosh,
date_bin, date_part, date_trunc, degrees, digest, exp,
expr::{self, Sort, WindowFunction},
- floor, from_unixtime, left, ln, log, log10, log2,
+ factorial, floor, from_unixtime, gcd, lcm, left, ln, log, log10, log2,
logical_plan::{PlanType, StringifiedPlan},
lower, lpad, ltrim, md5, now, nullif, octet_length, pi, power, radians, random,
regexp_match, regexp_replace, repeat, replace, reverse, right, round, rpad, rtrim,
@@ -427,6 +427,9 @@ impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction {
ScalarFunction::Log10 => Self::Log10,
ScalarFunction::Degrees => Self::Degrees,
ScalarFunction::Radians => Self::Radians,
+ ScalarFunction::Factorial => Self::Factorial,
+ ScalarFunction::Gcd => Self::Gcd,
+ ScalarFunction::Lcm => Self::Lcm,
ScalarFunction::Floor => Self::Floor,
ScalarFunction::Ceil => Self::Ceil,
ScalarFunction::Round => Self::Round,
@@ -1165,6 +1168,9 @@ pub fn parse_expr(
ScalarFunction::Ln => Ok(ln(parse_expr(&args[0], registry)?)),
ScalarFunction::Log10 => Ok(log10(parse_expr(&args[0], registry)?)),
ScalarFunction::Floor => Ok(floor(parse_expr(&args[0], registry)?)),
+ ScalarFunction::Factorial => {
+ Ok(factorial(parse_expr(&args[0], registry)?))
+ }
ScalarFunction::Ceil => Ok(ceil(parse_expr(&args[0], registry)?)),
ScalarFunction::Round => Ok(round(
args.to_owned()
@@ -1218,6 +1224,14 @@ pub fn parse_expr(
}
ScalarFunction::Chr => Ok(chr(parse_expr(&args[0], registry)?)),
ScalarFunction::InitCap => Ok(ascii(parse_expr(&args[0], registry)?)),
+ ScalarFunction::Gcd => Ok(gcd(
+ parse_expr(&args[0], registry)?,
+ parse_expr(&args[1], registry)?,
+ )),
+ ScalarFunction::Lcm => Ok(lcm(
+ parse_expr(&args[0], registry)?,
+ parse_expr(&args[1], registry)?,
+ )),
ScalarFunction::Left => Ok(left(
parse_expr(&args[0], registry)?,
parse_expr(&args[1], registry)?,
diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rs
index 1897be4dba..64735568b4 100644
--- a/datafusion/proto/src/logical_plan/to_proto.rs
+++ b/datafusion/proto/src/logical_plan/to_proto.rs
@@ -1277,6 +1277,9 @@ impl TryFrom<&BuiltinScalarFunction> for protobuf::ScalarFunction {
BuiltinScalarFunction::Acosh => Self::Acosh,
BuiltinScalarFunction::Atanh => Self::Atanh,
BuiltinScalarFunction::Exp => Self::Exp,
+ BuiltinScalarFunction::Factorial => Self::Factorial,
+ BuiltinScalarFunction::Gcd => Self::Gcd,
+ BuiltinScalarFunction::Lcm => Self::Lcm,
BuiltinScalarFunction::Log => Self::Log,
BuiltinScalarFunction::Ln => Self::Ln,
BuiltinScalarFunction::Log10 => Self::Log10,
diff --git a/docs/source/user-guide/expressions.md b/docs/source/user-guide/expressions.md
index 0a8bef345f..e250dc4bb6 100644
--- a/docs/source/user-guide/expressions.md
+++ b/docs/source/user-guide/expressions.md
@@ -91,7 +91,10 @@ expressions such as `col("a") + col("b")` to be used.
| cosh(x) | hyperbolic cosine |
| degrees(x) | converts radians to degrees |
| exp(x) | exponential |
+| factorial(x) | factorial |
| floor(x) | nearest integer less than or equal to argument |
+| gcd(x, y) | greatest common divisor |
+| lcm(x, y) | least common multiple |
| ln(x) | natural logarithm |
| log(base, x) | logarithm of x for a particular base |
| log10(x) | base 10 logarithm |
diff --git a/docs/source/user-guide/sql/scalar_functions.md b/docs/source/user-guide/sql/scalar_functions.md
index 8c217b3790..cbf9e2fa18 100644
--- a/docs/source/user-guide/sql/scalar_functions.md
+++ b/docs/source/user-guide/sql/scalar_functions.md
@@ -35,7 +35,10 @@
- [cosh](#cosh)
- [degrees](#degrees)
- [exp](#exp)
+- [factorial](#factorial)
- [floor](#floor)
+- [gcd](#gcd)
+- [lcm](#lcm)
- [ln](#ln)
- [log](#log)
- [log10](#log10)
@@ -238,6 +241,19 @@ exp(numeric_expression)
- **numeric_expression**: Numeric expression to use as the exponent.
Can be a constant, column, or function, and any combination of arithmetic operators.
+### `factorial`
+
+Factorial. Returns 1 if value is less than 2.
+
+```
+factorial(numeric_expression)
+```
+
+#### Arguments
+
+- **numeric_expression**: Numeric expression to operate on.
+ Can be a constant, column, or function, and any combination of arithmetic operators.
+
### `floor`
Returns the nearest integer less than or equal to a number.
@@ -251,6 +267,36 @@ floor(numeric_expression)
- **numeric_expression**: Numeric expression to operate on.
Can be a constant, column, or function, and any combination of arithmetic operators.
+### `gcd`
+
+Returns the greatest common divisor of `expression_x` and `expression_y`. Returns 0 if both inputs are zero.
+
+```
+gcd(expression_x, expression_y)
+```
+
+#### Arguments
+
+- **expression_x**: First numeric expression to operate on.
+ Can be a constant, column, or function, and any combination of arithmetic operators.
+- **expression_y**: Second numeric expression to operate on.
+ Can be a constant, column, or function, and any combination of arithmetic operators.
+
+### `lcm`
+
+Returns the least common multiple of `expression_x` and `expression_y`. Returns 0 if either input is zero.
+
+```
+lcm(expression_x, expression_y)
+```
+
+#### Arguments
+
+- **expression_x**: First numeric expression to operate on.
+ Can be a constant, column, or function, and any combination of arithmetic operators.
+- **expression_y**: Second numeric expression to operate on.
+ Can be a constant, column, or function, and any combination of arithmetic operators.
+
### `ln`
Returns the natural logarithm of a number.