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.CustomSignature;
import org.apache.doris.nereids.trees.expressions.functions.Monotonic;
import org.apache.doris.nereids.trees.expressions.functions.PropagateNullLiteral;
import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
import org.apache.doris.nereids.trees.expressions.literal.Literal;
import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.literal.format.DateTimeChecker;
import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.DateTimeV2Type;
import org.apache.doris.nereids.types.TimeStampTzType;
import org.apache.doris.nereids.types.VarcharType;

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

import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * ScalarFunction 'date_trunc'. This class is generated by GenerateFunction.
 */
public class DateTrunc extends ScalarFunction
        implements BinaryExpression, PropagateNullLiteral, PropagateNullable, Monotonic, CustomSignature {
    private static final List<String> LEGAL_TIME_UNIT =
            ImmutableList.of("year", "quarter", "month", "week", "day", "hour", "minute", "second");
    // units under which date_trunc is a floor (f(col) <= col). Kept separate from LEGAL_TIME_UNIT
    // on purpose (do NOT merge for DRY): "legal to use" and "safe to derive col >= c from" are
    // different concepts. They happen to coincide today; a future non-floor legal unit must be
    // added to LEGAL_TIME_UNIT but not here, or predicate pushdown would silently drop rows.
    private static final Set<String> FLOOR_UNITS = ImmutableSet.of(
            "year", "quarter", "month", "week", "day", "hour", "minute", "second");

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

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

    @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(((StringLikeLiteral) getArgument(0)).getStringValue().toLowerCase())
                    && !LEGAL_TIME_UNIT.contains(((StringLikeLiteral) 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 = ((StringLikeLiteral) 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(getFunctionParams(children));
    }

    @Override
    public FunctionSignature customSignature() {
        // should never return V1 Type
        // Handle TimeStampTzType first, before isDateLikeType check
        // Because getCurrentType() would convert TimeStampTzType to DateTimeV2Type
        if (getArgument(0).getDataType() instanceof TimeStampTzType) {
            TimeStampTzType type = (TimeStampTzType) getArgument(0).getDataType();
            return FunctionSignature.ret(type).args(type, VarcharType.SYSTEM_DEFAULT);
        } else if (getArgument(1).getDataType() instanceof TimeStampTzType) {
            TimeStampTzType type = (TimeStampTzType) getArgument(1).getDataType();
            return FunctionSignature.ret(type).args(VarcharType.SYSTEM_DEFAULT, type);
        }

        if (getArgument(0).getDataType().isDateLikeType()) {
            DataType type = DataType.getCurrentType(getArgument(0).getDataType());
            return FunctionSignature.ret(type).args(type, VarcharType.SYSTEM_DEFAULT);
        } else if (getArgument(1).getDataType().isDateLikeType()) {
            DataType type = DataType.getCurrentType(getArgument(1).getDataType());
            return FunctionSignature.ret(type).args(VarcharType.SYSTEM_DEFAULT, type);
        }

        boolean firstArgIsStringLiteral =
                getArgument(0).isConstant() && getArgument(0) instanceof StringLikeLiteral;
        boolean secondArgIsStringLiteral =
                getArgument(1).isConstant() && getArgument(1) instanceof StringLikeLiteral;
        if (firstArgIsStringLiteral && !secondArgIsStringLiteral) {
            DataType argType = getArgument(1).getDataType();
            if (argType instanceof TimeStampTzType) {
                return FunctionSignature.ret((TimeStampTzType) argType)
                        .args(VarcharType.SYSTEM_DEFAULT, (TimeStampTzType) argType);
            }
            return FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                    .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.WILDCARD);
        } else if (!firstArgIsStringLiteral && secondArgIsStringLiteral) {
            DataType argType = getArgument(0).getDataType();
            if (argType instanceof TimeStampTzType) {
                return FunctionSignature.ret((TimeStampTzType) argType)
                        .args((TimeStampTzType) argType, VarcharType.SYSTEM_DEFAULT);
            }
            return FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                    .args(DateTimeV2Type.WILDCARD, VarcharType.SYSTEM_DEFAULT);
        } else if (firstArgIsStringLiteral && secondArgIsStringLiteral) {
            boolean timeUnitIsFirst = LEGAL_TIME_UNIT.contains(((StringLikeLiteral) getArgument(0))
                    .getStringValue().toLowerCase());
            // Check if the datetime string contains timezone information
            String datetimeStr = timeUnitIsFirst
                    ? ((StringLikeLiteral) getArgument(1)).getStringValue()
                    : ((StringLikeLiteral) getArgument(0)).getStringValue();
            if (DateTimeChecker.hasTimeZone(datetimeStr)) {
                return timeUnitIsFirst ? FunctionSignature.ret(TimeStampTzType.SYSTEM_DEFAULT)
                        .args(VarcharType.SYSTEM_DEFAULT, TimeStampTzType.SYSTEM_DEFAULT)
                        : FunctionSignature.ret(TimeStampTzType.SYSTEM_DEFAULT)
                                .args(TimeStampTzType.SYSTEM_DEFAULT, VarcharType.SYSTEM_DEFAULT);
            }
            return timeUnitIsFirst ? FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                    .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.WILDCARD)
                    : FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                            .args(DateTimeV2Type.WILDCARD, VarcharType.SYSTEM_DEFAULT);
        }
        // if both of args are not constant, `checkLegalityBeforeTypeCoercion` will throw exception so just return
        // a signature here.
        return FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.WILDCARD);
    }

    @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 boolean isFloor() {
        int dateIdx = getMonotonicFunctionChildIndex();
        Expression unit = getArgument(dateIdx == 0 ? 1 : 0);
        return unit instanceof StringLikeLiteral
                && FLOOR_UNITS.contains(((StringLikeLiteral) unit).getStringValue().toLowerCase());
    }

    @Override
    public Optional<Expression> floorUpperBound(Literal c) {
        // date_trunc(col,'unit') = c  <=>  col in [c, c + 1 unit). The added granularity MUST match
        // the trunc unit exactly; a mismatch would prune rows that must be kept. Carry-over (leap
        // year / month end) is handled by the reused *Add functions, not by hand.
        int dateIdx = getMonotonicFunctionChildIndex();
        Expression unitArg = getArgument(dateIdx == 0 ? 1 : 0);
        if (!(unitArg instanceof StringLikeLiteral)) {
            return Optional.empty();
        }
        Literal one = new IntegerLiteral(1);
        switch (((StringLikeLiteral) unitArg).getStringValue().toLowerCase()) {
            case "year":
                return Optional.of(new YearsAdd(c, one));
            case "quarter":
                return Optional.of(new QuartersAdd(c, one));
            case "month":
                return Optional.of(new MonthsAdd(c, one));
            case "week":
                return Optional.of(new WeeksAdd(c, one));
            case "day":
                return Optional.of(new DaysAdd(c, one));
            case "hour":
                return Optional.of(new HoursAdd(c, one));
            case "minute":
                return Optional.of(new MinutesAdd(c, one));
            case "second":
                return Optional.of(new SecondsAdd(c, one));
            default:
                return Optional.empty();
        }
    }

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