hello-stephen commented on code in PR #71241:
URL: https://github.com/apache/doris/pull/71241#discussion_r4779067142


##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmPlanSignatureEvaluator.java:
##########
@@ -0,0 +1,314 @@
+// 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.ivm;
+
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.MTMV;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.mtmv.BaseTableInfo;
+import org.apache.doris.mtmv.MTMVPlanUtil;
+import org.apache.doris.mtmv.MTMVRelation;
+import org.apache.doris.mysql.privilege.PrivPredicate;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import 
org.apache.doris.nereids.trees.plans.commands.ExplainCommand.ExplainLevel;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.OriginStatement;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Evaluates the live canonical IVM layout signature text for a materialized 
view without
+ * executing a refresh, mutating metadata, or consuming stream offsets.
+ */
+public final class IvmPlanSignatureEvaluator {
+
+    private IvmPlanSignatureEvaluator() {
+    }
+
+    /**
+     * Computes the live canonical IVM layout signature for {@code 
qualifiedMvName}, which may be
+     * {@code mv}, {@code db.mv}, or {@code catalog.db.mv} (each part 
optionally backtick-quoted).
+     *
+     * @param callerCtx caller's session context (used for default catalog/db 
and privilege checks)
+     * @param qualifiedMvName materialized view name in 1-, 2-, or 3-part 
qualified form
+     * @return the canonical signature string for unique-key IVM MVs, or empty 
for append-only detail IVM MVs
+     */
+    public static Optional<String> evaluate(ConnectContext callerCtx, String 
qualifiedMvName) {
+        return evaluate(callerCtx, callerCtx == null ? null : 
callerCtx.getStatementContext(), qualifiedMvName);
+    }
+
+    /**
+     * Computes the live canonical IVM layout signature for {@code 
qualifiedMvName}, enforcing that
+     * when {@code callerStmtCtx} already holds table locks, all tables needed 
by the MV were
+     * pre-collected before locking so table lock order is never inverted.
+     */
+    public static Optional<String> evaluate(ConnectContext callerCtx, 
StatementContext callerStmtCtx,
+            String qualifiedMvName) {
+        if (callerCtx == null) {
+            throw new AnalysisException("ivm_plan_signature requires an active 
session context");
+        }
+        List<String> parts = parseQualifiedName(qualifiedMvName);
+        String catalogName;
+        String dbName;
+        String mvName;
+        if (parts.size() == 1) {
+            catalogName = StringUtils.defaultIfBlank(
+                    callerCtx.getDefaultCatalog(), 
InternalCatalog.INTERNAL_CATALOG_NAME);
+            dbName = callerCtx.getDatabase();
+            mvName = parts.get(0);
+        } else if (parts.size() == 2) {
+            catalogName = StringUtils.defaultIfBlank(
+                    callerCtx.getDefaultCatalog(), 
InternalCatalog.INTERNAL_CATALOG_NAME);
+            dbName = parts.get(0);
+            mvName = parts.get(1);
+        } else {
+            catalogName = parts.get(0);
+            dbName = parts.get(1);
+            mvName = parts.get(2);
+        }
+
+        if (!InternalCatalog.INTERNAL_CATALOG_NAME.equals(catalogName)) {
+            throw new AnalysisException("Unsupported catalog '" + catalogName
+                    + "' for ivm_plan_signature: IVM materialized views only 
exist in internal catalog");
+        }
+        if (StringUtils.isBlank(dbName)) {
+            throw new AnalysisException("No database selected for 
ivm_plan_signature");
+        }
+
+        InternalCatalog catalog = Env.getCurrentInternalCatalog();
+        Database db = catalog.getDbNullable(dbName);
+        if (db == null) {
+            throw new AnalysisException("Unknown database '" + dbName + "'");
+        }
+        TableIf table = db.getTableNullable(mvName);
+        if (!(table instanceof MTMV)) {
+            throw new AnalysisException("Materialized view '" + dbName + "." + 
mvName + "' does not exist");
+        }
+        MTMV mtmv = (MTMV) table;
+        if (!Env.getCurrentEnv().getAccessManager().checkTblPriv(
+                callerCtx, InternalCatalog.INTERNAL_CATALOG_NAME, 
db.getFullName(), mtmv.getName(),
+                PrivPredicate.SHOW)) {
+            throw new AnalysisException("Permission denied: SHOW privilege 
required on materialized view '"
+                    + db.getFullName() + "." + mtmv.getName() + "'");
+        }
+        if (!mtmv.isIvm()) {
+            throw new AnalysisException("Materialized view '" + 
db.getFullName() + "." + mtmv.getName()
+                    + "' is not an IVM materialized view");
+        }
+        if (mtmv.isIvmAppendOnlyDupTable()) {
+            return Optional.empty();
+        }
+        verifyLockOrderSafety(mtmv, callerStmtCtx);
+        return Optional.of(computeCanonicalSignature(mtmv));
+    }
+
+    /**
+     * Best-effort lookup used during {@code CollectRelation} (before caller 
table locks are acquired)
+     * so the caller can lock the target MV and its base tables in the same 
ascending table-id order.
+     */
+    public static Optional<MTMV> 
resolveIvmMtmvForLockCollection(ConnectContext callerCtx, String 
qualifiedMvName) {
+        if (callerCtx == null || StringUtils.isBlank(qualifiedMvName)) {
+            return Optional.empty();
+        }
+        try {
+            List<String> parts = parseQualifiedName(qualifiedMvName);
+            String catalogName;
+            String dbName;
+            String mvName;
+            if (parts.size() == 1) {
+                catalogName = StringUtils.defaultIfBlank(
+                        callerCtx.getDefaultCatalog(), 
InternalCatalog.INTERNAL_CATALOG_NAME);
+                dbName = callerCtx.getDatabase();
+                mvName = parts.get(0);
+            } else if (parts.size() == 2) {
+                catalogName = StringUtils.defaultIfBlank(
+                        callerCtx.getDefaultCatalog(), 
InternalCatalog.INTERNAL_CATALOG_NAME);
+                dbName = parts.get(0);
+                mvName = parts.get(1);
+            } else {
+                catalogName = parts.get(0);
+                dbName = parts.get(1);
+                mvName = parts.get(2);
+            }
+            if (!InternalCatalog.INTERNAL_CATALOG_NAME.equals(catalogName) || 
StringUtils.isBlank(dbName)) {
+                return Optional.empty();
+            }
+            Database db = 
Env.getCurrentInternalCatalog().getDbNullable(dbName);
+            if (db == null) {
+                return Optional.empty();
+            }
+            TableIf table = db.getTableNullable(mvName);
+            if (!(table instanceof MTMV)) {
+                return Optional.empty();
+            }
+            MTMV mtmv = (MTMV) table;
+            if (!mtmv.isIvm() || mtmv.isIvmAppendOnlyDupTable()) {
+                return Optional.empty();
+            }
+            return Optional.of(mtmv);
+        } catch (AnalysisException ignored) {
+            return Optional.empty();
+        }
+    }
+
+    private static void verifyLockOrderSafety(MTMV mtmv, StatementContext 
callerStmtCtx) {
+        if (callerStmtCtx == null || !callerStmtCtx.hasTableLocks()) {
+            return;
+        }
+        Set<Long> callerLockedIds = new HashSet<>();
+        for (TableIf t : callerStmtCtx.getTables().values()) {
+            callerLockedIds.add(t.getId());
+        }
+        for (TableIf t : callerStmtCtx.getMtmvRelatedTables().values()) {
+            callerLockedIds.add(t.getId());
+        }
+        for (TableIf t : callerStmtCtx.getInsertTargetTables().values()) {
+            callerLockedIds.add(t.getId());
+        }
+        if (!callerLockedIds.contains(mtmv.getId())) {
+            throw new AnalysisException("ivm_plan_signature cannot evaluate a 
non-literal MV name '"
+                    + mtmv.getName() + "' while holding other table locks; 
pass a string literal MV name");
+        }
+        List<BaseTableInfo> requiredTables = new ArrayList<>();
+        mtmv.readMvLock();
+        try {
+            MTMVRelation relation = mtmv.getRelation();
+            if (relation != null) {
+                requiredTables.addAll(relation.getBaseTables());
+                requiredTables.addAll(relation.getBaseViews());
+            }
+        } finally {
+            mtmv.readMvUnlock();
+        }
+        for (BaseTableInfo baseTable : requiredTables) {
+            if (baseTable.isValid() && 
!callerLockedIds.contains(baseTable.getTableId())) {

Review Comment:
   [P2] Compare dependency locks with the currently resolved table
   
   For an IVM MV over an AGG_KEYS table `t` with `excluded_trigger_tables='t'` 
(as supported by `test_ivm_excluded_trigger_table`), replacing `t` with an 
identical-schema table makes a literal call fail:
   
   ```sql
   ALTER TABLE t REPLACE WITH TABLE replacement;
   SELECT ivm_plan_signature('mv');
   ```
   
   `CollectRelation` resolves and locks the replacement by name, but 
`MTMVRelation` still contains the original `BaseTableInfo.tableId` until 
refresh. This check therefore throws “cannot evaluate a non-literal MV name” 
despite the literal argument and correctly collected locks. Excluded tables 
need no stream rebuild (`IvmFullRefreshMTMV` skips them), so the live signature 
can otherwise be computed. Please validate against the currently collected 
dependency object rather than its deprecated persisted ID, and cover 
replacement before refresh in a test.



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