ElementAt.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.scalar;

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.PreferPushDownProject;
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.literal.IntegerLikeLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.ArrayType;
import org.apache.doris.nereids.types.BigIntType;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.MapType;
import org.apache.doris.nereids.types.NullType;
import org.apache.doris.nereids.types.StructField;
import org.apache.doris.nereids.types.StructType;
import org.apache.doris.nereids.types.VarcharType;
import org.apache.doris.nereids.types.VariantType;
import org.apache.doris.nereids.types.coercion.AnyDataType;
import org.apache.doris.nereids.types.coercion.FollowToAnyDataType;

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

import java.util.List;

/**
 * ScalarFunction 'element_at'. This class is generated by GenerateFunction.
 */
public class ElementAt extends ScalarFunction
        implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNullable,
            PropagateNullLiteral, PreferPushDownProject {

    public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
            FunctionSignature.ret(new FollowToAnyDataType(0))
                    .args(ArrayType.of(new AnyDataType(0)), BigIntType.INSTANCE),
            FunctionSignature.ret(VariantType.INSTANCE)
                    .args(VariantType.INSTANCE, VarcharType.SYSTEM_DEFAULT),
            FunctionSignature.ret(VariantType.INSTANCE)
                    .args(VariantType.INSTANCE, BigIntType.INSTANCE),
            FunctionSignature.ret(new FollowToAnyDataType(1))
                    .args(MapType.of(new AnyDataType(0), new AnyDataType(1)), new FollowToAnyDataType(0))
    );

    /**
     * constructor with 2 arguments.
     */
    public ElementAt(Expression arg0, Expression arg1) {
        super("element_at", arg0, arg1);
    }

    /** constructor for withChildren and reuse signature */
    protected ElementAt(ScalarFunctionParams functionParams) {
        super(functionParams);
    }

    /**
     * withChildren.
     */
    @Override
    public ElementAt withChildren(List<Expression> children) {
        Preconditions.checkArgument(children.size() == 2);
        return new ElementAt(getFunctionParams(children));
    }

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

    @Override
    public void checkLegalityBeforeTypeCoercion() {
        // Struct field access (the former struct_element) only accepts a constant int/string index,
        // since the selected field ��� and therefore the result type ��� must be known at analysis time.
        if (child(0).getDataType() instanceof StructType) {
            Expression field = getArgument(1);
            if (!(field instanceof StringLikeLiteral || field instanceof IntegerLikeLiteral)) {
                throw new AnalysisException("element_at over a struct only allows a constant int or"
                        + " string second parameter: " + this.toSql());
            }
        }
    }

    @Override
    public List<FunctionSignature> getSignatures() {
        DataType arg0Type = child(0).getDataType();
        if (arg0Type instanceof NullType) {
            return ImmutableList.of(
                    FunctionSignature.ret(NullType.INSTANCE).args(NullType.INSTANCE, child(1).getDataType()));
        }
        if (arg0Type instanceof StructType) {
            return ImmutableList.of(FunctionSignature.ret(structFieldType((StructType) arg0Type))
                    .args(arg0Type, child(1).getDataType()));
        }
        return SIGNATURES;
    }

    // Resolve the type of the struct field selected by the constant int/string index.
    private DataType structFieldType(StructType structType) {
        Expression field = getArgument(1);
        if (field instanceof IntegerLikeLiteral) {
            int offset = ((IntegerLikeLiteral) field).getIntValue();
            if (offset <= 0 || offset > structType.getFields().size()) {
                throw new AnalysisException("the specified field index out of bound: " + this.toSql());
            }
            return structType.getFields().get(offset - 1).getDataType();
        } else if (field instanceof StringLikeLiteral) {
            String name = ((StringLikeLiteral) field).getStringValue();
            StructField structField = structType.getField(name);
            if (structField == null) {
                throw new AnalysisException("the specified field name " + name + " was not found: " + this.toSql());
            }
            return structField.getDataType();
        } else {
            throw new AnalysisException("element_at over a struct only allows a constant int or"
                    + " string second parameter: " + this.toSql());
        }
    }

    @Override
    public FunctionSignature computeSignature(FunctionSignature signature) {
        List<Expression> arguments = getArguments();
        DataType expressionType = arguments.get(0).getDataType();
        DataType sigType = signature.argumentsTypes.get(0);
        if (expressionType instanceof VariantType && sigType instanceof VariantType) {
            // Preserve predefinedFields for schema template matching
            VariantType originalType = (VariantType) expressionType;
            signature = signature.withArgumentType(0, originalType);
            signature = signature.withReturnType(originalType);
        }
        return super.computeSignature(signature);
    }
}