This is an automated email from the ASF dual-hosted git repository.

starocean999 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 9296ce31020 [feat](nereids)implement useDatabase command in nereids 
(#45600)
9296ce31020 is described below

commit 9296ce31020858c773e23d18398c8921ec1df94b
Author: Petrichor <xiaowe...@selectdb.com>
AuthorDate: Mon Dec 23 10:12:59 2024 +0800

    [feat](nereids)implement useDatabase command in nereids (#45600)
    
    Issue Number: close https://github.com/apache/doris/issues/42523
---
 .../antlr4/org/apache/doris/nereids/DorisParser.g4 |   4 +-
 .../doris/nereids/parser/LogicalPlanBuilder.java   |  20 +++-
 .../apache/doris/nereids/trees/plans/PlanType.java |   3 +-
 .../trees/plans/commands/use/UseCommand.java       | 115 +++++++++++++++++++++
 .../trees/plans/visitor/CommandVisitor.java        |   5 +
 .../doris/nereids/parser/NereidsParserTest.java    |   8 +-
 .../nereids_p0/ddl/use/use_command_nereids.out     |  13 +++
 .../nereids_p0/ddl/use/use_command_nereids.groovy  |  79 ++++++++++++++
 8 files changed, 236 insertions(+), 11 deletions(-)

diff --git a/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4 
b/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
index 97876c231fe..368847bac5f 100644
--- a/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
+++ b/fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
@@ -870,11 +870,11 @@ supportedUnsetStatement
 
 supportedUseStatement
      : SWITCH catalog=identifier                                               
       #switchCatalog
+     | USE (catalog=identifier DOT)? database=identifier                       
       #useDatabase
      ;
 
 unsupportedUseStatement
-    : USE (catalog=identifier DOT)? database=identifier                        
      #useDatabase
-    | USE ((catalog=identifier DOT)? database=identifier)? ATSIGN 
cluster=identifier #useCloudCluster
+    : USE ((catalog=identifier DOT)? database=identifier)? ATSIGN 
cluster=identifier #useCloudCluster
     ;
 
 unsupportedDmlStatement
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
index bb344e1b376..7bc328e238d 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
@@ -324,6 +324,7 @@ import 
org.apache.doris.nereids.DorisParser.UnsupportedContext;
 import org.apache.doris.nereids.DorisParser.UpdateAssignmentContext;
 import org.apache.doris.nereids.DorisParser.UpdateAssignmentSeqContext;
 import org.apache.doris.nereids.DorisParser.UpdateContext;
+import org.apache.doris.nereids.DorisParser.UseDatabaseContext;
 import org.apache.doris.nereids.DorisParser.UserIdentifyContext;
 import org.apache.doris.nereids.DorisParser.UserVariableContext;
 import org.apache.doris.nereids.DorisParser.WhereClauseContext;
@@ -683,6 +684,7 @@ import 
org.apache.doris.nereids.trees.plans.commands.refresh.RefreshCatalogComma
 import 
org.apache.doris.nereids.trees.plans.commands.refresh.RefreshDatabaseCommand;
 import 
org.apache.doris.nereids.trees.plans.commands.refresh.RefreshTableCommand;
 import org.apache.doris.nereids.trees.plans.commands.use.SwitchCommand;
+import org.apache.doris.nereids.trees.plans.commands.use.UseCommand;
 import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
 import org.apache.doris.nereids.trees.plans.logical.LogicalCTE;
 import org.apache.doris.nereids.trees.plans.logical.LogicalExcept;
@@ -5178,12 +5180,20 @@ public class LogicalPlanBuilder extends 
DorisParserBaseVisitor<Object> {
     }
 
     @Override
-    public Object visitSwitchCatalog(SwitchCatalogContext ctx) {
-        String catalogName = ctx.catalog.getText();
-        if (catalogName != null) {
-            return new SwitchCommand(catalogName);
+    public LogicalPlan visitSwitchCatalog(SwitchCatalogContext ctx) {
+        if (ctx.catalog != null) {
+            return new SwitchCommand(ctx.catalog.getText());
         }
-        throw new AnalysisException("catalog name can not be null");
+        throw new ParseException("catalog name can not be null");
+    }
+
+    @Override
+    public LogicalPlan visitUseDatabase(UseDatabaseContext ctx) {
+        if (ctx.database == null) {
+            throw new ParseException("database name can not be null");
+        }
+        return ctx.catalog != null ? new UseCommand(ctx.catalog.getText(), 
ctx.database.getText())
+                : new UseCommand(ctx.database.getText());
     }
 }
 
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/PlanType.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/PlanType.java
index dfc129f10b0..407610fbe08 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/PlanType.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/PlanType.java
@@ -266,5 +266,6 @@ public enum PlanType {
     CREATE_ROUTINE_LOAD_COMMAND,
     SHOW_TABLE_CREATION_COMMAND,
     SHOW_QUERY_PROFILE_COMMAND,
-    SWITCH_COMMAND
+    SWITCH_COMMAND,
+    USE_COMMAND
 }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/use/UseCommand.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/use/UseCommand.java
new file mode 100644
index 00000000000..9223e7d5ad6
--- /dev/null
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/use/UseCommand.java
@@ -0,0 +1,115 @@
+// 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.plans.commands.use;
+
+import org.apache.doris.analysis.StmtType;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.ErrorCode;
+import org.apache.doris.common.ErrorReport;
+import org.apache.doris.mysql.privilege.PrivPredicate;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.commands.Command;
+import org.apache.doris.nereids.trees.plans.commands.NoForward;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.StmtExecutor;
+
+import com.google.common.base.Strings;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+/**
+ * Representation of a use db statement.
+ */
+public class UseCommand extends Command implements NoForward {
+    private static final Logger LOG = LogManager.getLogger(UseCommand.class);
+    private String catalogName;
+    private String databaseName;
+
+    public UseCommand(String databaseName) {
+        super(PlanType.USE_COMMAND);
+        this.databaseName = databaseName;
+    }
+
+    public UseCommand(String catalogName, String databaseName) {
+        super(PlanType.USE_COMMAND);
+        this.catalogName = catalogName;
+        this.databaseName = databaseName;
+    }
+
+    @Override
+    public void run(ConnectContext ctx, StmtExecutor executor) throws 
Exception {
+        validate(ctx);
+        handleUseStmt(ctx);
+    }
+
+    @Override
+    public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
+        return visitor.visitUseCommand(this, context);
+    }
+
+    @Override
+    public StmtType stmtType() {
+        return StmtType.USE;
+    }
+
+    private void validate(ConnectContext context) throws AnalysisException {
+        if (Strings.isNullOrEmpty(databaseName)) {
+            ErrorReport.reportAnalysisException(ErrorCode.ERR_NO_DB_ERROR);
+        }
+        String currentCatalogName = catalogName == null ? 
ConnectContext.get().getDefaultCatalog() : catalogName;
+
+        if (!Env.getCurrentEnv().getAccessManager()
+                .checkDbPriv(ConnectContext.get(), currentCatalogName, 
databaseName, PrivPredicate.SHOW)) {
+            
ErrorReport.reportAnalysisException(ErrorCode.ERR_DBACCESS_DENIED_ERROR, 
context.getQualifiedUser(),
+                    databaseName);
+        }
+    }
+
+    /**
+     * Process use statement.
+     */
+    private void handleUseStmt(ConnectContext context) {
+        try {
+            if (catalogName != null) {
+                context.getEnv().changeCatalog(context, catalogName);
+            }
+            context.getEnv().changeDb(context, databaseName);
+        } catch (DdlException e) {
+            LOG.warn("The handling of the use command failed.", e);
+            context.getState().setError(e.getMysqlErrorCode(), e.getMessage());
+            return;
+        }
+        context.getState().setOk();
+    }
+
+    /**
+     * Generate sql string.
+     */
+    public String toSql() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("USE ");
+        if (catalogName != null) {
+            sb.append("`").append(catalogName).append("`.");
+        }
+        sb.append("`").append(databaseName).append("`");
+        return sb.toString();
+    }
+}
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/visitor/CommandVisitor.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/visitor/CommandVisitor.java
index d3749e94d57..122e513a08c 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/visitor/CommandVisitor.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/visitor/CommandVisitor.java
@@ -151,6 +151,7 @@ import 
org.apache.doris.nereids.trees.plans.commands.refresh.RefreshCatalogComma
 import 
org.apache.doris.nereids.trees.plans.commands.refresh.RefreshDatabaseCommand;
 import 
org.apache.doris.nereids.trees.plans.commands.refresh.RefreshTableCommand;
 import org.apache.doris.nereids.trees.plans.commands.use.SwitchCommand;
+import org.apache.doris.nereids.trees.plans.commands.use.UseCommand;
 
 /** CommandVisitor. */
 public interface CommandVisitor<R, C> {
@@ -697,4 +698,8 @@ public interface CommandVisitor<R, C> {
     default R visitSwitchCommand(SwitchCommand switchCommand, C context) {
         return visitCommand(switchCommand, context);
     }
+
+    default R visitUseCommand(UseCommand useCommand, C context) {
+        return visitCommand(useCommand, context);
+    }
 }
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/NereidsParserTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/NereidsParserTest.java
index 9a46b810586..3ce7e64560c 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/NereidsParserTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/NereidsParserTest.java
@@ -448,7 +448,7 @@ public class NereidsParserTest extends ParserTestBase {
 
         sql = "use a";
         plan = nereidsParser.parseSingle(sql);
-        Assertions.assertEquals(plan.stmtType(), StmtType.OTHER);
+        Assertions.assertEquals(plan.stmtType(), StmtType.USE);
 
         sql = "CREATE TABLE tbl (`id` INT NOT NULL) DISTRIBUTED BY HASH(`id`) 
BUCKETS 1";
         plan = nereidsParser.parseSingle(sql);
@@ -463,10 +463,12 @@ public class NereidsParserTest extends ParserTestBase {
     public void testParseUse() {
         NereidsParser nereidsParser = new NereidsParser();
         String sql = "use db";
-        nereidsParser.parseSingle(sql);
+        LogicalPlan logicalPlan = nereidsParser.parseSingle(sql);
+        Assertions.assertEquals(logicalPlan.stmtType(), StmtType.USE);
 
         sql = "use catalog.db";
-        nereidsParser.parseSingle(sql);
+        LogicalPlan logicalPlan1 = nereidsParser.parseSingle(sql);
+        Assertions.assertEquals(logicalPlan1.stmtType(), StmtType.USE);
     }
 
     @Test
diff --git a/regression-test/data/nereids_p0/ddl/use/use_command_nereids.out 
b/regression-test/data/nereids_p0/ddl/use/use_command_nereids.out
new file mode 100644
index 00000000000..17a7eaf6d7e
--- /dev/null
+++ b/regression-test/data/nereids_p0/ddl/use/use_command_nereids.out
@@ -0,0 +1,13 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !show_tables_db1 --
+tb1
+
+-- !show_tables_db2 --
+tb2
+
+-- !show_tables_db1 --
+tb1
+
+-- !show_tables_db2 --
+tb2
+
diff --git 
a/regression-test/suites/nereids_p0/ddl/use/use_command_nereids.groovy 
b/regression-test/suites/nereids_p0/ddl/use/use_command_nereids.groovy
new file mode 100644
index 00000000000..70e0f3403e5
--- /dev/null
+++ b/regression-test/suites/nereids_p0/ddl/use/use_command_nereids.groovy
@@ -0,0 +1,79 @@
+// 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("use_command_nereids") {
+    String db1 = "test_use_command_db1"
+    String db2 = "test_use_command_db2"
+    String tbl1 = "tb1"
+    String tbl2 = "tb2"
+
+    sql """drop database if exists ${db1};"""
+    sql """drop database if exists ${db2};"""
+    // create database
+    sql """create database ${db1};"""
+    sql """create database ${db2};"""
+    //cloud-mode
+    if (isCloudMode()) {
+        return
+    }
+    // use command
+    checkNereidsExecute("use ${db1};")
+
+    """drop table if exists ${tbl1};"""
+    sql """ create table ${db1}.${tbl1}
+           (
+            c1 bigint,
+            c2 bigint
+           )
+           ENGINE=OLAP
+           DUPLICATE KEY(c1, c2)
+           COMMENT 'OLAP'
+           DISTRIBUTED BY HASH(c1) BUCKETS 1
+           PROPERTIES (
+           "replication_num" = "1"
+           );
+    """
+    qt_show_tables_db1 """show tables;"""
+
+    checkNereidsExecute("use ${db2};")
+    """drop table if exists ${tbl2};"""
+    sql """ create table ${db2}.${tbl2}
+               (
+                c1 bigint,
+                c2 bigint
+               )
+               ENGINE=OLAP
+               DUPLICATE KEY(c1, c2)
+               COMMENT 'OLAP'
+               DISTRIBUTED BY HASH(c1) BUCKETS 1
+               PROPERTIES (
+               "replication_num" = "1"
+               );
+        """
+
+    qt_show_tables_db2 """show tables;"""
+
+    checkNereidsExecute("use internal.${db1};")
+    qt_show_tables_db1 """show tables;"""
+    checkNereidsExecute("use internal.${db2};")
+    qt_show_tables_db2 """show tables;"""
+
+    sql """drop table if exists ${db1}.${tbl1};"""
+    sql """drop table if exists ${db2}.${tbl2};"""
+    sql """drop database if exists ${db1};"""
+    sql """drop database if exists ${db2};"""
+}
\ No newline at end of file


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org
For additional commands, e-mail: commits-h...@doris.apache.org

Reply via email to