This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.0 by this push:
new cbe11335daf branch-4.0: [Enhancement] support simple sql function for
factorial(from Hive) #57144 (#57878)
cbe11335daf is described below
commit cbe11335dafc0cac8b2e974135bfbb1ea4c47baf
Author: github-actions[bot]
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Tue Nov 11 09:24:36 2025 +0800
branch-4.0: [Enhancement] support simple sql function for factorial(from
Hive) #57144 (#57878)
Cherry-picked from #57144
Co-authored-by: K_handle_Y <[email protected]>
---
be/src/vec/functions/math.cpp | 69 ++++++++++++++++++++
be/test/vec/function/function_math_test.cpp | 28 +++++++++
.../doris/catalog/BuiltinScalarFunctions.java | 2 +
.../functions/executable/NumericArithmetic.java | 13 ++++
.../expressions/functions/scalar/Factorial.java | 73 ++++++++++++++++++++++
.../expressions/visitor/ScalarFunctionVisitor.java | 5 ++
.../test_math_unary_always_nullable.out | 38 +++++++++++
.../fold_constant_numeric_arithmatic.groovy | 10 +++
.../test_math_unary_always_nullable.groovy | 43 +++++++++++++
9 files changed, 281 insertions(+)
diff --git a/be/src/vec/functions/math.cpp b/be/src/vec/functions/math.cpp
index 87117b80f2c..33c50114c17 100644
--- a/be/src/vec/functions/math.cpp
+++ b/be/src/vec/functions/math.cpp
@@ -388,6 +388,74 @@ double csc(double x) {
}
using FunctionCosec = FunctionMathUnary<UnaryFunctionPlain<CscName, csc>>;
+static const Int64 FACT_TABLE[] = {1LL,
+ 1LL,
+ 2LL,
+ 6LL,
+ 24LL,
+ 120LL,
+ 720LL,
+ 5040LL,
+ 40320LL,
+ 362880LL,
+ 3628800LL,
+ 39916800LL,
+ 479001600LL,
+ 6227020800LL,
+ 87178291200LL,
+ 1307674368000LL,
+ 20922789888000LL,
+ 355687428096000LL,
+ 6402373705728000LL,
+ 121645100408832000LL,
+ 2432902008176640000LL};
+
+class FunctionFactorial : public IFunction {
+public:
+ static constexpr auto name = "factorial";
+ static FunctionPtr create() { return
std::make_shared<FunctionFactorial>(); }
+
+private:
+ String get_name() const override { return name; }
+ size_t get_number_of_arguments() const override { return 1; }
+
+ DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
+ return make_nullable(std::make_shared<DataTypeInt64>());
+ }
+
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ const auto* data_col =
+
check_and_get_column<ColumnInt64>(block.get_by_position(arguments[0]).column.get());
+ if (!data_col) {
+ return Status::InternalError(
+ "Unexpected column '%s' for argument of function %s",
+
block.get_by_position(arguments[0]).column->get_name().c_str(), get_name());
+ }
+
+ auto result_column = ColumnInt64::create(input_rows_count);
+ auto result_null_map = ColumnUInt8::create(input_rows_count, 0);
+ auto& result_data = result_column->get_data();
+ auto& result_null_map_data = result_null_map->get_data();
+
+ const auto& src_data = data_col->get_data();
+ for (size_t i = 0; i < input_rows_count; ++i) {
+ Int64 n = src_data[i];
+ if (n < 0 || n > 20) {
+ result_null_map_data[i] = 1;
+ result_data[i] = 0;
+ } else {
+ result_data[i] = FACT_TABLE[n];
+ }
+ }
+
+ block.replace_by_position(result,
ColumnNullable::create(std::move(result_column),
+
std::move(result_null_map)));
+
+ return Status::OK();
+ }
+};
+
template <typename A>
struct RadiansImpl {
static constexpr PrimitiveType ResultType =
ResultOfUnaryFunc<A>::ResultType;
@@ -859,6 +927,7 @@ void register_function_math(SimpleFunctionFactory& factory)
{
factory.register_alias("pow", "fpow");
factory.register_function<FunctionExp>();
factory.register_alias("exp", "dexp");
+ factory.register_function<FunctionFactorial>();
factory.register_function<FunctionRadians>();
factory.register_function<FunctionDegrees>();
factory.register_function<FunctionBin>();
diff --git a/be/test/vec/function/function_math_test.cpp
b/be/test/vec/function/function_math_test.cpp
index 6687145d34f..d28fd69be5a 100644
--- a/be/test/vec/function/function_math_test.cpp
+++ b/be/test/vec/function/function_math_test.cpp
@@ -911,4 +911,32 @@ TEST(MathFunctionTest, isinf_test) {
}
}
+TEST(MathFunctionTest, factorial_test) {
+ std::string func_name = "factorial"; // factorial(x), x ∈ [0, 20]
+
+ {
+ InputTypeSet input_types = {PrimitiveType::TYPE_BIGINT};
+
+ DataSet data_set = {{{BIGINT(0)}, BIGINT(1)}, {{BIGINT(1)},
BIGINT(1)},
+ {{BIGINT(5)}, BIGINT(120)}, {{BIGINT(20)},
BIGINT(2432902008176640000)},
+ {{BIGINT(21)}, Null()}, {{BIGINT(-1)}, Null()},
+ {{Null()}, Null()}};
+
+ static_cast<void>(
+ check_function_all_arg_comb<DataTypeInt64, true>(func_name,
input_types, data_set));
+ }
+
+ {
+ InputTypeSet input_types = {Consted {PrimitiveType::TYPE_BIGINT}};
+
+ DataSet data_set = {{{Null()}, Null()}, {{BIGINT(0)},
BIGINT(1)},
+ {{BIGINT(5)}, BIGINT(120)}, {{BIGINT(20)},
BIGINT(2432902008176640000)},
+ {{BIGINT(21)}, Null()}, {{BIGINT(-1)},
Null()}};
+
+ for (const auto& row : data_set) {
+ DataSet one = {row};
+ static_cast<void>(check_function<DataTypeInt64, true>(func_name,
input_types, one));
+ }
+ }
+}
} // namespace doris::vectorized
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
index e8d234524ea..684cbd90fad 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/catalog/BuiltinScalarFunctions.java
@@ -200,6 +200,7 @@ import
org.apache.doris.nereids.trees.expressions.functions.scalar.Even;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Exp;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ExportSet;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.ExtractUrlParameter;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Factorial;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Field;
import org.apache.doris.nereids.trees.expressions.functions.scalar.FindInSet;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.FirstSignificantSubdomain;
@@ -734,6 +735,7 @@ public class BuiltinScalarFunctions implements
FunctionHelper {
scalar(Exp.class, "exp"),
scalar(ExportSet.class, "export_set"),
scalar(ExtractUrlParameter.class, "extract_url_parameter"),
+ scalar(Factorial.class, "factorial"),
scalar(Field.class, "field"),
scalar(FindInSet.class, "find_in_set"),
scalar(FirstSignificantSubdomain.class,
"first_significant_subdomain"),
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/NumericArithmetic.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/NumericArithmetic.java
index c68d2456ac8..82e55e81f6f 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/NumericArithmetic.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/NumericArithmetic.java
@@ -33,6 +33,7 @@ import
org.apache.doris.nereids.trees.expressions.literal.SmallIntLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
import org.apache.doris.nereids.trees.expressions.literal.TinyIntLiteral;
import org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral;
+import org.apache.doris.nereids.types.BigIntType;
import org.apache.doris.nereids.types.DecimalV2Type;
import org.apache.doris.nereids.types.DecimalV3Type;
import org.apache.doris.nereids.types.DoubleType;
@@ -736,6 +737,18 @@ public class NumericArithmetic {
return new DoubleLiteral(value);
}
+ /**
+ * factorial
+ */
+ @ExecFunction(name = "factorial")
+ public static Expression factorial(BigIntLiteral first) {
+ long value = first.getValue();
+ if (value < 0 || value > 20) {
+ return new NullLiteral(BigIntType.INSTANCE);
+ }
+ return new BigIntLiteral(ArithmeticUtils.factorial((int) value));
+ }
+
/**
* gcd
*/
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Factorial.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Factorial.java
new file mode 100644
index 00000000000..e2f0ba99771
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Factorial.java
@@ -0,0 +1,73 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.trees.expressions.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNullable;
+import
org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import
org.apache.doris.nereids.trees.expressions.functions.PropagateNullLiteral;
+import org.apache.doris.nereids.trees.expressions.shape.UnaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.BigIntType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * ScalarFunction Factorial
+ */
+public class Factorial extends ScalarFunction
+ implements UnaryExpression, ExplicitlyCastableSignature,
AlwaysNullable, PropagateNullLiteral {
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+
FunctionSignature.ret(BigIntType.INSTANCE).args(BigIntType.INSTANCE)
+ );
+
+ /**
+ * constructor with 1 argument.
+ */
+ public Factorial(Expression arg) {
+ super("factorial", arg);
+ }
+
+ /** constructor for withChildren and reuse signature */
+ private Factorial(ScalarFunctionParams functionParams) {
+ super(functionParams);
+ }
+
+ /**
+ * withChildren.
+ */
+ @Override
+ public Factorial withChildren(List<Expression> children) {
+ Preconditions.checkArgument(children.size() == 1);
+ return new Factorial(getFunctionParams(children));
+ }
+
+ @Override
+ public List<FunctionSignature> getSignatures() {
+ return SIGNATURES;
+ }
+
+ @Override
+ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
+ return visitor.visitFactorial(this, context);
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
index 4727d9a773f..1ab526dc224 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/ScalarFunctionVisitor.java
@@ -211,6 +211,7 @@ import
org.apache.doris.nereids.trees.expressions.functions.scalar.Even;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Exp;
import org.apache.doris.nereids.trees.expressions.functions.scalar.ExportSet;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.ExtractUrlParameter;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Factorial;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Field;
import org.apache.doris.nereids.trees.expressions.functions.scalar.FindInSet;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.FirstSignificantSubdomain;
@@ -1293,6 +1294,10 @@ public interface ScalarFunctionVisitor<R, C> {
return visitScalarFunction(extractUrlParameter, context);
}
+ default R visitFactorial(Factorial factorial, C context) {
+ return visitScalarFunction(factorial, context);
+ }
+
default R visitField(Field field, C context) {
return visitScalarFunction(field, context);
}
diff --git
a/regression-test/data/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.out
b/regression-test/data/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.out
index bb6cff5ec93..7af7d7d5729 100644
---
a/regression-test/data/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.out
+++
b/regression-test/data/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.out
@@ -89,6 +89,44 @@
\N true 8
\N true 9
+-- !factorial_1 --
+\N true
+
+-- !factorial_2 --
+\N true
+
+-- !factorial_3 --
+1 120 2432902008176640000
+
+-- !factorial_4 --
+\N true 0
+\N true 1
+\N true 2
+\N true 3
+\N true 4
+\N true 5
+\N true 6
+\N true 7
+\N true 8
+\N true 9
+
+-- !factorial_col_nullable --
+1 120
+2 1
+3 \N
+4 \N
+5 \N
+
+-- !factorial_col_not_nullable --
+1 120
+2 1
+3 \N
+4 \N
+5 3628800
+
+-- !factorial_literal_nullable_cast --
+120
+
-- !acos_tbl_1 --
1 \N true
2 \N true
diff --git
a/regression-test/suites/nereids_p0/expression/fold_constant/fold_constant_numeric_arithmatic.groovy
b/regression-test/suites/nereids_p0/expression/fold_constant/fold_constant_numeric_arithmatic.groovy
index 11cc05d342a..f17705460a9 100644
---
a/regression-test/suites/nereids_p0/expression/fold_constant/fold_constant_numeric_arithmatic.groovy
+++
b/regression-test/suites/nereids_p0/expression/fold_constant/fold_constant_numeric_arithmatic.groovy
@@ -295,6 +295,16 @@ suite("fold_constant_numeric_arithmatic") {
testFoldConst("SELECT EXP(-709.782712893384)") // Near underflow boundary
testFoldConst("SELECT EXP(1959859681)") // Result overflow become infinity
+//Factorial function cases
+ testFoldConst("SELECT FACTORIAL(5)") // common case
+ testFoldConst("SELECT FACTORIAL(0)") // boundary value 0
+ testFoldConst("SELECT FACTORIAL(1)") // boundary value 1
+ testFoldConst("SELECT FACTORIAL(20)") // boundary value 20
+ testFoldConst("SELECT FACTORIAL(-1)") // invalid input (negative)
+ testFoldConst("SELECT FACTORIAL(21)") // invalid input (overflow)
+ testFoldConst("SELECT FACTORIAL(NULL)") // NULL handling
+ testFoldConst("SELECT FACTORIAL(CAST(5 AS BIGINT))")
+
//Floor function cases
testFoldConst("SELECT FLOOR(3.7) AS floor_case_1")
testFoldConst("SELECT FLOOR(-3.7) AS floor_case_2")
diff --git
a/regression-test/suites/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.groovy
b/regression-test/suites/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.groovy
index a4ebd6647fa..4fb3bcac8b8 100644
---
a/regression-test/suites/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.groovy
+++
b/regression-test/suites/query_p0/sql_functions/math_functions/test_math_unary_always_nullable.groovy
@@ -70,6 +70,49 @@ suite("test_math_unary_alway_nullable") {
select sqrt(-1.1), sqrt(-1.1) is NULL, number from
numbers("number"="10")
"""
+ qt_factorial_1 """
+ select factorial(-1), factorial(-1) is null;
+ """
+ qt_factorial_2 """
+ select factorial(21), factorial(21) is null;
+ """
+ qt_factorial_3 """
+ select factorial(0), factorial(5), factorial(20);
+ """
+ qt_factorial_4 """
+ select factorial(-1), factorial(-1) is NULL, number from
numbers("number"="10")
+ """
+
+ sql "drop table if exists test_math_unary_alway_nullable"
+
+ sql """
+ create table if not exists test_math_unary_alway_nullable (
+ rowid int,
+ val_null BIGINT NULL,
+ val_not_null BIGINT NOT NULL
+ )
+ distributed by hash(rowid) properties("replication_num" = "1");
+ """
+
+ sql """
+ insert into test_math_unary_alway_nullable values
+ (1, 5, 5), (2, 0, 0), (3, -1, -1), (4, 21, 21), (5, NULL, 10);
+ """
+
+ qt_factorial_col_nullable """
+ select rowid, factorial(val_null) from test_math_unary_alway_nullable
order by rowid;
+ """
+
+ qt_factorial_col_not_nullable """
+ select rowid, factorial(val_not_null) from
test_math_unary_alway_nullable order by rowid;
+ """
+
+ qt_factorial_literal_nullable_cast """
+ select factorial(CAST(5 as BIGINT));
+ """
+
+ sql "drop table if exists test_math_unary_alway_nullable"
+
sql "drop table if exists test_math_unary_alway_nullable"
sql """
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]