private RelNode applyMaterializedViewRewritingByText(
            ASTNode queryToRewriteAST,
            RelNode originalPlan,
            RelOptCluster optCluster,
            RelMetadataProvider metadataProvider) {
      if (!isMaterializedViewRewritingByTextEnabled()) {
        return originalPlan;
      }

      String expandedQueryText = null;
      try {
        unparseTranslator.applyTranslations(ctx.getTokenRewriteStream(), EXPANDED_QUERY_TOKEN_REWRITE_PROGRAM);
        expandedQueryText = ctx.getTokenRewriteStream().toString(
                EXPANDED_QUERY_TOKEN_REWRITE_PROGRAM,
                queryToRewriteAST.getTokenStartIndex(),
                queryToRewriteAST.getTokenStopIndex());

        ASTNode expandedAST = ParseUtils.parse(expandedQueryText, new Context(conf));
        
        Set<TableName> tablesUsedByOriginalPlan = getTablesUsed(removeSubqueries(originalPlan, metadataProvider));
        if (tablesUsedByOriginalPlan.isEmpty()) {
          return originalPlan;
        }
        
        RelNode mvScan = getMaterializedViewByAST(
            expandedAST, optCluster, ANY, db, tablesUsedByOriginalPlan, queryState::getValidTxnList, getTxnMgr());
        if (mvScan != null) {
          return mvScan;
        }

        if (!conf.getBoolVar(ConfVars.HIVE_MATERIALIZED_VIEW_ENABLE_AUTO_REWRITING_SUBQUERY_SQL)) {
          return originalPlan;
        }

        return new HiveMaterializedViewASTSubQueryRewriteShuttle(subQueryMap, queryToRewriteAST, expandedAST,
              HiveRelFactories.HIVE_BUILDER.create(optCluster, null),
              db, tablesUsedByOriginalPlan, queryState::getValidTxnList, getTxnMgr())
          .rewrite(originalPlan);
      } catch (Exception e) {
        LOG.warn("Automatic materialized view query rewrite failed. expanded query text: {} AST string {} ",
                expandedQueryText, queryToRewriteAST.toStringTree(), e);
        return originalPlan;
      }
    }
@return whether the specified cte fulfills all preconditions for materialization.
ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java