This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new 0d21f6bce2a branch-4.2: [fix](nereids) Port LambdaBindingSpec
framework to validate lambda arguments (#66968) (#71442)
0d21f6bce2a is described below
commit 0d21f6bce2ae6219d8d644474526598820ea798f
Author: linrrarity <[email protected]>
AuthorDate: Sat Dec 5 21:49:01 2026 +0800
branch-4.2: [fix](nereids) Port LambdaBindingSpec framework to validate
lambda arguments (#66968) (#71442)
### Background
Higher-order functions in Nereids receive a `Lambda` expression followed
by its input columns. Before function signature matching,
`ExpressionAnalyzer` extracts the input columns into
`ArrayItemReference` nodes inside the `Lambda` closure and replaces the
function children with the bound `Lambda` itself, so `FunctionSignature`
only sees a single `LambdaType` argument.
### What problem does this PR solve?
Issue Number: None
Related PR: #66968
PR Type: Bugfix
Problem Summary:
On `branch-4.2`, `Lambda.makeArguments()` assumes zip-style binding
whenever `inputs.size() == lambda.getLambdaArgumentNames().size()` and
only enters the `array_sort` comparator branch when those counts differ.
Calling `array_sort` with a binary comparator `(x, y) -> ...` and two
array arguments bypasses arity validation, binds `y` to the extra array,
and propagates the extra array's nullability to the return type while BE
`ArraySortFunction::execute` reads the outer null map only from the
first array—crashing BE with `SIGSEGV` when the extra array is nullable
(e.g., `CAST(NULL AS ARRAY<INT>)`).
This PR cherry-picks the `LambdaBindingSpec` registration framework from
#66968 (commit `a10c799e787`) so each higher-order builtin registers and
enforces its own SQL-level binding rule at analysis time:
```text
Before (branch-4.2):
array_sort((x, y) -> f(x, y), arr1, extra_arr)
--> inputs.size() == 2 == lambda.args.size()
--> skips array_sort arity check, binds y -> extra_arr
--> ArraySort.nullable() = arr1.nullable || extra_arr.nullable
--> extra_arr is Nullable, arr1 is non-Nullable -> BE SIGSEGV at
ColumnNullable::create
After (this PR):
BuiltinScalarFunctions registers array_sort with
LambdaBindingSpecs.ARRAY_COMPARATOR
--> ExpressionAnalyzer looks up FunctionBuilder.getLambdaBindingSpec()
before binding lambda
--> ARRAY_COMPARATOR enforces: inputs.size() == 1 && lambda.args.size()
== 2
--> rejects extra arguments in FE with AnalysisException
```
#### Scope & Compatibility Notes
- **Partial backport scope**: #66968 introduced both the
`LambdaBindingSpec` binding framework and six `MAP` lambda functions
(`map_filter`, `map_exists`, `map_all`, `map_apply`, `transform_keys`,
`transform_values`). Because the `MAP` lambda feature still has
unresolved issues on `master` (e.g., join cross-side `MAP` lambda NPEs
and `DECIMALV3` K/V coercion issues), this PR backports only the
`LambdaBindingSpec` framework and converts the existing 14 `ARRAY`
higher-order functions to `lambdaScalar(...)`, excluding all `MAP`
lambda functions and BE changes.
- **SQL compatibility**: Valid `ARRAY` higher-order queries preserve
identical semantics and `ExpressionAnalyzer`'s lexical scope resolution
(including `shouldPrioritizeRelationQualifier()`). Two classes of
previously unchecked invalid SQL now fail fast during FE analysis:
1. Calling `array_sort` with a binary comparator lambda and more than
one array argument now raises `AnalysisException: the lambda must be a
binary comparator lambda`.
2. Passing a lambda expression to a non-higher-order function now fails
at binding time with `AnalysisException: Function <name> does not
support lambda arguments`.
- **Forward pick compatibility**: Future backporting of the `MAP` lambda
portion of #66968 can directly add `MAP_ENTRIES` in `LambdaBindingSpecs`
and register the six `MAP` functions in `BuiltinScalarFunctions` without
touching `FunctionBuilder`, `BuiltinFunctionBuilder`, `FunctionHelper`,
`Lambda`, or `ExpressionAnalyzer` again.
### Details
Reproducer SQL executed against `branch-4.2` before and after this PR:
```sql
-- 1. Valid binary comparator call
SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2]);
-- 2. Invalid extra non-null array argument
SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], [9, 8]);
-- 3. Invalid extra nullable array argument (crashes BE on unpatched
branch-4.2)
SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], CAST(NULL AS
ARRAY<INT>));
```
Before (unpatched `branch-4.2` FE + latest `branch-4.2` BE):
```text
mysql> SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2]);
+----------------------------------------------+
| ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2]) |
+----------------------------------------------+
| [1, 2, 3] |
+----------------------------------------------+
mysql> SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], [9, 8]);
+------------------------------------------------------+
| ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], [9, 8]) |
+------------------------------------------------------+
| [1, 2, 3] |
+------------------------------------------------------+
mysql> SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], CAST(NULL AS
ARRAY<INT>));
ERROR 1105 (HY000) at line 1: RpcException, msg: send fragments failed.
io.grpc.StatusRuntimeException: UNAVAILABLE: io exception, host: 127.0.0.1
```
BE `be.out` on Before query 3:
```text
*** SIGSEGV address not mapped to object (@0x0) received by PID 2871421
(TID 2874176 OR 0x14d9c020a640) from PID 0; stack trace: ***
4# doris::(anonymous
namespace)::check_nullable_null_map_column(doris::IColumn const&) at
be/src/core/column/column_nullable.cpp:36
5# doris::(anonymous namespace)::check_nullable_sizes(doris::IColumn
const&, doris::IColumn const&) at be/src/core/column/column_nullable.cpp:52
6# doris::ColumnNullable::ColumnNullable(...) at
be/src/core/column/column_nullable.cpp:97
8# doris::ArraySortFunction::execute(...) at
be/src/exprs/lambda_function/varray_sort_function.cpp:271
```
After (this PR):
```text
mysql> SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2]);
+----------------------------------------------+
| ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2]) |
+----------------------------------------------+
| [1, 2, 3] |
+----------------------------------------------+
mysql> SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], [9, 8]);
ERROR 1105 (HY000) at line 1: errCode = 2, detailMessage = the lambda must
be a binary comparator lambda
mysql> SELECT ARRAY_SORT((x, y) -> SIGN(x - y), [3, 1, 2], CAST(NULL AS
ARRAY<INT>));
ERROR 1105 (HY000) at line 1: errCode = 2, detailMessage = the lambda must
be a binary comparator lambda
```
### Testing
- Built FE (`bash build.sh --fe -j50`) with Checkstyle enabled and
verified the SQL reproducer on a local 1-FE/1-BE cluster (`branch-4.2`
BE + patched FE).
- Ran FE unit tests (`./run-fe-ut.sh --run
org.apache.doris.nereids.rules.analysis.FunctionRegistryTest`): 7 tests
run, 0 failures, 0 errors, 0 skipped.
### Release note
Reject extra or mismatched arguments to lambda-based higher-order
functions such as `array_sort` during Nereids query analysis instead of
misbinding them and crashing BE on nullable inputs.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Ready
### AI Disclosure
- Tool: Antigravity
- Generated: Partial cherry-pick adaptation, unit test case, and PR
description draft
- Human review: Reviewed code diff, conflict resolution on
`ExpressionAnalyzer`, FE unit tests, and cluster reproducer outputs
---
.../doris/catalog/BuiltinScalarFunctions.java | 29 +++---
.../org/apache/doris/catalog/FunctionHelper.java | 19 +++-
.../nereids/rules/analysis/ExpressionAnalyzer.java | 110 +++++++++++----------
.../functions/BuiltinFunctionBuilder.java | 21 +++-
.../expressions/functions/FunctionBuilder.java | 5 +
.../trees/expressions/functions/LambdaBinding.java | 32 ++++++
.../expressions/functions/LambdaBindingSpec.java | 29 ++++++
.../expressions/functions/LambdaBindingSpecs.java | 96 ++++++++++++++++++
.../trees/expressions/functions/scalar/Lambda.java | 37 -------
.../rules/analysis/FunctionRegistryTest.java | 23 +++++
10 files changed, 297 insertions(+), 104 deletions(-)
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 73fdad54124..f3b50474fc0 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
@@ -19,6 +19,7 @@ package org.apache.doris.catalog;
import org.apache.doris.nereids.trees.expressions.Like;
import org.apache.doris.nereids.trees.expressions.Regexp;
+import org.apache.doris.nereids.trees.expressions.functions.LambdaBindingSpecs;
import org.apache.doris.nereids.trees.expressions.functions.ai.AIClassify;
import org.apache.doris.nereids.trees.expressions.functions.ai.AIExtract;
import org.apache.doris.nereids.trees.expressions.functions.ai.AIFilter;
@@ -633,7 +634,7 @@ public class BuiltinScalarFunctions implements
FunctionHelper {
scalar(ArrayConcat.class, "array_concat"),
scalar(ArrayContains.class, "array_contains"),
scalar(ArrayContainsAll.class, "array_contains_all", "hasSubstr"),
- scalar(ArrayCount.class, "array_count"),
+ lambdaScalar(ArrayCount.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_count"),
scalar(ArrayCrossProduct.class, "array_cross_product",
"cross_product"),
scalar(ArrayCumSum.class, "array_cum_sum"),
scalar(ArrayDifference.class, "array_difference"),
@@ -641,18 +642,18 @@ public class BuiltinScalarFunctions implements
FunctionHelper {
scalar(ArrayEnumerate.class, "array_enumerate"),
scalar(ArrayEnumerateUniq.class, "array_enumerate_uniq"),
scalar(ArrayExcept.class, "array_except"),
- scalar(ArrayExists.class, "array_exists"),
- scalar(ArrayFilter.class, "array_filter"),
- scalar(ArrayFirst.class, "array_first"),
- scalar(ArrayFirstIndex.class, "array_first_index"),
+ lambdaScalar(ArrayExists.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_exists"),
+ lambdaScalar(ArrayFilter.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_filter"),
+ lambdaScalar(ArrayFirst.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_first"),
+ lambdaScalar(ArrayFirstIndex.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_first_index"),
scalar(ArrayFlatten.class, "array_flatten"),
scalar(ArrayIntersect.class, "array_intersect"),
scalar(ArrayJoin.class, "array_join"),
- scalar(ArrayLast.class, "array_last"),
- scalar(ArrayLastIndex.class, "array_last_index"),
- scalar(ArrayMap.class, "array_map"),
- scalar(ArrayMatchAll.class, "array_match_all"),
- scalar(ArrayMatchAny.class, "array_match_any"),
+ lambdaScalar(ArrayLast.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_last"),
+ lambdaScalar(ArrayLastIndex.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_last_index"),
+ lambdaScalar(ArrayMap.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_map"),
+ lambdaScalar(ArrayMatchAll.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_match_all"),
+ lambdaScalar(ArrayMatchAny.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_match_any"),
scalar(ArrayMax.class, "array_max"),
scalar(ArrayMin.class, "array_min"),
scalar(ArrayPopBack.class, "array_popback"),
@@ -665,11 +666,11 @@ public class BuiltinScalarFunctions implements
FunctionHelper {
scalar(ArrayRemove.class, "array_remove"),
scalar(ArrayRepeat.class, "array_repeat"),
scalar(ArrayReverseSort.class, "array_reverse_sort"),
- scalar(ArrayReverseSplit.class, "array_reverse_split"),
+ lambdaScalar(ArrayReverseSplit.class,
LambdaBindingSpecs.ARRAY_ZIP, "array_reverse_split"),
scalar(ArraySlice.class, "array_slice"),
- scalar(ArraySort.class, "array_sort"),
- scalar(ArraySortBy.class, "array_sortby"),
- scalar(ArraySplit.class, "array_split"),
+ lambdaScalar(ArraySort.class, LambdaBindingSpecs.ARRAY_COMPARATOR,
"array_sort"),
+ lambdaScalar(ArraySortBy.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_sortby"),
+ lambdaScalar(ArraySplit.class, LambdaBindingSpecs.ARRAY_ZIP,
"array_split"),
scalar(ArrayShuffle.class, "array_shuffle", "shuffle"),
scalar(ArraySum.class, "array_sum"),
scalar(ArrayUnion.class, "array_union"),
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/FunctionHelper.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/FunctionHelper.java
index cc4158bd65a..1f144780182 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/FunctionHelper.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/FunctionHelper.java
@@ -20,6 +20,7 @@ package org.apache.doris.catalog;
import org.apache.doris.nereids.trees.expressions.functions.BoundFunction;
import
org.apache.doris.nereids.trees.expressions.functions.BuiltinFunctionBuilder;
import org.apache.doris.nereids.trees.expressions.functions.FunctionBuilder;
+import org.apache.doris.nereids.trees.expressions.functions.LambdaBindingSpec;
import
org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction;
import
org.apache.doris.nereids.trees.expressions.functions.generator.TableGeneratingFunction;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.ScalarFunction;
@@ -31,6 +32,7 @@ import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
public interface FunctionHelper {
/**
@@ -66,6 +68,11 @@ public interface FunctionHelper {
return new ScalarFunc(functionClass, functionNames);
}
+ default ScalarFunc lambdaScalar(Class<? extends ScalarFunction>
functionClass,
+ LambdaBindingSpec lambdaBindingSpec, String... functionNames) {
+ return new ScalarFunc(functionClass, lambdaBindingSpec, functionNames);
+ }
+
default AggregateFunc agg(Class<? extends AggregateFunction>
functionClass) {
String functionName = functionClass.getSimpleName();
return new AggregateFunc(functionClass, functionName);
@@ -104,11 +111,16 @@ public interface FunctionHelper {
public final List<FunctionBuilder> functionBuilders;
public NamedFunc(Class<? extends T> functionClass, String... names) {
+ this(functionClass, Optional.empty(), names);
+ }
+
+ public NamedFunc(Class<? extends T> functionClass,
+ Optional<LambdaBindingSpec> lambdaBindingSpec, String...
names) {
this.functionClass = functionClass;
this.names = Arrays.stream(names)
.map(String::toLowerCase)
.collect(ImmutableList.toImmutableList());
- this.functionBuilders =
BuiltinFunctionBuilder.resolve(functionClass);
+ this.functionBuilders =
BuiltinFunctionBuilder.resolve(functionClass, lambdaBindingSpec);
}
}
@@ -116,6 +128,11 @@ public interface FunctionHelper {
public ScalarFunc(Class<? extends ScalarFunction> functionClass,
String... names) {
super(functionClass, names);
}
+
+ public ScalarFunc(Class<? extends ScalarFunction> functionClass,
+ LambdaBindingSpec lambdaBindingSpec, String... names) {
+ super(functionClass, Optional.of(lambdaBindingSpec), names);
+ }
}
class AggregateFunc extends NamedFunc<AggregateFunction> {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/ExpressionAnalyzer.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/ExpressionAnalyzer.java
index ae03174223b..54c302d65a0 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/ExpressionAnalyzer.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/ExpressionAnalyzer.java
@@ -43,7 +43,6 @@ import
org.apache.doris.nereids.rules.expression.AbstractExpressionRewriteRule;
import org.apache.doris.nereids.rules.expression.ExpressionRewriteContext;
import org.apache.doris.nereids.trees.expressions.Alias;
import org.apache.doris.nereids.trees.expressions.And;
-import org.apache.doris.nereids.trees.expressions.ArrayItemReference;
import org.apache.doris.nereids.trees.expressions.Between;
import org.apache.doris.nereids.trees.expressions.BinaryArithmetic;
import org.apache.doris.nereids.trees.expressions.BitNot;
@@ -78,6 +77,8 @@ import org.apache.doris.nereids.trees.expressions.WhenClause;
import org.apache.doris.nereids.trees.expressions.WindowExpression;
import org.apache.doris.nereids.trees.expressions.functions.BoundFunction;
import org.apache.doris.nereids.trees.expressions.functions.FunctionBuilder;
+import org.apache.doris.nereids.trees.expressions.functions.LambdaBinding;
+import org.apache.doris.nereids.trees.expressions.functions.LambdaBindingSpec;
import org.apache.doris.nereids.trees.expressions.functions.RewriteWhenAnalyze;
import org.apache.doris.nereids.trees.expressions.functions.Udf;
import org.apache.doris.nereids.trees.expressions.functions.agg.AIAgg;
@@ -444,7 +445,7 @@ public class ExpressionAnalyzer extends
SubExprAnalyzer<ExpressionRewriteContext
* bind function
*
********************************************************************************************
*/
private UnboundFunction processHighOrderFunction(UnboundFunction
unboundFunction,
- ExpressionRewriteContext context) {
+ LambdaBindingSpec bindingSpec, ExpressionRewriteContext context) {
int childrenSize = unboundFunction.children().size();
List<Expression> subChildren = new ArrayList<>();
for (int i = 1; i < childrenSize; i++) {
@@ -454,12 +455,16 @@ public class ExpressionAnalyzer extends
SubExprAnalyzer<ExpressionRewriteContext
// bindLambdaFunction
Lambda lambda = (Lambda) unboundFunction.children().get(0);
Expression lambdaFunction = lambda.getLambdaFunction();
- List<ArrayItemReference> arrayItemReferences =
lambda.makeArguments(unboundFunction.getName(), subChildren);
+ LambdaBinding binding = bindingSpec.bind(unboundFunction.getName(),
lambda, subChildren);
+ lambdaFunction = analyzeLambdaFunction(lambdaFunction,
binding.getAnalysisSlots(), context);
+ Lambda lambdaClosure = binding.close(lambdaFunction);
- List<Slot> boundedSlots = arrayItemReferences.stream()
- .map(ArrayItemReference::toSlot)
- .collect(ImmutableList.toImmutableList());
+ // We don't add the ArrayExpression in high order function at all
+ return unboundFunction.withChildren(ImmutableList.of(lambdaClosure));
+ }
+ private Expression analyzeLambdaFunction(Expression lambdaFunction,
+ List<Slot> boundedSlots, ExpressionRewriteContext context) {
ExpressionAnalyzer enclosingAnalyzer = this;
ExpressionAnalyzer lambdaAnalyzer = new
ExpressionAnalyzer(currentPlan, new Scope(Optional.of(getScope()),
boundedSlots), context == null ? null :
context.cascadesContext,
@@ -483,12 +488,7 @@ public class ExpressionAnalyzer extends
SubExprAnalyzer<ExpressionRewriteContext
return false;
}
};
- lambdaFunction = lambdaAnalyzer.analyze(lambdaFunction, context);
-
- Lambda lambdaClosure =
lambda.withLambdaFunctionArguments(lambdaFunction, arrayItemReferences);
-
- // We don't add the ArrayExpression in high order function at all
- return unboundFunction.withChildren(ImmutableList.of(lambdaClosure));
+ return lambdaAnalyzer.analyze(lambdaFunction, context);
}
/** Whether relation-qualified columns should be resolved across scopes
before nested fields. */
@@ -497,43 +497,38 @@ public class ExpressionAnalyzer extends
SubExprAnalyzer<ExpressionRewriteContext
}
UnboundFunction preProcessUnboundFunction(UnboundFunction unboundFunction,
ExpressionRewriteContext context) {
- if (unboundFunction.isHighOrder()) {
- unboundFunction = processHighOrderFunction(unboundFunction,
context);
- } else {
- // NOTICE: some trick code here. because for time arithmetic
functions,
- // the first argument of them is TimeUnit, but is cannot
distinguish with UnboundSlot in parser.
- // So, convert the UnboundSlot to a fake SlotReference with
ExprId = -1 here
- // And, the SlotReference will be processed in
DatetimeFunctionBinder
- if (StringUtils.isEmpty(unboundFunction.getDbName())
- &&
DatetimeFunctionBinder.isDatetimeArithmeticFunction(unboundFunction.getName())
- && unboundFunction.arity() == 3
- && unboundFunction.child(0) instanceof UnboundSlot) {
- SlotReference slotReference = new SlotReference(new ExprId(-1),
- ((UnboundSlot) unboundFunction.child(0)).getName(),
- TinyIntType.INSTANCE, false, ImmutableList.of());
- ImmutableList.Builder<Expression> newChildrenBuilder =
ImmutableList.builder();
- newChildrenBuilder.add(slotReference);
- for (int i = 1; i < unboundFunction.arity(); i++) {
- newChildrenBuilder.add(unboundFunction.child(i));
- }
- unboundFunction =
unboundFunction.withChildren(newChildrenBuilder.build());
- } else if (StringUtils.isEmpty(unboundFunction.getDbName())
- && "get_format".equalsIgnoreCase(unboundFunction.getName())
- && unboundFunction.arity() == 2
- && unboundFunction.child(0) instanceof UnboundSlot) {
- SlotReference slotReference = new SlotReference(new ExprId(-1),
- ((UnboundSlot) unboundFunction.child(0)).getName(),
- StringType.INSTANCE, false, ImmutableList.of());
- ImmutableList.Builder<Expression> newChildrenBuilder =
ImmutableList.builder();
- newChildrenBuilder.add(slotReference);
- for (int i = 1; i < unboundFunction.arity(); i++) {
- newChildrenBuilder.add(unboundFunction.child(i));
- }
- unboundFunction =
unboundFunction.withChildren(newChildrenBuilder.build());
+ // NOTICE: some trick code here. because for time arithmetic functions,
+ // the first argument of them is TimeUnit, but is cannot distinguish
with UnboundSlot in parser.
+ // So, convert the UnboundSlot to a fake SlotReference with ExprId =
-1 here
+ // And, the SlotReference will be processed in DatetimeFunctionBinder
+ if (StringUtils.isEmpty(unboundFunction.getDbName())
+ &&
DatetimeFunctionBinder.isDatetimeArithmeticFunction(unboundFunction.getName())
+ && unboundFunction.arity() == 3
+ && unboundFunction.child(0) instanceof UnboundSlot) {
+ SlotReference slotReference = new SlotReference(new ExprId(-1),
+ ((UnboundSlot) unboundFunction.child(0)).getName(),
+ TinyIntType.INSTANCE, false, ImmutableList.of());
+ ImmutableList.Builder<Expression> newChildrenBuilder =
ImmutableList.builder();
+ newChildrenBuilder.add(slotReference);
+ for (int i = 1; i < unboundFunction.arity(); i++) {
+ newChildrenBuilder.add(unboundFunction.child(i));
+ }
+ unboundFunction =
unboundFunction.withChildren(newChildrenBuilder.build());
+ } else if (StringUtils.isEmpty(unboundFunction.getDbName())
+ && "get_format".equalsIgnoreCase(unboundFunction.getName())
+ && unboundFunction.arity() == 2
+ && unboundFunction.child(0) instanceof UnboundSlot) {
+ SlotReference slotReference = new SlotReference(new ExprId(-1),
+ ((UnboundSlot) unboundFunction.child(0)).getName(),
+ StringType.INSTANCE, false, ImmutableList.of());
+ ImmutableList.Builder<Expression> newChildrenBuilder =
ImmutableList.builder();
+ newChildrenBuilder.add(slotReference);
+ for (int i = 1; i < unboundFunction.arity(); i++) {
+ newChildrenBuilder.add(unboundFunction.child(i));
}
- unboundFunction = (UnboundFunction) super.visit(unboundFunction,
context);
+ unboundFunction =
unboundFunction.withChildren(newChildrenBuilder.build());
}
- return unboundFunction;
+ return (UnboundFunction) super.visit(unboundFunction, context);
}
List<Object> constructUnboundFunctionArguments(UnboundFunction
unboundFunction) {
@@ -558,10 +553,22 @@ public class ExpressionAnalyzer extends
SubExprAnalyzer<ExpressionRewriteContext
@Override
public Expression visitUnboundFunction(UnboundFunction unboundFunction,
ExpressionRewriteContext context) {
- unboundFunction = preProcessUnboundFunction(unboundFunction, context);
+ FunctionRegistry functionRegistry =
Env.getCurrentEnv().getFunctionRegistry();
+ FunctionBuilder builder = null;
+ if (unboundFunction.isHighOrder()) {
+ String lambdaFunctionName = unboundFunction.getName();
+ builder = functionRegistry.findFunctionBuilder(
+ unboundFunction.getDbName(), lambdaFunctionName,
+ ImmutableList.of(unboundFunction.child(0)));
+ LambdaBindingSpec bindingSpec = builder.getLambdaBindingSpec()
+ .orElseThrow(() -> new AnalysisException(String.format(
+ "Function %s does not support lambda arguments",
lambdaFunctionName)));
+ unboundFunction = processHighOrderFunction(unboundFunction,
bindingSpec, context);
+ } else {
+ unboundFunction = preProcessUnboundFunction(unboundFunction,
context);
+ }
// bind function
- FunctionRegistry functionRegistry =
Env.getCurrentEnv().getFunctionRegistry();
List<Object> arguments =
constructUnboundFunctionArguments(unboundFunction);
String dbName = unboundFunction.getDbName();
if (StringUtils.isEmpty(dbName)) {
@@ -601,8 +608,9 @@ public class ExpressionAnalyzer extends
SubExprAnalyzer<ExpressionRewriteContext
}
String functionName = unboundFunction.getName();
- FunctionBuilder builder = functionRegistry.findFunctionBuilder(
- dbName, functionName, arguments);
+ if (builder == null) {
+ builder = functionRegistry.findFunctionBuilder(dbName,
functionName, arguments);
+ }
// for create view stmt
if (builder instanceof UdfBuilder) {
unboundFunction.getIndexInSqlString().ifPresent(index -> {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/BuiltinFunctionBuilder.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/BuiltinFunctionBuilder.java
index f496c6bc9ca..d7044721e47 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/BuiltinFunctionBuilder.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/BuiltinFunctionBuilder.java
@@ -44,11 +44,18 @@ public class BuiltinFunctionBuilder extends FunctionBuilder
{
// Concrete BoundFunction's constructor
private final Constructor<BoundFunction> builderMethod;
private final Class<? extends BoundFunction> functionClass;
+ private final Optional<LambdaBindingSpec> lambdaBindingSpec;
public BuiltinFunctionBuilder(
Class<? extends BoundFunction> functionClass,
Constructor<BoundFunction> builderMethod) {
+ this(functionClass, builderMethod, Optional.empty());
+ }
+
+ public BuiltinFunctionBuilder(Class<? extends BoundFunction> functionClass,
+ Constructor<BoundFunction> builderMethod,
Optional<LambdaBindingSpec> lambdaBindingSpec) {
this.functionClass = Objects.requireNonNull(functionClass,
"functionClass can not be null");
this.builderMethod = Objects.requireNonNull(builderMethod,
"builderMethod can not be null");
+ this.lambdaBindingSpec = Objects.requireNonNull(lambdaBindingSpec,
"lambdaBindingSpec can not be null");
this.arity = builderMethod.getParameterCount();
this.isVariableLength = arity > 0 &&
builderMethod.getParameterTypes()[arity - 1].isArray();
}
@@ -62,6 +69,11 @@ public class BuiltinFunctionBuilder extends FunctionBuilder {
return functionClass;
}
+ @Override
+ public Optional<LambdaBindingSpec> getLambdaBindingSpec() {
+ return lambdaBindingSpec;
+ }
+
@Override
public boolean canApply(List<? extends Object> arguments) {
if (isVariableLength && arity > arguments.size() + 1) {
@@ -141,12 +153,19 @@ public class BuiltinFunctionBuilder extends
FunctionBuilder {
* @return list of FunctionBuilder which contains the constructor
*/
public static List<FunctionBuilder> resolve(Class<? extends BoundFunction>
functionClass) {
+ return resolve(functionClass, Optional.empty());
+ }
+
+ /** Resolve a builtin function together with its SQL-level lambda binding
contract. */
+ public static List<FunctionBuilder> resolve(
+ Class<? extends BoundFunction> functionClass,
Optional<LambdaBindingSpec> lambdaBindingSpec) {
Preconditions.checkArgument(!Modifier.isAbstract(functionClass.getModifiers()),
"Can not resolve bind function which is abstract class: "
+ functionClass.getSimpleName());
return Arrays.stream(functionClass.getConstructors())
.filter(constructor ->
Modifier.isPublic(constructor.getModifiers()))
- .map(constructor -> new BuiltinFunctionBuilder(functionClass,
(Constructor<BoundFunction>) constructor))
+ .map(constructor -> new BuiltinFunctionBuilder(
+ functionClass, (Constructor<BoundFunction>)
constructor, lambdaBindingSpec))
.collect(ImmutableList.toImmutableList());
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/FunctionBuilder.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/FunctionBuilder.java
index 0bf3edcd60c..3c347a19def 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/FunctionBuilder.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/FunctionBuilder.java
@@ -23,6 +23,7 @@ import org.apache.doris.nereids.trees.expressions.Expression;
import com.google.common.collect.ImmutableList;
import java.util.List;
+import java.util.Optional;
/**
* This class used to build BoundFunction(Builtin or Combinator) by a list of
Expressions.
@@ -30,6 +31,10 @@ import java.util.List;
public abstract class FunctionBuilder {
public abstract Class<? extends BoundFunction> functionClass();
+ public Optional<LambdaBindingSpec> getLambdaBindingSpec() {
+ return Optional.empty();
+ }
+
/** check whether arguments can apply to the constructor */
public abstract boolean canApply(List<? extends Object> arguments);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBinding.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBinding.java
new file mode 100644
index 00000000000..f7f7ca38150
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBinding.java
@@ -0,0 +1,32 @@
+// 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;
+
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Lambda;
+
+import java.util.List;
+
+/** Mapping between SQL lambda parameters and the lambda arguments used during
execution. */
+public interface LambdaBinding {
+
+ List<Slot> getAnalysisSlots();
+
+ Lambda close(Expression analyzedBody);
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBindingSpec.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBindingSpec.java
new file mode 100644
index 00000000000..e5f5bced873
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBindingSpec.java
@@ -0,0 +1,29 @@
+// 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;
+
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Lambda;
+
+import java.util.List;
+
+/** SQL-level contract for binding the parameters of a lambda function. */
+public interface LambdaBindingSpec {
+
+ LambdaBinding bind(String functionName, Lambda lambda, List<Expression>
inputs);
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBindingSpecs.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBindingSpecs.java
new file mode 100644
index 00000000000..b8664b59811
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/LambdaBindingSpecs.java
@@ -0,0 +1,96 @@
+// 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;
+
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.trees.expressions.ArrayItemReference;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Lambda;
+import org.apache.doris.nereids.types.ArrayType;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/** Standard lambda parameter binding contracts used by builtin higher-order
functions. */
+public final class LambdaBindingSpecs {
+
+ public static final LambdaBindingSpec ARRAY_ZIP =
LambdaBindingSpecs::bindArrayZip;
+ public static final LambdaBindingSpec ARRAY_COMPARATOR =
LambdaBindingSpecs::bindArrayComparator;
+
+ private LambdaBindingSpecs() {
+ }
+
+ private static LambdaBinding bindArrayZip(
+ String functionName, Lambda lambda, List<Expression> inputs) {
+ if (inputs.size() != lambda.getLambdaArgumentNames().size()) {
+ throw new AnalysisException(String.format(
+ "lambda %s arguments' size is not equal parameters' size",
lambda.toSql()));
+ }
+ ImmutableList.Builder<ArrayItemReference> arguments =
ImmutableList.builderWithExpectedSize(inputs.size());
+ for (int i = 0; i < inputs.size(); i++) {
+ Expression input = inputs.get(i);
+ requireArrayInput(input);
+ arguments.add(new
ArrayItemReference(lambda.getLambdaArgumentName(i), input));
+ }
+ return new ArrayLambdaBinding(lambda, arguments.build());
+ }
+
+ private static LambdaBinding bindArrayComparator(
+ String functionName, Lambda lambda, List<Expression> inputs) {
+ if (inputs.size() != 1 || lambda.getLambdaArgumentNames().size() != 2)
{
+ throw new AnalysisException("the lambda must be a binary
comparator lambda");
+ }
+ Expression input = inputs.get(0);
+ requireArrayInput(input);
+ return new ArrayLambdaBinding(lambda, ImmutableList.of(
+ new ArrayItemReference(lambda.getLambdaArgumentName(0), input),
+ new ArrayItemReference(lambda.getLambdaArgumentName(1),
input)));
+ }
+
+ private static void requireArrayInput(Expression input) {
+ if (!(input.getDataType() instanceof ArrayType)) {
+ throw new AnalysisException(String.format("lambda argument must be
array but is %s", input));
+ }
+ }
+
+ private static final class ArrayLambdaBinding implements LambdaBinding {
+ private final Lambda lambda;
+ private final List<ArrayItemReference> arguments;
+ private final List<Slot> analysisSlots;
+
+ private ArrayLambdaBinding(Lambda lambda, List<ArrayItemReference>
arguments) {
+ this.lambda = lambda;
+ this.arguments = arguments;
+ this.analysisSlots = arguments.stream()
+ .map(ArrayItemReference::toSlot)
+ .collect(ImmutableList.toImmutableList());
+ }
+
+ @Override
+ public List<Slot> getAnalysisSlots() {
+ return analysisSlots;
+ }
+
+ @Override
+ public Lambda close(Expression analyzedBody) {
+ return lambda.withLambdaFunctionArguments(analyzedBody, arguments);
+ }
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Lambda.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Lambda.java
index 192f04e5632..0b2250c3b95 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Lambda.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/Lambda.java
@@ -17,16 +17,13 @@
package org.apache.doris.nereids.trees.expressions.functions.scalar;
-import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.expressions.ArrayItemReference;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
-import org.apache.doris.nereids.types.ArrayType;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.LambdaType;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
import java.util.List;
import java.util.Objects;
@@ -38,7 +35,6 @@ import java.util.stream.Collectors;
* After bind, x -> x : arguments("x") -> children: Expression(x)
ArrayItemReference(x)
*/
public class Lambda extends Expression {
-
private final List<String> argumentNames;
/**
@@ -58,39 +54,6 @@ public class Lambda extends Expression {
argumentNames, "argumentNames should not null"));
}
- /**
- * make slot according array expression
- * @param functionName function name
- * @param arrays array expression
- * @return item slots of array expression
- */
- public ImmutableList<ArrayItemReference> makeArguments(String
functionName, List<Expression> arrays) {
- Builder<ArrayItemReference> builder = new ImmutableList.Builder<>();
- if (arrays.size() != argumentNames.size()) {
- // In the lambda expression of array_sort, x and y point to the
same slot.
- if (functionName.equalsIgnoreCase("array_sort") && arrays.size()
== 1 && argumentNames.size() == 2) {
- Expression array = arrays.get(0);
- if (!(array.getDataType() instanceof ArrayType)) {
- throw new AnalysisException(String.format("lambda argument
must be array but is %s", array));
- }
- builder.add(new ArrayItemReference(argumentNames.get(0),
array));
- builder.add(new ArrayItemReference(argumentNames.get(1),
array));
- return builder.build();
- }
- throw new AnalysisException(String.format("lambda %s arguments'
size is not equal parameters' size",
- toSql()));
- }
- for (int i = 0; i < arrays.size(); i++) {
- Expression array = arrays.get(i);
- if (!(array.getDataType() instanceof ArrayType)) {
- throw new AnalysisException(String.format("lambda argument
must be array but is %s", array));
- }
- String name = argumentNames.get(i);
- builder.add(new ArrayItemReference(name, array));
- }
- return builder.build();
- }
-
public String getLambdaArgumentName(int i) {
return argumentNames.get(i);
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/FunctionRegistryTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/FunctionRegistryTest.java
index ef0b4b59f7b..98f13c14408 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/FunctionRegistryTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/FunctionRegistryTest.java
@@ -25,6 +25,8 @@ import
org.apache.doris.nereids.trees.expressions.functions.BoundFunction;
import
org.apache.doris.nereids.trees.expressions.functions.BuiltinFunctionBuilder;
import
org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
import org.apache.doris.nereids.trees.expressions.functions.FunctionBuilder;
+import org.apache.doris.nereids.trees.expressions.functions.LambdaBindingSpec;
+import org.apache.doris.nereids.trees.expressions.functions.LambdaBindingSpecs;
import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.ParseToVariant;
import
org.apache.doris.nereids.trees.expressions.functions.scalar.ScalarFunction;
@@ -108,6 +110,27 @@ public class FunctionRegistryTest implements
MemoPatternMatchSupported {
);
}
+ @Test
+ public void testLambdaBindingSpecComesFromFunctionRegistration() {
+ FunctionRegistry functionRegistry = new FunctionRegistry();
+
+ assertLambdaBindingSpec(functionRegistry, "array_map",
LambdaBindingSpecs.ARRAY_ZIP);
+ assertLambdaBindingSpec(functionRegistry, "array_sort",
LambdaBindingSpecs.ARRAY_COMPARATOR);
+
Assertions.assertTrue(functionRegistry.tryGetBuiltinBuilders("abs").get().stream()
+ .allMatch(builder ->
!builder.getLambdaBindingSpec().isPresent()));
+
+ AnalysisException exception =
Assertions.assertThrows(AnalysisException.class,
+ () -> PlanChecker.from(connectContext).analyze(
+ "select array_sort((x, y) -> sign(x - y), [3, 1, 2],
cast(null as array<int>))"));
+ Assertions.assertTrue(exception.getMessage().contains("the lambda must
be a binary comparator lambda"));
+ }
+
+ private void assertLambdaBindingSpec(
+ FunctionRegistry functionRegistry, String functionName,
LambdaBindingSpec expectedSpec) {
+
Assertions.assertTrue(functionRegistry.tryGetBuiltinBuilders(functionName).get().stream()
+ .allMatch(builder ->
builder.getLambdaBindingSpec().orElse(null) == expectedSpec));
+ }
+
@Test
public void testOverrideArity() {
// the substring function has 2 override functions:
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]