DateTrunc.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.functions.AlwaysNullable;
import org.apache.doris.nereids.trees.expressions.functions.CustomSignature;
import org.apache.doris.nereids.trees.expressions.functions.Monotonic;
import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral;
import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DateTimeV2Type;
import org.apache.doris.nereids.types.VarcharType;

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

import java.util.List;

/**
 * ScalarFunction 'date_trunc'. This class is generated by GenerateFunction.
 */
public class DateTrunc extends ScalarFunction
        implements BinaryExpression, AlwaysNullable, Monotonic, CustomSignature {
    private static final List<String> LEGAL_TIME_UNIT =
            ImmutableList.of("year", "quarter", "month", "week", "day", "hour", "minute", "second");

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

    @Override
    public void checkLegalityBeforeTypeCoercion() {
        boolean firstArgIsStringLiteral =
                getArgument(0).isConstant() && getArgument(0) instanceof StringLikeLiteral;
        boolean secondArgIsStringLiteral =
                getArgument(1).isConstant() && getArgument(1) instanceof StringLikeLiteral;
        if (!firstArgIsStringLiteral && !secondArgIsStringLiteral) {
            throw new AnalysisException("the time unit parameter of "
                    + getName() + " function must be a string constant: " + toSql());
        } else if (firstArgIsStringLiteral && secondArgIsStringLiteral) {
            if (!LEGAL_TIME_UNIT.contains(((VarcharLiteral) getArgument(0)).getStringValue().toLowerCase())
                    && !LEGAL_TIME_UNIT.contains(((VarcharLiteral) getArgument(1))
                    .getStringValue().toLowerCase())) {
                throw new AnalysisException("date_trunc function time unit param only support argument is "
                        + String.join("|", LEGAL_TIME_UNIT));
            }
        } else {
            final String constParam = ((VarcharLiteral) getArgument(firstArgIsStringLiteral ? 0 : 1))
                    .getStringValue().toLowerCase();
            if (!LEGAL_TIME_UNIT.contains(constParam)) {
                throw new AnalysisException("date_trunc function time unit param only support argument is "
                        + String.join("|", LEGAL_TIME_UNIT));
            }
        }
    }

    /**
     * withChildren.
     */
    @Override
    public DateTrunc withChildren(List<Expression> children) {
        Preconditions.checkArgument(children.size() == 2);
        return new DateTrunc(children.get(0), children.get(1));
    }

    @Override
    public FunctionSignature customSignature() {
        if (getArgument(0).getDataType().isDateLikeType()) {
            return FunctionSignature.ret(getArgument(0).getDataType())
                    .args(getArgument(0).getDataType(), VarcharType.SYSTEM_DEFAULT);
        } else if (getArgument(1).getDataType().isDateLikeType()) {
            return FunctionSignature.ret(getArgument(1).getDataType())
                    .args(VarcharType.SYSTEM_DEFAULT, getArgument(1).getDataType());
        }
        boolean firstArgIsStringLiteral =
                getArgument(0).isConstant() && getArgument(0) instanceof VarcharLiteral;
        boolean secondArgIsStringLiteral =
                getArgument(1).isConstant() && getArgument(1) instanceof VarcharLiteral;
        if (firstArgIsStringLiteral && !secondArgIsStringLiteral) {
            return FunctionSignature.ret(DateTimeV2Type.SYSTEM_DEFAULT)
                    .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.SYSTEM_DEFAULT);
        } else if (!firstArgIsStringLiteral && secondArgIsStringLiteral) {
            return FunctionSignature.ret(DateTimeV2Type.SYSTEM_DEFAULT)
                    .args(DateTimeV2Type.SYSTEM_DEFAULT, VarcharType.SYSTEM_DEFAULT);
        } else if (firstArgIsStringLiteral && secondArgIsStringLiteral) {
            boolean timeUnitIsFirst = LEGAL_TIME_UNIT.contains(((VarcharLiteral) getArgument(0))
                    .getStringValue().toLowerCase());
            return timeUnitIsFirst ? FunctionSignature.ret(DateTimeV2Type.SYSTEM_DEFAULT)
                    .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.SYSTEM_DEFAULT)
                    : FunctionSignature.ret(DateTimeV2Type.SYSTEM_DEFAULT)
                            .args(DateTimeV2Type.SYSTEM_DEFAULT, VarcharType.SYSTEM_DEFAULT);
        }
        // if both of args are not constant, `checkLegalityBeforeTypeCoercion` will throw exception so just return
        // a signature here.
        return FunctionSignature.ret(DateTimeV2Type.SYSTEM_DEFAULT)
                .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.SYSTEM_DEFAULT);
    }

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

    @Override
    public boolean isPositive() {
        return true;
    }

    @Override
    public int getMonotonicFunctionChildIndex() {
        return getArgument(0).getDataType().isDateLikeType() ? 0 : 1;
    }

    @Override
    public Expression withConstantArgs(Expression literal) {
        return getArgument(0).getDataType().isDateLikeType()
                ? new DateTrunc(literal, child(1)) : new DateTrunc(child(0), literal);
    }
}