GroupConcat.java

// 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.agg;

import org.apache.doris.catalog.FunctionSignature;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.OrderExpression;
import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.VarcharType;
import org.apache.doris.nereids.types.coercion.AnyDataType;
import org.apache.doris.nereids.util.ExpressionUtils;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

/**
 * AggregateFunction 'group_concat'. This class is generated by GenerateFunction.
 */
public class GroupConcat extends NullableAggregateFunction
        implements ExplicitlyCastableSignature, SupportMultiDistinct {

    public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
            FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT).args(VarcharType.SYSTEM_DEFAULT),
            FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT)
                    .varArgs(VarcharType.SYSTEM_DEFAULT, AnyDataType.INSTANCE_WITHOUT_INDEX),
            FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT)
                    .varArgs(VarcharType.SYSTEM_DEFAULT, VarcharType.SYSTEM_DEFAULT, AnyDataType.INSTANCE_WITHOUT_INDEX)
    );

    private final int nonOrderArguments;

    /**
     * constructor with 1 argument.
     */
    public GroupConcat(boolean distinct, boolean alwaysNullable, Expression arg, Expression... others) {
        this(distinct, alwaysNullable, ExpressionUtils.mergeArguments(arg, others));
    }

    /**
     * constructor with 1 argument.
     */
    public GroupConcat(boolean distinct, Expression arg, Expression... others) {
        this(distinct, false, arg, others);
    }

    /**
     * constructor with 1 argument, use for function search.
     */
    public GroupConcat(Expression arg, Expression... others) {
        this(false, arg, others);
    }

    /**
     * constructor for always nullable.
     */
    public GroupConcat(boolean distinct, boolean alwaysNullable, List<Expression> args) {
        super("group_concat", distinct, alwaysNullable, args);
        this.nonOrderArguments = findOrderExprIndex(children);
    }

    @Override
    public boolean nullable() {
        return alwaysNullable || children().stream()
                .anyMatch(expression -> !(expression instanceof OrderExpression) && expression.nullable());
    }

    @Override
    public List<Expression> getDistinctArguments() {
        if (distinct) {
            return ImmutableList.of(getArgument(0));
        } else {
            return ImmutableList.of();
        }
    }

    @Override
    public void checkLegalityBeforeTypeCoercion() {
        DataType typeOrArg0 = getArgumentType(0);
        if (!typeOrArg0.isStringLikeType() && !typeOrArg0.isNullType()) {
            throw new AnalysisException(
                    "group_concat requires first parameter to be of type STRING: " + this.toSql());
        }

        if (nonOrderArguments == 2) {
            DataType typeOrArg1 = getArgumentType(1);
            if (!typeOrArg1.isStringLikeType() && !typeOrArg1.isNullType()) {
                throw new AnalysisException(
                        "group_concat requires second parameter to be of type STRING: " + this.toSql());
            }
        }
    }

    @Override
    public GroupConcat withAlwaysNullable(boolean alwaysNullable) {
        return new GroupConcat(distinct, alwaysNullable, children);
    }

    /**
     * withDistinctAndChildren.
     */
    @Override
    public GroupConcat withDistinctAndChildren(boolean distinct, List<Expression> children) {
        return new GroupConcat(distinct, alwaysNullable, children);
    }

    @Override
    public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
        return visitor.visitGroupConcat(this, context);
    }

    @Override
    public List<FunctionSignature> getSignatures() {
        return SIGNATURES;
    }

    @Override
    public MultiDistinctGroupConcat convertToMultiDistinct() {
        Preconditions.checkArgument(distinct,
                "can't convert to multi_distinct_group_concat because there is no distinct args");
        return new MultiDistinctGroupConcat(alwaysNullable, children);
    }

    @Override
    public boolean mustUseMultiDistinctAgg() {
        return distinct && children.stream().anyMatch(OrderExpression.class::isInstance);
    }

    private int findOrderExprIndex(List<Expression> children) {
        Preconditions.checkArgument(children().size() >= 1, "children's size should >= 1");
        boolean foundOrderExpr = false;
        int firstOrderExrIndex = 0;
        for (int i = 0; i < children.size(); i++) {
            Expression child = children.get(i);
            if (child instanceof OrderExpression) {
                foundOrderExpr = true;
            } else if (!foundOrderExpr) {
                firstOrderExrIndex++;
            } else {
                throw new AnalysisException(
                        "invalid multi_distinct_group_concat parameters: " + children);
            }
        }

        if (firstOrderExrIndex > 2) {
            throw new AnalysisException(
                    "multi_distinct_group_concat requires one or two parameters: " + children);
        }
        return firstOrderExrIndex;
    }
}