github-actions[bot] commented on code in PR #62535:
URL: https://github.com/apache/doris/pull/62535#discussion_r3091883402


##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPartitionExprDateTruncDateAddSub.java:
##########
@@ -0,0 +1,299 @@
+// 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.mtmv;
+
+import org.apache.doris.analysis.Expr;
+import org.apache.doris.analysis.FunctionCallExpr;
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.analysis.PartitionExprUtil;
+import org.apache.doris.analysis.PartitionKeyDesc;
+import org.apache.doris.analysis.PartitionValue;
+import org.apache.doris.analysis.StringLiteral;
+import org.apache.doris.analysis.TimestampArithmeticExpr;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.util.PropertyAnalyzer;
+import org.apache.doris.datasource.mvcc.MvccUtil;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import 
org.apache.doris.nereids.trees.expressions.functions.executable.DateTimeArithmetic;
+import 
org.apache.doris.nereids.trees.expressions.functions.executable.DateTimeExtractAndTransform;
+import org.apache.doris.nereids.trees.expressions.literal.BigIntLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal;
+import org.apache.doris.nereids.trees.expressions.literal.DateV2Literal;
+import org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Rollup service for expressions:
+ * date_trunc(date_add/date_sub(partition_col, interval N hour), 'unit')
+ */
+public class MTMVPartitionExprDateTruncDateAddSub implements 
MTMVPartitionExprService {
+    private static final Set<String> TIME_UNITS = ImmutableSet.of(
+            "year", "quarter", "week", "month", "day", "hour");
+    private final String timeUnit;
+    private final long offsetHours;
+
+    public MTMVPartitionExprDateTruncDateAddSub(FunctionCallExpr 
functionCallExpr) throws AnalysisException {
+        List<Expr> paramsExprs = functionCallExpr.getParams().exprs();
+        if (paramsExprs.size() != 2) {
+            throw new AnalysisException("date_trunc params exprs size should 
be 2.");
+        }
+        Expr dateTruncUnit = paramsExprs.get(1);
+        if (!(dateTruncUnit instanceof StringLiteral)) {
+            throw new AnalysisException("date_trunc param of time unit is not 
string literal.");
+        }
+        this.timeUnit = dateTruncUnit.getStringValue().toLowerCase();
+
+        Expr dateTruncArg = paramsExprs.get(0);
+        if (!(dateTruncArg instanceof TimestampArithmeticExpr)) {
+            throw new AnalysisException("date_trunc first argument should be 
date_add/date_sub in mtmv partition");
+        }
+        TimestampArithmeticExpr timestampArithmeticExpr = 
(TimestampArithmeticExpr) dateTruncArg;
+        if (timestampArithmeticExpr.getTimeUnit() != 
TimestampArithmeticExpr.TimeUnit.HOUR) {
+            throw new AnalysisException("only HOUR unit is supported in 
date_add/date_sub for mtmv partition");
+        }
+        if (!(timestampArithmeticExpr.getChild(1) instanceof LiteralExpr)) {
+            throw new AnalysisException("date_add/date_sub offset should be a 
literal");
+        }
+        long offset = parseOffsetHours((LiteralExpr) 
timestampArithmeticExpr.getChild(1));
+        String functionName = 
timestampArithmeticExpr.getFuncName().toLowerCase();
+        if ("date_sub".equals(functionName)) {
+            this.offsetHours = -offset;
+        } else if ("date_add".equals(functionName)) {
+            this.offsetHours = offset;
+        } else {
+            throw new AnalysisException("only date_add/date_sub is supported 
in mtmv partition");
+        }
+    }
+
+    @Override
+    public String getRollUpIdentity(PartitionKeyDesc partitionKeyDesc, 
Map<String, String> mvProperties)
+            throws AnalysisException {
+        String res = null;
+        Optional<String> dateFormat = getDateFormat(mvProperties);
+        List<List<PartitionValue>> inValues = partitionKeyDesc.getInValues();
+        for (int i = 0; i < inValues.size(); i++) {
+            PartitionValue partitionValue = inValues.get(i).get(0);
+            if (partitionValue.isNullPartition()) {
+                throw new AnalysisException("date_trunc + date_add/date_sub 
not support null partition value");
+            }
+            String identity = 
dateTruncByOffset(partitionValue.getStringValue(), dateFormat, 
false).toString();
+            if (i == 0) {
+                res = identity;
+            } else if (!Objects.equals(res, identity)) {
+                throw new AnalysisException(
+                        String.format("partition values not equal, res: %s, 
identity: %s", res, identity));
+            }
+        }
+        return res;
+    }
+
+    @Override
+    public PartitionKeyDesc generateRollUpPartitionKeyDesc(PartitionKeyDesc 
partitionKeyDesc,
+            MTMVPartitionInfo mvPartitionInfo, MTMVRelatedTableIf pctTable) 
throws AnalysisException {
+        Type partitionColumnType = MTMVPartitionUtil
+                .getPartitionColumnType(pctTable, 
mvPartitionInfo.getPartitionColByPctTable(pctTable));
+        Preconditions.checkState(partitionKeyDesc.getLowerValues().size() == 1,
+                "only support one partition column");
+        DateTimeV2Literal beginTime = dateTruncByOffset(
+                partitionKeyDesc.getLowerValues().get(0).getStringValue(), 
Optional.empty(), false);
+        PartitionValue lowerValue = new 
PartitionValue(dateTimeToStr(beginTime, partitionColumnType));
+        PartitionValue upperValue = 
getUpperValue(partitionKeyDesc.getUpperValues().get(0), beginTime,
+                partitionColumnType);
+        return PartitionKeyDesc.createFixed(
+                Collections.singletonList(lowerValue),
+                Collections.singletonList(upperValue));
+    }
+
+    @Override
+    public void analyze(MTMVPartitionInfo mvPartitionInfo) throws 
AnalysisException {
+        if (!TIME_UNITS.contains(this.timeUnit)) {
+            throw new AnalysisException(
+                    String.format("timeUnit not support: %s, only support: 
%s", this.timeUnit, TIME_UNITS));
+        }
+        List<BaseColInfo> pctInfos = mvPartitionInfo.getPctInfos();
+        for (BaseColInfo pctInfo : pctInfos) {
+            MTMVRelatedTableIf pctTable = 
MTMVUtil.getRelatedTable(pctInfo.getTableInfo());
+            PartitionType partitionType = 
pctTable.getPartitionType(MvccUtil.getSnapshotFromContext(pctTable));
+            if (partitionType == PartitionType.RANGE) {
+                Type partitionColumnType = 
MTMVPartitionUtil.getPartitionColumnType(pctTable, pctInfo.getColName());

Review Comment:
   `analyze()` now accepts any `DATE/DATEV2` partition column, but 
`generateRollUpPartitionKeyDesc()` still models the base range as a continuous 
`DATETIME` interval. For a `DATE`-partitioned table with daily ranges, 
`date_trunc(date_add(k2, INTERVAL 3 HOUR), 'day')` fails immediately: 
lower=`2025-07-24` maps to `2025-07-24 00:00`, while the exclusive upper bound 
`2025-07-25` is shifted to `2025-07-25 03:00` and truncated to `2025-07-25 
00:00`, so `getUpperValue()` throws `partition values not equal`. Either 
`DATE/DATEV2` should be rejected here, or the range rollup logic needs a 
discrete-date implementation instead of reusing the `DATETIME` boundary logic.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/info/MTMVPartitionDefinition.java:
##########
@@ -190,6 +197,18 @@ private static Pair<Integer, Expr> 
convertToLegacyRecursion(Expression expressio
         }
     }
 
+    private static TimestampArithmeticExpr 
convertDateAddSubToLegacy(Expression expression, String funcName) {
+        Pair<Integer, Expr> timeExprPair = 
convertToLegacyRecursion(expression.child(0));
+        if (timeExprPair.key() != 1) {
+            throw new AnalysisException("unsupported date arithmetic argument 
" + expression.toString());
+        }
+        if (!(expression.child(1) instanceof Literal)) {
+            throw new AnalysisException("date arithmetic offset should be 
literal " + expression.toString());

Review Comment:
   Supporting `HoursAdd/HoursSub` here is not enough to make the feature work 
for the user-facing syntax in the PR description. 
`analyzeAndTransferToMTMVPartitionInfo()` still derives `partitionColName` only 
when `functionCallExpression.getArgument(0)` is an `UnboundSlot` (the earlier 
logic around lines 85-90). For `PARTITION BY (date_trunc(date_add(k2, INTERVAL 
3 HOUR), 'day'))`, that argument is a nested function, so `partitionColName` 
becomes `null` and `fillPctInfos()` fails with `partition column can not find 
from sql select column` before this new conversion code ever runs. The same raw 
expression is also reparsed in `MTMVPlanUtil.analyzeQueryWithSql()` during 
`ensureMTMVQueryUsable()`, so schema-change validation would fail for these MVs 
too. We need to extract the underlying slot from the nested hour-add/sub 
expression in the initial analysis path as well, otherwise the new syntax is 
still unsupported.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPartitionExprDateTruncDateAddSub.java:
##########
@@ -0,0 +1,299 @@
+// 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.mtmv;
+
+import org.apache.doris.analysis.Expr;
+import org.apache.doris.analysis.FunctionCallExpr;
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.analysis.PartitionExprUtil;
+import org.apache.doris.analysis.PartitionKeyDesc;
+import org.apache.doris.analysis.PartitionValue;
+import org.apache.doris.analysis.StringLiteral;
+import org.apache.doris.analysis.TimestampArithmeticExpr;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.util.PropertyAnalyzer;
+import org.apache.doris.datasource.mvcc.MvccUtil;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import 
org.apache.doris.nereids.trees.expressions.functions.executable.DateTimeArithmetic;
+import 
org.apache.doris.nereids.trees.expressions.functions.executable.DateTimeExtractAndTransform;
+import org.apache.doris.nereids.trees.expressions.literal.BigIntLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal;
+import org.apache.doris.nereids.trees.expressions.literal.DateV2Literal;
+import org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Rollup service for expressions:
+ * date_trunc(date_add/date_sub(partition_col, interval N hour), 'unit')
+ */
+public class MTMVPartitionExprDateTruncDateAddSub implements 
MTMVPartitionExprService {
+    private static final Set<String> TIME_UNITS = ImmutableSet.of(
+            "year", "quarter", "week", "month", "day", "hour");
+    private final String timeUnit;
+    private final long offsetHours;
+
+    public MTMVPartitionExprDateTruncDateAddSub(FunctionCallExpr 
functionCallExpr) throws AnalysisException {
+        List<Expr> paramsExprs = functionCallExpr.getParams().exprs();
+        if (paramsExprs.size() != 2) {
+            throw new AnalysisException("date_trunc params exprs size should 
be 2.");
+        }
+        Expr dateTruncUnit = paramsExprs.get(1);
+        if (!(dateTruncUnit instanceof StringLiteral)) {
+            throw new AnalysisException("date_trunc param of time unit is not 
string literal.");
+        }
+        this.timeUnit = dateTruncUnit.getStringValue().toLowerCase();
+
+        Expr dateTruncArg = paramsExprs.get(0);
+        if (!(dateTruncArg instanceof TimestampArithmeticExpr)) {
+            throw new AnalysisException("date_trunc first argument should be 
date_add/date_sub in mtmv partition");
+        }
+        TimestampArithmeticExpr timestampArithmeticExpr = 
(TimestampArithmeticExpr) dateTruncArg;
+        if (timestampArithmeticExpr.getTimeUnit() != 
TimestampArithmeticExpr.TimeUnit.HOUR) {
+            throw new AnalysisException("only HOUR unit is supported in 
date_add/date_sub for mtmv partition");
+        }
+        if (!(timestampArithmeticExpr.getChild(1) instanceof LiteralExpr)) {
+            throw new AnalysisException("date_add/date_sub offset should be a 
literal");
+        }
+        long offset = parseOffsetHours((LiteralExpr) 
timestampArithmeticExpr.getChild(1));
+        String functionName = 
timestampArithmeticExpr.getFuncName().toLowerCase();
+        if ("date_sub".equals(functionName)) {
+            this.offsetHours = -offset;
+        } else if ("date_add".equals(functionName)) {
+            this.offsetHours = offset;
+        } else {
+            throw new AnalysisException("only date_add/date_sub is supported 
in mtmv partition");
+        }
+    }
+
+    @Override
+    public String getRollUpIdentity(PartitionKeyDesc partitionKeyDesc, 
Map<String, String> mvProperties)
+            throws AnalysisException {
+        String res = null;
+        Optional<String> dateFormat = getDateFormat(mvProperties);
+        List<List<PartitionValue>> inValues = partitionKeyDesc.getInValues();
+        for (int i = 0; i < inValues.size(); i++) {
+            PartitionValue partitionValue = inValues.get(i).get(0);
+            if (partitionValue.isNullPartition()) {
+                throw new AnalysisException("date_trunc + date_add/date_sub 
not support null partition value");
+            }
+            String identity = 
dateTruncByOffset(partitionValue.getStringValue(), dateFormat, 
false).toString();
+            if (i == 0) {
+                res = identity;
+            } else if (!Objects.equals(res, identity)) {
+                throw new AnalysisException(
+                        String.format("partition values not equal, res: %s, 
identity: %s", res, identity));
+            }
+        }
+        return res;
+    }
+
+    @Override
+    public PartitionKeyDesc generateRollUpPartitionKeyDesc(PartitionKeyDesc 
partitionKeyDesc,
+            MTMVPartitionInfo mvPartitionInfo, MTMVRelatedTableIf pctTable) 
throws AnalysisException {
+        Type partitionColumnType = MTMVPartitionUtil
+                .getPartitionColumnType(pctTable, 
mvPartitionInfo.getPartitionColByPctTable(pctTable));
+        Preconditions.checkState(partitionKeyDesc.getLowerValues().size() == 1,
+                "only support one partition column");
+        DateTimeV2Literal beginTime = dateTruncByOffset(
+                partitionKeyDesc.getLowerValues().get(0).getStringValue(), 
Optional.empty(), false);
+        PartitionValue lowerValue = new 
PartitionValue(dateTimeToStr(beginTime, partitionColumnType));
+        PartitionValue upperValue = 
getUpperValue(partitionKeyDesc.getUpperValues().get(0), beginTime,
+                partitionColumnType);
+        return PartitionKeyDesc.createFixed(
+                Collections.singletonList(lowerValue),
+                Collections.singletonList(upperValue));
+    }
+
+    @Override
+    public void analyze(MTMVPartitionInfo mvPartitionInfo) throws 
AnalysisException {
+        if (!TIME_UNITS.contains(this.timeUnit)) {
+            throw new AnalysisException(
+                    String.format("timeUnit not support: %s, only support: 
%s", this.timeUnit, TIME_UNITS));
+        }
+        List<BaseColInfo> pctInfos = mvPartitionInfo.getPctInfos();
+        for (BaseColInfo pctInfo : pctInfos) {
+            MTMVRelatedTableIf pctTable = 
MTMVUtil.getRelatedTable(pctInfo.getTableInfo());
+            PartitionType partitionType = 
pctTable.getPartitionType(MvccUtil.getSnapshotFromContext(pctTable));
+            if (partitionType == PartitionType.RANGE) {
+                Type partitionColumnType = 
MTMVPartitionUtil.getPartitionColumnType(pctTable, pctInfo.getColName());
+                if (!partitionColumnType.isDateType()) {
+                    throw new AnalysisException(
+                            "partitionColumnType should be date/datetime "
+                                    + "when PartitionType is range and expr is 
date_trunc + date_add/date_sub");
+                }
+            } else {
+                throw new AnalysisException("date_trunc + date_add/date_sub 
only support range partition");
+            }
+        }
+    }
+
+    @Override
+    public String toSql(MTMVPartitionInfo mvPartitionInfo) {
+        String funcName = offsetHours >= 0 ? "date_add" : "date_sub";
+        return String.format("date_trunc(%s(`%s`, INTERVAL %s HOUR), '%s')",

Review Comment:
   `toSql()` is reusing `mvPartitionInfo.getPartitionCol()` here, which is the 
MV output alias (`day_alias`, `week_alias`, ...), not the base column inside 
the stored legacy expression. For an MV created as `PARTITION BY 
(date_trunc(day_alias, 'day')) AS SELECT date_trunc(date_add(k2, INTERVAL 3 
HOUR), 'day') AS day_alias ...`, `SHOW CREATE MATERIALIZED VIEW` will now emit 
`date_trunc(date_add(day_alias, INTERVAL 3 HOUR), 'day')`. That DDL is not 
round-trippable: replaying it feeds the raw nested expression back into 
`MTMVPartitionDefinition`, where partition-column extraction still expects a 
bare slot. So this breaks `SHOW CREATE` / recreate semantics for the new 
feature.



-- 
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]

Reply via email to