Skip to content

Apache DataFusion SQL Query Engine

feat: Simplify LOG and POWER functions (#5816)

Igor Izvekovea7a74665703
diff --git a/datafusion/common/src/scalar.rs b/datafusion/common/src/scalar.rs
index de11d9d106..f0e171b4d0 100644
--- a/datafusion/common/src/scalar.rs
+++ b/datafusion/common/src/scalar.rs
@@ -1705,6 +1705,28 @@ impl ScalarValue {
})
}
+ /// Create an one value in the given type.
+ pub fn new_one(datatype: &DataType) -> Result<ScalarValue> {
+ assert!(datatype.is_primitive());
+ Ok(match datatype {
+ DataType::Int8 => ScalarValue::Int8(Some(1)),
+ DataType::Int16 => ScalarValue::Int16(Some(1)),
+ DataType::Int32 => ScalarValue::Int32(Some(1)),
+ DataType::Int64 => ScalarValue::Int64(Some(1)),
+ DataType::UInt8 => ScalarValue::UInt8(Some(1)),
+ DataType::UInt16 => ScalarValue::UInt16(Some(1)),
+ DataType::UInt32 => ScalarValue::UInt32(Some(1)),
+ DataType::UInt64 => ScalarValue::UInt64(Some(1)),
+ DataType::Float32 => ScalarValue::Float32(Some(1.0)),
+ DataType::Float64 => ScalarValue::Float64(Some(1.0)),
+ _ => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Can't create an one scalar from data_type \"{datatype:?}\""
+ )));
+ }
+ })
+ }
+
/// Create a negative one value in the given type.
pub fn new_negative_one(datatype: &DataType) -> Result<ScalarValue> {
assert!(datatype.is_primitive());
@@ -1723,6 +1745,27 @@ impl ScalarValue {
})
}
+ pub fn new_ten(datatype: &DataType) -> Result<ScalarValue> {
+ assert!(datatype.is_primitive());
+ Ok(match datatype {
+ DataType::Int8 => ScalarValue::Int8(Some(10)),
+ DataType::Int16 => ScalarValue::Int16(Some(10)),
+ DataType::Int32 => ScalarValue::Int32(Some(10)),
+ DataType::Int64 => ScalarValue::Int64(Some(10)),
+ DataType::UInt8 => ScalarValue::UInt8(Some(10)),
+ DataType::UInt16 => ScalarValue::UInt16(Some(10)),
+ DataType::UInt32 => ScalarValue::UInt32(Some(10)),
+ DataType::UInt64 => ScalarValue::UInt64(Some(10)),
+ DataType::Float32 => ScalarValue::Float32(Some(10.0)),
+ DataType::Float64 => ScalarValue::Float64(Some(10.0)),
+ _ => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Can't create a negative one scalar from data_type \"{datatype:?}\""
+ )));
+ }
+ })
+ }
+
/// Getter for the `DataType` of the value
pub fn get_datatype(&self) -> DataType {
match self {
diff --git a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs
index e904f895e1..d58a6ee0c3 100644
--- a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs
+++ b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs
@@ -34,7 +34,7 @@ use datafusion_expr::{
};
use datafusion_physical_expr::{create_physical_expr, execution_props::ExecutionProps};
-use super::SimplifyInfo;
+use crate::simplify_expressions::SimplifyInfo;
/// This structure handles API for expression simplification
pub struct ExprSimplifier<S> {
@@ -1072,6 +1072,18 @@ impl<'a, S: SimplifyInfo> TreeNodeRewriter for Simplifier<'a, S> {
out_expr.rewrite(self)?
}
+ // log
+ Expr::ScalarFunction {
+ fun: BuiltinScalarFunction::Log,
+ args,
+ } => simpl_log(args, <&S>::clone(&info))?,
+
+ // power
+ Expr::ScalarFunction {
+ fun: BuiltinScalarFunction::Power,
+ args,
+ } => simpl_power(args, <&S>::clone(&info))?,
+
// concat
Expr::ScalarFunction {
fun: BuiltinScalarFunction::Concat,
@@ -2210,6 +2222,68 @@ mod tests {
assert_eq!(simplify(expr_eq), lit(true));
}
+ #[test]
+ fn test_simplify_log() {
+ // Log(c3, 1) ===> 0
+ {
+ let expr = log(col("c3_non_null"), lit(1));
+ let expected = lit(0i64);
+ assert_eq!(simplify(expr), expected);
+ }
+ // Log(c3, c3) ===> 1
+ {
+ let expr = log(col("c3_non_null"), col("c3_non_null"));
+ let expected = lit(1i64);
+ assert_eq!(simplify(expr), expected);
+ }
+ // Log(c3, Power(c3, c4)) ===> c4
+ {
+ let expr = log(
+ col("c3_non_null"),
+ power(col("c3_non_null"), col("c4_non_null")),
+ );
+ let expected = col("c4_non_null");
+ assert_eq!(simplify(expr), expected);
+ }
+ // Log(c3, c4) ===> Log(c3, c4)
+ {
+ let expr = log(col("c3_non_null"), col("c4_non_null"));
+ let expected = log(col("c3_non_null"), col("c4_non_null"));
+ assert_eq!(simplify(expr), expected);
+ }
+ }
+
+ #[test]
+ fn test_simplify_power() {
+ // Power(c3, 0) ===> 1
+ {
+ let expr = power(col("c3_non_null"), lit(0));
+ let expected = lit(1i64);
+ assert_eq!(simplify(expr), expected);
+ }
+ // Power(c3, 1) ===> c3
+ {
+ let expr = power(col("c3_non_null"), lit(1));
+ let expected = col("c3_non_null");
+ assert_eq!(simplify(expr), expected);
+ }
+ // Power(c3, Log(c3, c4)) ===> c4
+ {
+ let expr = power(
+ col("c3_non_null"),
+ log(col("c3_non_null"), col("c4_non_null")),
+ );
+ let expected = col("c4_non_null");
+ assert_eq!(simplify(expr), expected);
+ }
+ // Power(c3, c4) ===> Power(c3, c4)
+ {
+ let expr = power(col("c3_non_null"), col("c4_non_null"));
+ let expected = power(col("c3_non_null"), col("c4_non_null"));
+ assert_eq!(simplify(expr), expected);
+ }
+ }
+
#[test]
fn test_simplify_concat_ws() {
let null = lit(ScalarValue::Utf8(None));
diff --git a/datafusion/optimizer/src/simplify_expressions/utils.rs b/datafusion/optimizer/src/simplify_expressions/utils.rs
index 8b3f437dc2..a69b48a0d0 100644
--- a/datafusion/optimizer/src/simplify_expressions/utils.rs
+++ b/datafusion/optimizer/src/simplify_expressions/utils.rs
@@ -17,6 +17,7 @@
//! Utility functions for expression simplification
+use crate::simplify_expressions::SimplifyInfo;
use datafusion_common::{DataFusionError, Result, ScalarValue};
use datafusion_expr::{
expr::{Between, BinaryExpr},
@@ -350,6 +351,77 @@ pub fn distribute_negation(expr: Expr) -> Expr {
}
}
+/// Simplify the `log` function by the relevant rules:
+/// 1. Log(a, 1) ===> 0
+/// 2. Log(a, a) ===> 1
+/// 3. Log(a, Power(a, b)) ===> b
+pub fn simpl_log(current_args: Vec<Expr>, info: &dyn SimplifyInfo) -> Result<Expr> {
+ let mut number = &current_args[0];
+ let mut base = &Expr::Literal(ScalarValue::new_ten(&info.get_data_type(number)?)?);
+ if current_args.len() == 2 {
+ base = &current_args[0];
+ number = &current_args[1];
+ }
+
+ match number {
+ Expr::Literal(value)
+ if value == &ScalarValue::new_one(&info.get_data_type(number)?)? =>
+ {
+ Ok(Expr::Literal(ScalarValue::new_zero(
+ &info.get_data_type(base)?,
+ )?))
+ }
+ Expr::ScalarFunction {
+ fun: BuiltinScalarFunction::Power,
+ args,
+ } if base == &args[0] => Ok(args[1].clone()),
+ _ => {
+ if number == base {
+ Ok(Expr::Literal(ScalarValue::new_one(
+ &info.get_data_type(number)?,
+ )?))
+ } else {
+ Ok(Expr::ScalarFunction {
+ fun: BuiltinScalarFunction::Log,
+ args: vec![base.clone(), number.clone()],
+ })
+ }
+ }
+ }
+}
+
+/// Simplify the `power` function by the relevant rules:
+/// 1. Power(a, 0) ===> 0
+/// 2. Power(a, 1) ===> a
+/// 3. Power(a, Log(a, b)) ===> b
+pub fn simpl_power(current_args: Vec<Expr>, info: &dyn SimplifyInfo) -> Result<Expr> {
+ let base = &current_args[0];
+ let exponent = &current_args[1];
+
+ match exponent {
+ Expr::Literal(value)
+ if value == &ScalarValue::new_zero(&info.get_data_type(exponent)?)? =>
+ {
+ Ok(Expr::Literal(ScalarValue::new_one(
+ &info.get_data_type(base)?,
+ )?))
+ }
+ Expr::Literal(value)
+ if value == &ScalarValue::new_one(&info.get_data_type(exponent)?)? =>
+ {
+ Ok(base.clone())
+ }
+ Expr::ScalarFunction {
+ fun: BuiltinScalarFunction::Log,
+ args,
+ } if base == &args[0] => Ok(args[1].clone()),
+ _ => Ok(Expr::ScalarFunction {
+ fun: BuiltinScalarFunction::Power,
+ args: current_args,
+ }),
+ }
+}
+
/// Simplify the `concat` function by
/// 1. filtering out all `null` literals
/// 2. concatenating contiguous literal arguments