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

924060929 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 2c3fb787c05 [fix](dcl) Support WHERE and LIKE in SHOW CHARACTER SET 
(#70706)
2c3fb787c05 is described below

commit 2c3fb787c056aa3d4c38741006c67377253c7a82
Author: 924060929 <[email protected]>
AuthorDate: Thu Nov 19 14:14:48 2026 +0800

    [fix](dcl) Support WHERE and LIKE in SHOW CHARACTER SET (#70706)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Related PR: #43155
    
    `SHOW CHARACTER SET` and `SHOW CHARSET` reject the optional `WHERE` and
    `LIKE` clauses used by MySQL clients. Both forms now filter the existing
    FE row with the character set name, description, default collation and
    maximum length.
    
    - `LIKE` decodes the SQL string literal in the current SQL mode before
    matching the character set name with the existing case-insensitive
    pattern matcher.
    - `WHERE` binds the output column names in Nereids and evaluates the
    predicate over a typed single-row relation. A scoped internal MySQL text
    query uses the caller's session settings and prepared bindings. The
    outer SHOW owns its query state and sends the resulting rows in the
    client's protocol.
    - SHOW's internal filter skips SQL result caching and the automatic
    SELECT limit. The predicate can still read the original session
    variables.
    
    ### Testing
    
    - Local FE build and Checkstyle.
    - Targeted FE unit tests in `ShowCharsetCommandTest` and
    `NereidsParserTest`.
    - Regression suites `test_show_charset_command` and
    `test_show_charset_over_arrow_flight` in an isolated Docker cluster with
    the master FE and official 4.1.5 BE. Cases include escaping, changes to
    the session's collation, `sql_select_limit=0`, server-side prepared
    parameters, and Flight results from both the FE and BE evaluation paths.
    
    ### Release note
    
    Support `WHERE` and `LIKE` filters in `SHOW CHARACTER SET` and `SHOW
    CHARSET`.
    
    ### Check List (For Author)
    
    - Test: FE unit tests and SQL regression tests
    - Behavior changed: Yes (filtered character set commands are supported)
    - Does this need documentation: No
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex
    - Generated: Implementation, tests and PR description
    - Human review: Pending author review
---
 .../org/apache/doris/nereids/StatementContext.java |  44 ++++--
 .../doris/nereids/parser/LogicalPlanBuilder.java   |   9 +-
 .../nereids/rules/rewrite/AddDefaultLimit.java     |   7 +-
 .../trees/plans/commands/ShowCharsetCommand.java   |  70 +++++++++-
 .../java/org/apache/doris/qe/ConnectContext.java   |  33 +++++
 .../plans/commands/ShowCharsetCommandTest.java     | 149 +++++++++++++++++++++
 .../org/apache/doris/qe/ConnectContextTest.java    |  21 +++
 .../antlr4/org/apache/doris/nereids/DorisParser.g4 |   2 +-
 .../test_show_charset_over_arrow_flight.out        |   9 ++
 .../query_p0/show/test_show_charset_command.out    |  78 +++++++++++
 .../test_show_charset_over_arrow_flight.groovy}    |  17 +--
 .../query_p0/show/test_show_charset_command.groovy |  70 ++++++++--
 12 files changed, 467 insertions(+), 42 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
index abc041e46d3..2136c1cb1dc 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
@@ -243,6 +243,7 @@ public class StatementContext implements Closeable {
     private final Map<CTEId, Map<ExprId, ExprId>> producerExprIdRemap = new 
HashMap<>();
     private final Set<String> viewDdlSqlSet = Sets.newHashSet();
     private final SqlCacheContext sqlCacheContext;
+    private final boolean showQuery;
 
     // generate for next id for prepared statement's placeholders, which is
     // connection level
@@ -466,10 +467,16 @@ public class StatementContext implements Closeable {
      * StatementContext
      */
     private StatementContext(ConnectContext connectContext, OriginStatement 
originStatement, int initialId) {
+        this(connectContext, originStatement, initialId, false);
+    }
+
+    private StatementContext(ConnectContext connectContext, OriginStatement 
originStatement, int initialId,
+            boolean showQuery) {
         this.connectContext = connectContext;
         this.originStatement = originStatement;
+        this.showQuery = showQuery;
         exprIdGenerator = ExprId.createGenerator(initialId);
-        if (connectContext != null && connectContext.getSessionVariable() != 
null) {
+        if (!showQuery && connectContext != null && 
connectContext.getSessionVariable() != null) {
             if 
(CacheAnalyzer.canUseSqlCache(connectContext.getSessionVariable())) {
                 // cannot set the queryId here because the queryId for the 
current query is set
                 // in the subsequent steps.
@@ -511,25 +518,36 @@ public class StatementContext implements Closeable {
      * scope, ...) starts empty/fresh on the new context.
      */
     public StatementContext createNextExecuteContext() {
-        // Continue the id generators from the previous context. The cached 
analyzed plan from
-        // PREPARE (and every prior execution) already consumed ids from them, 
so a fresh
-        // generator starting at 0 would collide with those ids during this 
execution's planning.
-        StatementContext next = new StatementContext(connectContext, 
originStatement,
-                exprIdGenerator.getCurrentId());
+        StatementContext next = copyExpressionState(connectContext, showQuery);
+        // Carry over the short-circuit state used to execute the cached 
prepared plan.
+        next.idToComparisonSlot.putAll(idToComparisonSlot);
+        next.isShortCircuitQuery = isShortCircuitQuery;
+        next.hasNondeterministic = hasNondeterministic;
+        return next;
+    }
+
+    /**
+     * Create a context for a query that filters SHOW output using the already 
parsed predicate.
+     */
+    public StatementContext createShowQueryContext(ConnectContext 
internalContext) {
+        return copyExpressionState(internalContext, true);
+    }
+
+    public boolean isShowQuery() {
+        return showQuery;
+    }
+
+    private StatementContext copyExpressionState(ConnectContext context, 
boolean showQuery) {
+        // Already parsed or analyzed expressions may hold ids allocated by 
this context.
+        StatementContext next = new StatementContext(context, originStatement,
+                exprIdGenerator.getCurrentId(), showQuery);
         next.objectIdGenerator.resetId(objectIdGenerator.getCurrentId());
         next.relationIdGenerator.resetId(relationIdGenerator.getCurrentId());
         next.cteIdGenerator.resetId(cteIdGenerator.getCurrentId());
         next.talbeIdGenerator.resetId(talbeIdGenerator.getCurrentId());
         
next.placeHolderIdGenerator.resetId(placeHolderIdGenerator.getCurrentId());
-        // Placeholder bindings of this EXECUTE, and the comparison-slot 
registry used to replace
-        // conjuncts on the cached short-circuit plan without re-planning.
         next.idToPlaceholderRealExpr.putAll(idToPlaceholderRealExpr);
-        next.idToComparisonSlot.putAll(idToComparisonSlot);
         next.placeholders = new ArrayList<>(placeholders);
-        // Short-circuit gating flags are computed by the previous execution's 
planning and gate
-        // the fast path of this execution before any re-planning happens.
-        next.isShortCircuitQuery = isShortCircuitQuery;
-        next.hasNondeterministic = hasNondeterministic;
         return next;
     }
 
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 c7bac094768..e14f4a5d8ff 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
@@ -7168,7 +7168,14 @@ public class LogicalPlanBuilder extends 
DorisParserBaseVisitor<Object> {
 
     @Override
     public LogicalPlan visitShowCharset(ShowCharsetContext ctx) {
-        return new ShowCharsetCommand();
+        if (ctx.wildWhere() != null) {
+            if (ctx.wildWhere().LIKE() != null) {
+                return new ShowCharsetCommand(
+                        
SqlLiteralUtils.parseStringLiteral(ctx.wildWhere().STRING_LITERAL().getText()), 
null);
+            }
+            return new ShowCharsetCommand(null, 
getExpression(ctx.wildWhere().expression()));
+        }
+        return new ShowCharsetCommand(null, null);
     }
 
     @Override
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AddDefaultLimit.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AddDefaultLimit.java
index c54439b1774..336093e091e 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AddDefaultLimit.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AddDefaultLimit.java
@@ -38,11 +38,12 @@ public class AddDefaultLimit extends 
DefaultPlanRewriter<StatementContext> imple
 
     @Override
     public Plan rewriteRoot(Plan plan, JobContext jobContext) {
-        if (jobContext.getCascadesContext().getConnectContext() == null
-                || 
!jobContext.getCascadesContext().getConnectContext().getState().isQuery()) {
+        StatementContext statementContext = 
jobContext.getCascadesContext().getStatementContext();
+        ConnectContext ctx = 
jobContext.getCascadesContext().getConnectContext();
+        if (ctx == null || !ctx.getState().isQuery() || 
statementContext.isShowQuery()) {
             return plan;
         }
-        return plan.accept(this, 
jobContext.getCascadesContext().getStatementContext());
+        return plan.accept(this, statementContext);
     }
 
     @Override
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommand.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommand.java
index 7ff2272f65f..cdd5170c892 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommand.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommand.java
@@ -19,19 +19,38 @@ package org.apache.doris.nereids.trees.plans.commands;
 
 import org.apache.doris.catalog.Column;
 import org.apache.doris.catalog.ScalarType;
+import org.apache.doris.common.PatternMatcherWrapper;
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.analyzer.UnboundResultSink;
+import org.apache.doris.nereids.glue.LogicalPlanAdapter;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
 import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation;
 import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.qe.AutoCloseConnectContext;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.ShowResultSet;
 import org.apache.doris.qe.ShowResultSetMetaData;
 import org.apache.doris.qe.StmtExecutor;
+import org.apache.doris.statistics.repository.ResultRow;
 
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
 import java.util.List;
+import java.util.stream.Collectors;
 
 /**
- * Represents the command for SHOW CHARSETG
+ * Represents the command for SHOW CHARACTER SET
  */
 public class ShowCharsetCommand extends ShowCommand {
     private static final ShowResultSetMetaData CHARSET_META_DATA =
@@ -42,8 +61,13 @@ public class ShowCharsetCommand extends ShowCommand {
                     .addColumn(new Column("Maxlen", 
ScalarType.createVarchar(10)))
                     .build();
 
-    public ShowCharsetCommand() {
+    private final String likePattern;
+    private final Expression whereClause;
+
+    public ShowCharsetCommand(String likePattern, Expression whereClause) {
         super(PlanType.SHOW_CHARSET_COMMAND);
+        this.likePattern = likePattern;
+        this.whereClause = whereClause;
     }
 
     @Override
@@ -53,7 +77,14 @@ public class ShowCharsetCommand extends ShowCommand {
 
     @Override
     public ShowResultSet doRun(ConnectContext ctx, StmtExecutor executor) 
throws Exception {
+        if (whereClause != null) {
+            return new ShowResultSet(getMetaData(), filterRows(ctx, executor));
+        }
         List<List<String>> rows = Lists.newArrayList();
+        if (likePattern != null && 
!PatternMatcherWrapper.createMysqlPattern(likePattern, false)
+                .match(ctx.getSessionVariable().getCharsetServer())) {
+            return new ShowResultSet(getMetaData(), rows);
+        }
         List<String> row = Lists.newArrayList();
         // | utf8mb4 | UTF-8 Unicode | utf8mb4_general_ci | 4|
         row.add(ctx.getSessionVariable().getCharsetServer());
@@ -65,6 +96,41 @@ public class ShowCharsetCommand extends ShowCommand {
         return new ShowResultSet(getMetaData(), rows);
     }
 
+    private List<List<String>> filterRows(ConnectContext ctx, StmtExecutor 
executor) throws UserException {
+        try (AutoCloseConnectContext scope = new 
AutoCloseConnectContext(ctx.createInternalQueryContext());
+                StatementContext statementContext = ctx.getStatementContext()
+                        .createShowQueryContext(scope.connectContext)) {
+            ConnectContext internalContext = scope.connectContext;
+            internalContext.setStatementContext(statementContext);
+
+            List<NamedExpression> projects = ImmutableList.of(
+                    new Alias(new 
StringLiteral(ctx.getSessionVariable().getCharsetServer()), "Charset"),
+                    new Alias(new StringLiteral("UTF-8 Unicode"), 
"Description"),
+                    new Alias(new 
StringLiteral(ctx.getSessionVariable().getCollationConnection()),
+                            "Default collation"),
+                    new Alias(new IntegerLiteral(4), "Maxlen"));
+            LogicalOneRowRelation relation = new LogicalOneRowRelation(
+                    StatementScopeIdGenerator.newRelationId(), projects);
+            LogicalFilter<LogicalOneRowRelation> filter = new LogicalFilter<>(
+                    ExpressionUtils.extractConjunctionToSet(whereClause), 
relation);
+            LogicalPlanAdapter adapter = new LogicalPlanAdapter(new 
UnboundResultSink<>(filter), statementContext);
+            adapter.setOrigStmt(executor.getOriginStmt());
+            StmtExecutor internalExecutor = new StmtExecutor(internalContext, 
adapter);
+            internalContext.setExecutor(internalExecutor);
+            executor.setCancelDelegate(internalExecutor::cancel);
+            // Publish the delegate before checking for cancellation that 
arrived before publication.
+            Status cancelReason = executor.getPendingCancelReason();
+            if (cancelReason != null) {
+                throw new UserException(cancelReason.getErrorMsg());
+            }
+            return internalExecutor.executeInternalQuery().stream()
+                    .map(ResultRow::getValues)
+                    .collect(Collectors.toList());
+        } finally {
+            executor.clearCancelDelegate();
+        }
+    }
+
     @Override
     public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
         return visitor.visitShowCharsetCommand(this, context);
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/ConnectContext.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/ConnectContext.java
index ff739ffa37b..c84411ababf 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/ConnectContext.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/ConnectContext.java
@@ -462,6 +462,39 @@ public class ConnectContext {
         init();
     }
 
+    /**
+     * Isolate a read-only internal query from the client protocol and 
statement state while
+     * retaining the caller's session identity, name resolution and variable 
values.
+     * The caller still owns the session and its cleanup.
+     */
+    public ConnectContext createInternalQueryContext() {
+        return new ConnectContext(this);
+    }
+
+    private ConnectContext(ConnectContext parent) {
+        protocolAdapter = new MysqlProtocolAdapter(new DummyMysqlChannel());
+        command = MysqlCommand.COM_QUERY;
+        state = new QueryState();
+        sessionVariable = 
VariableMgr.cloneSessionVariable(parent.sessionVariable);
+        userVars.putAll(parent.userVars);
+        env = parent.env;
+        currentUserIdentity = parent.currentUserIdentity;
+        authenticatedPrincipal = parent.authenticatedPrincipal;
+        authenticatedRoles = parent.authenticatedRoles;
+        sessionContext = parent.sessionContext;
+        isTempUser = parent.isTempUser;
+        remoteIP = parent.remoteIP;
+        connectionId = parent.connectionId;
+        startTime = parent.startTime;
+        startTimeInstant = parent.startTimeInstant;
+        lastQueryId = parent.lastQueryId;
+        computeGroup = parent.computeGroup;
+        cloudCluster = parent.cloudCluster;
+        restoreNameSpaceContext(parent.getNameSpaceContext());
+        // Borrow the caller's temporary-table namespace without registering a 
new session.
+        sessionId = parent.sessionId;
+    }
+
     /** The context of a MySQL client connection. */
     public static ConnectContext forMysql(StreamConnection connection) {
         return new ConnectContext(connection);
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommandTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommandTest.java
new file mode 100644
index 00000000000..c1208812761
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/ShowCharsetCommandTest.java
@@ -0,0 +1,149 @@
+// 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;
+
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.ShowResultSet;
+import org.apache.doris.qe.StmtExecutor;
+import org.apache.doris.thrift.TStatusCode;
+import org.apache.doris.thrift.TUniqueId;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.ImmutableList;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+class ShowCharsetCommandTest extends TestWithFeService {
+    private static final List<List<String>> EXPECTED_ROWS = ImmutableList.of(
+            ImmutableList.of("utf8mb4", "UTF-8 Unicode", "utf8mb4_0900_bin", 
"4"));
+
+    private ShowResultSet execute(String sql) throws Exception {
+        connectContext.getState().reset();
+        StmtExecutor executor = new StmtExecutor(connectContext, sql);
+        ShowCharsetCommand command = (ShowCharsetCommand) new 
NereidsParser().parseSingle(sql);
+        StatementContext statementContext = 
connectContext.getStatementContext();
+        TUniqueId queryId = new TUniqueId(1, 2);
+        connectContext.setQueryId(queryId);
+        try {
+            return command.doRun(connectContext, executor);
+        } finally {
+            Assertions.assertSame(connectContext, ConnectContext.get());
+            Assertions.assertSame(executor, connectContext.getExecutor());
+            Assertions.assertSame(statementContext, 
connectContext.getStatementContext());
+            Assertions.assertSame(queryId, connectContext.queryId());
+            Assertions.assertFalse(connectContext.getState().isInternal());
+            Assertions.assertFalse(connectContext.getState().isQuery());
+        }
+    }
+
+    @Test
+    void testUnfiltered() throws Exception {
+        Assertions.assertEquals(EXPECTED_ROWS, execute("SHOW 
CHARSET").getResultRows());
+        ShowResultSet result = execute("SHOW CHARACTER SET");
+        Assertions.assertEquals(EXPECTED_ROWS, result.getResultRows());
+        Assertions.assertEquals("Charset", 
result.getMetaData().getColumn(0).getName());
+        Assertions.assertEquals("Default collation", 
result.getMetaData().getColumn(2).getName());
+    }
+
+    @Test
+    void testLike() throws Exception {
+        for (String pattern : ImmutableList.of("utf8mb4", "utf8%", "utf8mb_", 
"UTF8%", "%")) {
+            Assertions.assertEquals(EXPECTED_ROWS,
+                    execute("SHOW CHARACTER SET LIKE '" + pattern + 
"'").getResultRows(), pattern);
+        }
+        Assertions.assertTrue(execute("SHOW CHARSET LIKE 
'latin%'").getResultRows().isEmpty());
+        Assertions.assertTrue(execute("SHOW CHARSET LIKE 
''").getResultRows().isEmpty());
+    }
+
+    @Test
+    void testWhere() throws Exception {
+        Assertions.assertEquals(EXPECTED_ROWS,
+                execute("SHOW CHARACTER SET WHERE charset = 
'utf8mb4'").getResultRows());
+        Assertions.assertEquals(EXPECTED_ROWS,
+                execute("SHOW CHARSET WHERE CHARSET = 'utf8mb4' AND Maxlen >= 
4").getResultRows());
+        Assertions.assertEquals(EXPECTED_ROWS,
+                execute("SHOW CHARSET WHERE Charset = 'latin1' OR Description 
= 'UTF-8 Unicode'").getResultRows());
+        Assertions.assertEquals(EXPECTED_ROWS,
+                execute("SHOW CHARSET WHERE `Default collation` = 
'utf8mb4_0900_bin'").getResultRows());
+        Assertions.assertTrue(execute("SHOW CHARSET WHERE Charset = 
'latin1'").getResultRows().isEmpty());
+        Assertions.assertTrue(execute("SHOW CHARSET WHERE Maxlen > 
4").getResultRows().isEmpty());
+        Assertions.assertEquals(EXPECTED_ROWS,
+                execute("SHOW CHARSET WHERE upper(Charset) = 'UTF8MB4' AND 
Maxlen + 1 = 5").getResultRows());
+    }
+
+    @Test
+    void testNullAndConstantPredicates() throws Exception {
+        Assertions.assertEquals(EXPECTED_ROWS, execute("SHOW CHARSET WHERE 
TRUE").getResultRows());
+        Assertions.assertTrue(execute("SHOW CHARSET WHERE 
FALSE").getResultRows().isEmpty());
+        Assertions.assertTrue(execute("SHOW CHARSET WHERE 
NULL").getResultRows().isEmpty());
+        Assertions.assertTrue(execute("SHOW CHARSET WHERE Charset = 
NULL").getResultRows().isEmpty());
+        Assertions.assertEquals(EXPECTED_ROWS,
+                execute("SHOW CHARSET WHERE Charset IS NOT 
NULL").getResultRows());
+    }
+
+    @Test
+    void testCancelledBeforeFilterStarts() {
+        String sql = "SHOW CHARSET WHERE TRUE";
+        StmtExecutor executor = new StmtExecutor(connectContext, sql);
+        ShowCharsetCommand command = (ShowCharsetCommand) new 
NereidsParser().parseSingle(sql);
+        Status reason = new Status(TStatusCode.CANCELLED, "cancelled before 
SHOW filter starts");
+        executor.cancel(reason, false);
+
+        UserException exception = Assertions.assertThrows(UserException.class,
+                () -> command.doRun(connectContext, executor));
+        Assertions.assertEquals(reason.getErrorMsg(), 
exception.getDetailMessage());
+        Assertions.assertSame(connectContext, ConnectContext.get());
+    }
+
+    @Test
+    void testUnknownColumn() {
+        RuntimeException exception = 
Assertions.assertThrows(RuntimeException.class,
+                () -> execute("SHOW CHARSET WHERE unknown_column = 
'utf8mb4'"));
+        
Assertions.assertTrue(exception.getMessage().contains("unknown_column"));
+    }
+
+    @Test
+    void testSessionValues() throws Exception {
+        boolean originalEnableSqlCache = 
connectContext.getSessionVariable().isEnableSqlCache();
+        String originalCharset = 
connectContext.getSessionVariable().charsetServer;
+        String originalCollation = 
connectContext.getSessionVariable().collationConnection;
+        try {
+            connectContext.getSessionVariable().setEnableSqlCache(true);
+            Assertions.assertEquals(EXPECTED_ROWS, execute("SHOW CHARSET WHERE 
TRUE").getResultRows());
+            connectContext.getSessionVariable().charsetServer = "test_charset";
+            connectContext.getSessionVariable().collationConnection = 
"test_collation";
+            List<List<String>> expected = execute("SHOW 
CHARSET").getResultRows();
+            Assertions.assertEquals(expected, execute("SHOW CHARSET LIKE 
'test_%'").getResultRows());
+            Assertions.assertEquals(expected, execute("SHOW CHARSET WHERE 
TRUE").getResultRows());
+            
Assertions.assertTrue(connectContext.getSessionVariable().isEnableSqlCache());
+            Assertions.assertEquals(expected, execute("SHOW CHARSET WHERE 
Charset = 'test_charset' "
+                    + "AND `Default collation` = 
'test_collation'").getResultRows());
+            Assertions.assertTrue(execute("SHOW CHARSET WHERE Charset = 
'utf8mb4'").getResultRows().isEmpty());
+        } finally {
+            
connectContext.getSessionVariable().setEnableSqlCache(originalEnableSqlCache);
+            connectContext.getSessionVariable().charsetServer = 
originalCharset;
+            connectContext.getSessionVariable().collationConnection = 
originalCollation;
+        }
+    }
+}
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java
index 06fa707fcc2..e180fe71e9e 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java
@@ -32,8 +32,12 @@ import org.apache.doris.common.Config;
 import org.apache.doris.common.DdlException;
 import org.apache.doris.common.ErrorCode;
 import org.apache.doris.common.Pair;
+import org.apache.doris.connector.ConnectorSessionBuilder;
+import org.apache.doris.connector.spi.ConnectorSession;
 import org.apache.doris.datasource.CatalogMgr;
+import org.apache.doris.datasource.DelegatedCredential;
 import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.datasource.SessionContext;
 import org.apache.doris.mysql.MysqlCapability;
 import org.apache.doris.mysql.MysqlCommand;
 import org.apache.doris.mysql.privilege.AccessControllerManager;
@@ -82,6 +86,23 @@ public class ConnectContextTest {
         
Mockito.when(catalogMgr.getCatalog(Mockito.anyString())).thenReturn(internalCatalog);
     }
 
+    @Test
+    public void testInternalQueryInheritsDelegatedSession() {
+        ConnectContext parent = new ConnectContext();
+        
parent.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("testUser",
 "%"));
+        SessionContext session = SessionContext.of("test-session",
+                new DelegatedCredential(DelegatedCredential.Type.ID_TOKEN, 
"test-token"));
+        parent.setSessionContext(session);
+
+        ConnectContext child = parent.createInternalQueryContext();
+        ConnectorSession connectorSession = ConnectorSessionBuilder.from(child)
+                .withUserSessionCapability(true)
+                .build();
+        Assertions.assertEquals(session.getSessionId(), 
connectorSession.getSessionId());
+        Assertions.assertEquals("test-token", 
connectorSession.getDelegatedCredential().orElseThrow().getToken());
+        
Assertions.assertTrue(ConnectorSessionBuilder.from(child).build().getDelegatedCredential().isEmpty());
+    }
+
     @Test
     public void testResetConnectionClearsSessionState() throws Exception {
         ConnectContext ctx = new ConnectContext();
diff --git 
a/fe/fe-sql-parser/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4 
b/fe/fe-sql-parser/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
index 380d614c6bc..09ce1373744 100644
--- a/fe/fe-sql-parser/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
+++ b/fe/fe-sql-parser/src/main/antlr4/org/apache/doris/nereids/DorisParser.g4
@@ -605,7 +605,7 @@ showStatement
     | SHOW EXPORT ((FROM | IN) database=multipartIdentifier)? wildWhere?
         sortClause? limitClause?                                               
     #showExport
     | SHOW LAST INSERT                                                         
     #showLastInsert
-    | SHOW ((CHAR SET) | CHARSET)                                              
     #showCharset
+    | SHOW ((CHAR SET) | CHARSET) wildWhere?                                   
     #showCharset
     | SHOW DELETE ((FROM | IN) database=multipartIdentifier)?                  
     #showDelete
     | SHOW CREATE statementScope? FUNCTION functionIdentifier
         LEFT_PAREN functionArguments? RIGHT_PAREN
diff --git 
a/regression-test/data/arrow_flight_sql_p0/test_show_charset_over_arrow_flight.out
 
b/regression-test/data/arrow_flight_sql_p0/test_show_charset_over_arrow_flight.out
new file mode 100644
index 00000000000..d801aa583f1
--- /dev/null
+++ 
b/regression-test/data/arrow_flight_sql_p0/test_show_charset_over_arrow_flight.out
@@ -0,0 +1,9 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !arrow_flight_sql_show_charset --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !arrow_flight_sql_show_charset_on_be --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !arrow_flight_sql_show_charset_no_match --
+
diff --git a/regression-test/data/query_p0/show/test_show_charset_command.out 
b/regression-test/data/query_p0/show/test_show_charset_command.out
index dd9ca552bf7..28438b95d15 100644
--- a/regression-test/data/query_p0/show/test_show_charset_command.out
+++ b/regression-test/data/query_p0/show/test_show_charset_command.out
@@ -2,3 +2,81 @@
 -- !cmd --
 utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
 
+-- !character_set --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_exact --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_percent --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_underscore --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_case --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_no_match --
+
+-- !like_empty --
+
+-- !where_charset --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_no_match --
+
+-- !where_like --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_not_like --
+
+-- !where_and --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_or --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_collation --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_numeric --
+
+-- !where_expression --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_true --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_false --
+
+-- !where_null --
+
+-- !where_equals_null --
+
+-- !where_not_null --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_backspace --
+
+-- !like_backslash --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !like_no_backslash_escapes --
+
+-- !where_before_collation_change --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !where_after_collation_change --
+utf8mb4        UTF-8 Unicode   utf8mb4_general_ci      4
+
+-- !where_with_select_limit --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !select_limit_still_applies --
+
+-- !prepared_match --
+utf8mb4        UTF-8 Unicode   utf8mb4_0900_bin        4
+
+-- !prepared_no_match --
+
diff --git 
a/regression-test/suites/query_p0/show/test_show_charset_command.groovy 
b/regression-test/suites/arrow_flight_sql_p0/test_show_charset_over_arrow_flight.groovy
similarity index 67%
copy from regression-test/suites/query_p0/show/test_show_charset_command.groovy
copy to 
regression-test/suites/arrow_flight_sql_p0/test_show_charset_over_arrow_flight.groovy
index 30ad3631b94..f6dc581fdff 100644
--- a/regression-test/suites/query_p0/show/test_show_charset_command.groovy
+++ 
b/regression-test/suites/arrow_flight_sql_p0/test_show_charset_over_arrow_flight.groovy
@@ -15,16 +15,9 @@
 // specific language governing permissions and limitations
 // under the License.
 
-suite("test_show_charset_command", "query,charset") {
-    try {
-        // Execute the SHOW CHARSET command and verify the output
-        checkNereidsExecute("SHOW CHARSET")
-        qt_cmd("SHOW CHARSET")
-
-    } catch (Exception e) {
-        // Log any exceptions that occur during testing
-        log.error("Failed to execute SHOW CHARSET command", e)
-        throw e
-    }
+suite("test_show_charset_over_arrow_flight", "arrow_flight_sql") {
+    order_qt_arrow_flight_sql_show_charset "SHOW CHARSET WHERE TRUE"
+    // RAND() is evaluated by a backend, exercising the internal result 
receiver.
+    order_qt_arrow_flight_sql_show_charset_on_be "SHOW CHARSET WHERE RAND() >= 
0"
+    order_qt_arrow_flight_sql_show_charset_no_match "SHOW CHARACTER SET WHERE 
Maxlen < 4"
 }
-
diff --git 
a/regression-test/suites/query_p0/show/test_show_charset_command.groovy 
b/regression-test/suites/query_p0/show/test_show_charset_command.groovy
index 30ad3631b94..4923cd05592 100644
--- a/regression-test/suites/query_p0/show/test_show_charset_command.groovy
+++ b/regression-test/suites/query_p0/show/test_show_charset_command.groovy
@@ -16,15 +16,65 @@
 // under the License.
 
 suite("test_show_charset_command", "query,charset") {
-    try {
-        // Execute the SHOW CHARSET command and verify the output
-        checkNereidsExecute("SHOW CHARSET")
-        qt_cmd("SHOW CHARSET")
-
-    } catch (Exception e) {
-        // Log any exceptions that occur during testing
-        log.error("Failed to execute SHOW CHARSET command", e)
-        throw e
+    checkNereidsExecute("SHOW CHARSET")
+    order_qt_cmd "SHOW CHARSET"
+    order_qt_character_set "SHOW CHARACTER SET"
+
+    order_qt_like_exact "SHOW CHARACTER SET LIKE 'utf8mb4'"
+    order_qt_like_percent "SHOW CHARSET LIKE 'utf8%'"
+    order_qt_like_underscore "SHOW CHARSET LIKE 'utf8mb_'"
+    order_qt_like_case "SHOW CHARSET LIKE 'UTF8%'"
+    order_qt_like_no_match "SHOW CHARACTER SET LIKE 'latin%'"
+    order_qt_like_empty "SHOW CHARSET LIKE ''"
+
+    order_qt_where_charset "SHOW CHARACTER SET WHERE charset = 'utf8mb4'"
+    order_qt_where_no_match "SHOW CHARSET WHERE Charset = 'latin1'"
+    order_qt_where_like "SHOW CHARSET WHERE Charset LIKE 'utf8%'"
+    order_qt_where_not_like "SHOW CHARSET WHERE Charset NOT LIKE 'utf8%'"
+    order_qt_where_and "SHOW CHARSET WHERE CHARSET = 'utf8mb4' AND Maxlen >= 4"
+    order_qt_where_or "SHOW CHARSET WHERE Charset = 'latin1' OR Description = 
'UTF-8 Unicode'"
+    order_qt_where_collation "SHOW CHARSET WHERE `Default collation` = 
'utf8mb4_0900_bin'"
+    order_qt_where_numeric "SHOW CHARSET WHERE Maxlen > 4"
+    order_qt_where_expression "SHOW CHARSET WHERE upper(Charset) = 'UTF8MB4' 
AND Maxlen + 1 = 5"
+    order_qt_where_true "SHOW CHARSET WHERE TRUE"
+    order_qt_where_false "SHOW CHARSET WHERE FALSE"
+    order_qt_where_null "SHOW CHARSET WHERE NULL"
+    order_qt_where_equals_null "SHOW CHARSET WHERE Charset = NULL"
+    order_qt_where_not_null "SHOW CHARSET WHERE Charset IS NOT NULL"
+
+    sql "SET sql_mode = ''"
+    order_qt_like_backspace "SHOW CHARSET LIKE 'utf8m\\b4'"
+    order_qt_like_backslash "SHOW CHARSET LIKE 'utf8m\\\\b4'"
+    sql "SET sql_mode = 'NO_BACKSLASH_ESCAPES'"
+    order_qt_like_no_backslash_escapes "SHOW CHARSET LIKE 'utf8m\\\\b4'"
+    sql "SET sql_mode = DEFAULT"
+
+    sql "SET enable_sql_cache = true"
+    order_qt_where_before_collation_change "SHOW CHARSET WHERE TRUE"
+    sql "SET collation_connection = 'utf8mb4_general_ci'"
+    order_qt_where_after_collation_change "SHOW CHARSET WHERE TRUE"
+    sql "SET collation_connection = DEFAULT"
+    sql "SET enable_sql_cache = DEFAULT"
+
+    sql "SET sql_select_limit = 0"
+    order_qt_where_with_select_limit "SHOW CHARSET WHERE @@sql_select_limit = 
0"
+    order_qt_select_limit_still_applies "SELECT 1"
+    sql "SET sql_select_limit = DEFAULT"
+
+    def url = getServerPrepareJdbcUrl(context.config.jdbcUrl, context.dbName, 
false) +
+            "&emulateUnsupportedPstmts=false"
+    connect(context.config.jdbcUser, context.config.jdbcPassword, url) {
+        context.getConnection().prepareStatement("SHOW CHARSET WHERE Maxlen = 
?").withCloseable { stmt ->
+            assertTrue(stmt instanceof 
com.mysql.cj.jdbc.ServerPreparedStatement)
+            stmt.setInt(1, 4)
+            qe_prepared_match stmt
+            stmt.setInt(1, 5)
+            qe_prepared_no_match stmt
+        }
     }
-}
 
+    test {
+        sql "SHOW CHARSET WHERE unknown_column = 'utf8mb4'"
+        exception "unknown_column"
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to