github-actions[bot] commented on code in PR #62599:
URL: https://github.com/apache/doris/pull/62599#discussion_r3146826896
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/info/MTMVPartitionDefinition.java:
##########
@@ -105,6 +137,283 @@ public MTMVPartitionInfo
analyzeAndTransferToMTMVPartitionInfo(NereidsPlanner pl
return mtmvPartitionInfo;
}
+ private static final class ResolvedPartitionColumn {
+ private final String partitionColName;
+ private final String timeUnit;
+
+ private ResolvedPartitionColumn(String partitionColName, String
timeUnit) {
+ this.partitionColName = partitionColName;
+ this.timeUnit = timeUnit;
+ }
+ }
+
+ /**
+ * Resolve an MV output column name for MTMV partition tracking.
+ *
+ * The downstream create/reanalysis expects {@link
MTMVPartitionInfo#getPartitionCol()} to be a real MV output
+ * column name, so for raw nested forms like:
+ * PARTITION BY (date_trunc(date_add(k2, INTERVAL 3 HOUR), 'day'))
+ * we must find a matching SELECT column and use that name as partitionCol.
+ */
+ private static ResolvedPartitionColumn
resolvePartitionColumnForDateTrunc(NereidsPlanner planner,
+ Expression dateTruncArg, String timeUnit) {
+ if (isSlotLikePartitionArg(dateTruncArg)) {
+ return new ResolvedPartitionColumn(extractSlotName(dateTruncArg),
timeUnit);
+ }
+ CascadesContext cascadesContext = planner.getCascadesContext();
+ Plan planWithoutSink =
PartitionIncrementMaintainer.removeSink(planner.getRewrittenPlan());
+ Optional<DateTruncDateAddSubSignature> fullSig =
+
extractDateTruncDateAddSubSignature(PARTITION_BY_FUNCTION_NAME, dateTruncArg,
timeUnit);
+ if (fullSig.isPresent()) {
+ Optional<String> matchedColumn =
matchOutputColumnByDateTruncSignature(planWithoutSink, cascadesContext,
+ fullSig.get());
+ if (matchedColumn.isPresent()) {
+ return new ResolvedPartitionColumn(matchedColumn.get(), null);
+ }
+ }
+
+ Optional<HourOffsetSignature> offsetSig =
extractHourOffsetSignature(dateTruncArg);
+ if (offsetSig.isPresent()) {
+ Optional<String> matchedColumn =
matchOutputColumnByHourOffsetSignature(planWithoutSink, cascadesContext,
+ offsetSig.get());
+ if (matchedColumn.isPresent()) {
+ return new ResolvedPartitionColumn(matchedColumn.get(),
timeUnit);
+ }
+ }
+ throw new AnalysisException("partition expression must reference a
SELECT output column. "
+ + "Please expose the partition expression (or its
date_add/date_sub argument) in SELECT with an alias");
+ }
+
+ private static Optional<String> matchOutputColumnByDateTruncSignature(Plan
planWithoutSink,
+ CascadesContext cascadesContext, DateTruncDateAddSubSignature
signature) {
+ ExpressionNormalization normalization = new ExpressionNormalization();
+ ExpressionRewriteContext rewriteContext = new
ExpressionRewriteContext(cascadesContext);
+ List<String> matched = new ArrayList<>();
+ for (Slot outputSlot : planWithoutSink.getOutput()) {
+ Expression lineage =
ExpressionUtils.shuttleExpressionWithLineage(outputSlot, planWithoutSink);
+ lineage = normalization.rewrite(lineage, rewriteContext);
+ Optional<DateTruncDateAddSubSignature> sig =
extractDateTruncDateAddSubSignature(lineage);
+ if (sig.isPresent() && sig.get().equals(signature)) {
+ matched.add(outputSlot.getName());
+ }
+ }
+ if (matched.isEmpty()) {
+ return Optional.empty();
+ }
+ if (matched.size() != 1) {
+ throw new AnalysisException("partition expression matches multiple
SELECT columns: " + matched
+ + ", please use an explicit alias in PARTITION BY");
+ }
+ return Optional.of(matched.get(0));
+ }
+
+ private static Optional<String>
matchOutputColumnByHourOffsetSignature(Plan planWithoutSink,
+ CascadesContext cascadesContext, HourOffsetSignature signature) {
+ ExpressionNormalization normalization = new ExpressionNormalization();
+ ExpressionRewriteContext rewriteContext = new
ExpressionRewriteContext(cascadesContext);
+ List<String> matched = new ArrayList<>();
+ for (Slot outputSlot : planWithoutSink.getOutput()) {
+ Expression lineage =
ExpressionUtils.shuttleExpressionWithLineage(outputSlot, planWithoutSink);
+ lineage = normalization.rewrite(lineage, rewriteContext);
+ Optional<HourOffsetSignature> sig =
extractHourOffsetSignatureFromAny(lineage);
+ if (sig.isPresent() && sig.get().equals(signature)) {
+ matched.add(outputSlot.getName());
+ }
+ }
+ if (matched.isEmpty()) {
+ return Optional.empty();
+ }
+ if (matched.size() != 1) {
+ throw new AnalysisException("partition expression matches multiple
SELECT columns: " + matched
+ + ", please use an explicit alias in PARTITION BY");
+ }
+ return Optional.of(matched.get(0));
+ }
+
+ private static boolean isSlotLikePartitionArg(Expression expression) {
+ if (expression instanceof UnboundSlot || expression instanceof
SlotReference) {
+ return true;
+ } else if (expression instanceof Slot) {
+ return true;
+ } else if (expression instanceof Cast) {
+ return isSlotLikePartitionArg(((Cast) expression).child());
+ } else {
+ return false;
+ }
+ }
+
+ private static final class HourOffsetSignature {
+ private final String baseSlotName;
+ private final long offsetHours;
+
+ private HourOffsetSignature(String baseSlotName, long offsetHours) {
+ this.baseSlotName = baseSlotName;
+ this.offsetHours = offsetHours;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof HourOffsetSignature)) {
+ return false;
+ }
+ HourOffsetSignature that = (HourOffsetSignature) o;
+ return baseSlotName.equalsIgnoreCase(that.baseSlotName) &&
offsetHours == that.offsetHours;
+ }
+
+ @Override
+ public int hashCode() {
+ return baseSlotName.toLowerCase().hashCode() * 31 +
Long.hashCode(offsetHours);
+ }
+ }
+
+ private static Optional<HourOffsetSignature>
extractHourOffsetSignatureFromAny(Expression expression) {
+ Optional<HourOffsetSignature> direct =
extractHourOffsetSignature(expression);
+ if (direct.isPresent()) {
+ return direct;
+ }
+ if (expression instanceof DateTrunc && expression.arity() >= 1) {
+ return extractHourOffsetSignature(expression.child(0));
+ }
+ if (expression instanceof UnboundFunction
+ &&
PARTITION_BY_FUNCTION_NAME.equalsIgnoreCase(((UnboundFunction)
expression).getName())
+ && expression.arity() >= 1) {
+ return extractHourOffsetSignature(expression.child(0));
+ }
+ return Optional.empty();
+ }
+
+ private static Optional<HourOffsetSignature>
extractHourOffsetSignature(Expression expression) {
+ if (expression instanceof Cast) {
+ return extractHourOffsetSignature(((Cast) expression).child());
+ }
+ if (expression instanceof HoursAdd) {
+ String slotName = extractSlotName(expression.child(0));
+ if (slotName == null) {
+ return Optional.empty();
+ }
+ return Optional.of(new HourOffsetSignature(slotName,
extractIntervalHours(expression.child(1))));
+ } else if (expression instanceof HoursSub) {
+ String slotName = extractSlotName(expression.child(0));
+ if (slotName == null) {
+ return Optional.empty();
+ }
+ return Optional.of(new HourOffsetSignature(slotName,
-extractIntervalHours(expression.child(1))));
+ } else if (expression instanceof UnboundFunction) {
+ String name = ((UnboundFunction)
expression).getName().toLowerCase();
+ if ("hours_add".equals(name) || "date_add".equals(name)) {
+ String slotName = extractSlotName(expression.child(0));
Review Comment:
This is a distinct create-time issue from the existing refresh/equality
threads. `extractHourOffsetSignature()` strips `Cast`, and the matching
signature only keeps `baseSlotName + offset (+ unit)`, so
`date_trunc(date_add(k2, INTERVAL 3 HOUR), 'day')` and
`date_trunc(date_add(cast(k2 as date), INTERVAL 3 HOUR), 'day')` become
indistinguishable during `resolvePartitionColumnForDateTrunc()`.
That means a raw `PARTITION BY (date_trunc(date_add(cast(k2 as date),
INTERVAL 3 HOUR), 'day'))` can bind to the wrong SELECT output, or hit the
multiple-match error if the query also exposes the uncasted form. In the worst
case we persist the uncasted expression even though the user declared the
casted one. The matching key needs to preserve the wrapped expression shape,
not just the underlying slot name.
##########
regression-test/suites/mtmv_p0/test_rollup_partition_mtmv_cross_unit.groovy:
##########
@@ -0,0 +1,228 @@
+// 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.
+
+suite("test_rollup_partition_mtmv_cross_unit", "mtmv") {
+ // Comprehensive test for ALL valid PARTITION BY / SELECT unit combinations
+ // Valid: PARTITION unit <= SELECT unit (in granularity)
+ // hour < day < week < month < quarter < year
+ //
+ // Total: 21 combinations × 2 directions (add/sub) = 42 test cases
+
+ def createBaseTable = { tableName, partitions ->
+ sql """drop table if exists ${tableName}"""
+ sql """
+ CREATE TABLE ${tableName} (
+ id INT,
+ k2 DATETIME NOT NULL
+ )
+ PARTITION BY RANGE(k2) (
+ ${partitions}
+ )
+ DISTRIBUTED BY HASH(id) BUCKETS 2
+ PROPERTIES ('replication_num' = '1');
+ """
+ }
+
+ def createAndTestMV = { mvName, tableName, partitionExpr, selectUnit,
offset, isAdd ->
+ def funcName = isAdd ? "date_add" : "date_sub"
+ def aliasName = "${selectUnit}_alias"
+
+ sql """drop materialized view if exists ${mvName}"""
+ sql """
+ CREATE MATERIALIZED VIEW ${mvName}
+ BUILD IMMEDIATE REFRESH AUTO ON MANUAL
+ partition by (${aliasName})
Review Comment:
`partitionExpr` is never used here, and every MV is created as `partition by
(${aliasName})`. So this suite does not exercise any of the advertised
cross-unit cases; it only repeats same-unit alias-form creation.
Because of that, the `42 combinations` summary is misleading and the new
cross-unit logic can still regress without this test failing. The helper should
build the `PARTITION BY` clause from `partitionExpr` (or the suite should be
split into focused cases that actually cover those combinations).
--
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]