yujun777 commented on code in PR #69456: URL: https://github.com/apache/doris/pull/69456#discussion_r4358132125
########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ArraySortedMerge.java: ########## @@ -0,0 +1,161 @@ +// 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.exceptions.AnalysisException; +import org.apache.doris.nereids.trees.expressions.ArrayItemReference; +import org.apache.doris.nereids.trees.expressions.Cast; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.functions.ImplicitlyCastableSignature; +import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor; +import org.apache.doris.nereids.types.ArrayType; +import org.apache.doris.nereids.types.BooleanType; +import org.apache.doris.nereids.types.DataType; +import org.apache.doris.nereids.types.LambdaType; +import org.apache.doris.nereids.types.coercion.FollowToAnyDataType; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; + +import java.util.List; + +/** + * array_sorted_merge(merge_fn, arr1, arr2, is_asc): merge two arrays that are already sorted. + * + * <pre> + * array_sorted_merge((a, b) -> ..., arr1, arr2, true) + * </pre> + * + * <p>The inputs must already be sorted by the elements' natural order in the direction given by + * {@code is_asc}; the function only merges them. The merge lambda receives the two current + * candidates as {@code (a, b)} and returns the combined element; returning NULL means the two + * elements must not be combined, so both are kept. Each key occurs at most once per input, so a + * key appears at most twice across the two arrays and the lambda is called at most once per key. + * + * <p>A NULL input array makes the result NULL, like the other higher-order array functions. The + * ascending flag must be a non-null constant; it deliberately does not take part in nullable + * propagation, which would fold a NULL flag into a NULL result instead of failing the analysis. + */ +public class ArraySortedMerge extends ScalarFunction + implements ImplicitlyCastableSignature { + + // The bound form: the lambda plus the ascending flag; the arrays live in the lambda argument + // references, like the other lambda functions. + public static final List<FunctionSignature> SIGNATURES = ImmutableList.of( + FunctionSignature.ret(new FollowToAnyDataType(0)) + .args(LambdaType.INSTANCE, BooleanType.INSTANCE)); + + /** + * The extra arguments are variadic so that the function builder resolved with only the lambda + * (the higher-order lookup) can also build the bound form that keeps the ascending flag. + */ + public ArraySortedMerge(Expression lambda, Expression... extra) { + super("array_sorted_merge", + ImmutableList.<Expression>builder().add(lambda).add(extra).build()); + } + + /** constructor for withChildren and reuse signature */ + private ArraySortedMerge(ScalarFunctionParams functionParams) { + super(functionParams); + } + + @Override + public List<FunctionSignature> getSignatures() { + return SIGNATURES; + } + + @Override + public ArraySortedMerge withChildren(List<Expression> children) { + Preconditions.checkArgument(children.size() == 2); + return new ArraySortedMerge(getFunctionParams(children)); + } + + @Override + public void checkLegalityBeforeTypeCoercion() { + if (!(child(0) instanceof Lambda)) { + throw new AnalysisException(getName() + " requires a merge lambda as the first argument"); + } + Lambda lambda = (Lambda) child(0); + if (lambda.getLambdaArgumentNames().size() != 2) { + throw new AnalysisException(getName() + " requires a two-argument merge lambda, but got " + + lambda.getLambdaArgumentNames().size()); + } + ArrayType left = requireArray(lambda, 0); + ArrayType right = requireArray(lambda, 1); + if (!left.getItemType().equals(right.getItemType())) { + throw new AnalysisException(getName() + + " requires both arrays to have the same element type, but got " + + left.getItemType().toSql() + " and " + right.getItemType().toSql()); + } + if (!lambda.getRetType().equals(left.getItemType())) { Review Comment: Fixed in e250347cd12: the pair fields of min_topk/max_topk are now declared nullable, which is what a lambda can actually produce from them. An array element is always nullable, so `element_at` yields a nullable field and `named_struct` records it as nullable; a required field made the element-type equality fail, and `CheckCast` correctly refuses the nullable -> required cast that would otherwise be needed. The aggregate still never writes a NULL field: the BE return type mirrors the nullable fields, and `insert_result_into` writes zero null maps for the pair element and for both fields. Nothing is cast, and the `CheckCast` safety rule is untouched. The direct composition now works for both aggregates: ```sql SELECT array_sorted_merge( (a, b) -> IF(element_at(a, 'value') = element_at(b, 'value'), named_struct('value', element_at(a, 'value'), 'count', element_at(a, 'count') + element_at(b, 'count')), NULL), s, s, true) FROM (SELECT min_topk(i, 2) AS s FROM (SELECT 1 AS i) t) x -- [{"value":1, "count":2}] ``` Covered by `order_qt_topk_output_merge` in `test_array_sorted_merge`; `TopKFunctionSignatureTest` and the BE `TopKTest.*` unit tests were updated to assert the nullable pair layout. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
