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

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new eca38776ff [#14660] fix(trino,spark): keep the server reason when a 
cascade drop schema is refused (#14663)
eca38776ff is described below

commit eca38776ff31ae1934684be1780b30e08c5d97af
Author: geyanggang <[email protected]>
AuthorDate: Mon Nov 9 10:40:21 2026 +0800

    [#14660] fix(trino,spark): keep the server reason when a cascade drop 
schema is refused (#14663)
    
    ### What changes were proposed in this pull request?
    
    - Trino `CatalogConnectorMetadata.dropSchema`: surface the
    `NonEmptySchemaException` message (falling back to "Schema is not empty"
    when blank) instead of the fixed "Schema does not empty", keeping the
    `GRAVITINO_SCHEMA_NOT_EMPTY` code.
    - Spark `BaseCatalog.dropNamespace`: when `cascade` is true, propagate
    the original `NonEmptySchemaException` (which carries the server's
    reason); keep `NonEmptyNamespaceException` for the non-cascade path.
    
    ### Why are the changes needed?
    
    When a cascade drop is refused for a hard dependency, the connectors
    report a misleading, fixed message, so users cannot see the blocking
    dependency.
    
    Fixes #14660
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A refused `DROP SCHEMA ... CASCADE` now shows the server's reason
    in Trino, and in Spark propagates that reason instead of a generic
    "namespace is not empty". The non-cascade Spark behavior is unchanged.
    
    ### How was this patch tested?
    
    - Trino `TestCatalogConnectorMetadataErrors`: reason preserved, blank
    fallback.
    - New Spark `TestBaseCatalogDropNamespace`: cascade keeps the reason,
    non-cascade still throws `NonEmptyNamespaceException`.
    - Built `trino-connector-482-483`, `spark-3.5` and `spark-4.0` with
    `-PskipITs`; spotless clean.
---
 .../operation/PostgreSqlSchemaOperations.java      |  34 +++++-
 .../operation/TestPostgreSqlSchemaOperations.java  |  30 +++++
 .../spark/connector/catalog/BaseCatalog.java       |   7 ++
 .../catalog/TestBaseCatalogDropNamespace.java      | 127 +++++++++++++++++++++
 .../trino/connector/GravitinoErrorCode.java        |  16 ++-
 .../catalog/CatalogConnectorMetadata.java          |   6 +-
 .../trino/connector/TestGravitinoErrorCode.java    |  11 ++
 .../TestCatalogConnectorMetadataErrors.java        |  40 +++++++
 8 files changed, 260 insertions(+), 11 deletions(-)

diff --git 
a/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlSchemaOperations.java
 
b/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlSchemaOperations.java
index 410ae53155..fda1d77dfb 100644
--- 
a/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlSchemaOperations.java
+++ 
b/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlSchemaOperations.java
@@ -33,6 +33,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
 import javax.sql.DataSource;
 import org.apache.commons.collections4.MapUtils;
 import org.apache.commons.lang3.StringUtils;
@@ -44,6 +46,8 @@ import 
org.apache.gravitino.catalog.jdbc.utils.JdbcConnectorUtils;
 import org.apache.gravitino.exceptions.NoSuchSchemaException;
 import org.apache.gravitino.exceptions.NonEmptySchemaException;
 import org.apache.gravitino.meta.AuditInfo;
+import org.postgresql.util.PSQLException;
+import org.postgresql.util.ServerErrorMessage;
 
 /** Database operations for PostgreSQL. */
 public class PostgreSqlSchemaOperations extends JdbcDatabaseOperations {
@@ -184,12 +188,40 @@ public class PostgreSqlSchemaOperations extends 
JdbcDatabaseOperations {
                 + "guaranteed. Remove its objects explicitly, then retry 
dropping the empty schema. "
                 + "PostgreSQL reason: %s",
             schema,
-            e.getMessage());
+            singleLineReason(e));
       }
       throw exceptionMapper.toGravitinoException(e);
     }
   }
 
+  // pgjdbc renders a server error over several lines, and the DETAIL line 
that names the dependent
+  // object comes after the first one. A client keeps only the first line of a 
message, because the
+  // rest of what it receives is the server stack trace, so fold the reason 
and its detail into one
+  // line to keep the blocking object visible.
+  private static String singleLineReason(SQLException e) {
+    if (e instanceof PSQLException) {
+      ServerErrorMessage server = ((PSQLException) e).getServerErrorMessage();
+      if (server != null) {
+        String reason = singleLine(server.getMessage());
+        String detail = singleLine(server.getDetail());
+        if (!reason.isEmpty()) {
+          return detail.isEmpty() ? reason : reason + " (" + detail + ")";
+        }
+      }
+    }
+    return singleLine(e.getMessage());
+  }
+
+  private static String singleLine(@Nullable String text) {
+    if (text == null) {
+      return "";
+    }
+    return text.lines()
+        .map(String::strip)
+        .filter(StringUtils::isNotEmpty)
+        .collect(Collectors.joining("; "));
+  }
+
   private static String quoteName(String name) {
     return "\"" + name.replace("\"", "\"\"") + "\"";
   }
diff --git 
a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlSchemaOperations.java
 
b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlSchemaOperations.java
index 8750c85129..379a90080e 100644
--- 
a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlSchemaOperations.java
+++ 
b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlSchemaOperations.java
@@ -44,6 +44,36 @@ import org.junit.jupiter.api.Test;
 @Tag("gravitino-docker-test")
 public class TestPostgreSqlSchemaOperations extends TestPostgreSql {
 
+  @Test
+  void testRefusedDropNamesTheBlockerOnTheFirstLine() throws SQLException {
+    String schema = RandomNameUtils.genRandomName("blocked_source");
+    String other = RandomNameUtils.genRandomName("blocked_other");
+    try (Connection connection = DATA_SOURCE.getConnection()) {
+      JdbcConnectorUtils.executeUpdate(connection, "CREATE SCHEMA " + schema);
+      JdbcConnectorUtils.executeUpdate(connection, "CREATE SCHEMA " + other);
+      try {
+        JdbcConnectorUtils.executeUpdate(
+            connection, "CREATE TABLE " + schema + ".parent (id int PRIMARY 
KEY)");
+        JdbcConnectorUtils.executeUpdate(
+            connection, "CREATE VIEW " + other + ".v AS SELECT * FROM " + 
schema + ".parent");
+
+        NonEmptySchemaException error =
+            Assertions.assertThrows(
+                NonEmptySchemaException.class, () -> 
DATABASE_OPERATIONS.delete(schema, true));
+
+        // Clients keep only the first line of a message and treat the rest as 
the server stack
+        // trace, so the object in the other schema that blocks the drop must 
be on that line.
+        Assertions.assertFalse(error.getMessage().contains("\n"), 
error.getMessage());
+        Assertions.assertTrue(error.getMessage().contains(other + ".v"), 
error.getMessage());
+        Assertions.assertEquals("2BP01", ((SQLException) 
error.getCause()).getSQLState());
+      } finally {
+        JdbcConnectorUtils.executeUpdate(connection, "DROP SCHEMA IF EXISTS " 
+ other + " CASCADE");
+        JdbcConnectorUtils.executeUpdate(
+            connection, "DROP SCHEMA IF EXISTS " + schema + " CASCADE");
+      }
+    }
+  }
+
   @Test
   void testCascadeDropPreservesExternalDependents() throws SQLException {
     String schema = RandomNameUtils.genRandomName("cascade_source");
diff --git 
a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
 
b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
index 23d5c472dd..21781dc479 100644
--- 
a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
+++ 
b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java
@@ -530,6 +530,13 @@ public abstract class BaseCatalog implements TableCatalog, 
SupportsNamespaces, F
     try {
       return gravitinoCatalogClient.asSchemas().dropSchema(namespace[0], 
cascade);
     } catch (NonEmptySchemaException e) {
+      // Without cascade, Spark expects NonEmptyNamespaceException so the user 
knows to retry with
+      // cascade. With cascade the user already asked to drop the contents, so 
a refusal means a
+      // hard dependency blocks it; keep the server's reason instead of the 
misleading "namespace
+      // is not empty".
+      if (cascade) {
+        throw e;
+      }
       throw new NonEmptyNamespaceException(namespace);
     }
   }
diff --git 
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogDropNamespace.java
 
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogDropNamespace.java
new file mode 100644
index 0000000000..002f3fc782
--- /dev/null
+++ 
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogDropNamespace.java
@@ -0,0 +1,127 @@
+/*
+ * 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.gravitino.spark.connector.catalog;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.Map;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.SupportsSchemas;
+import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.exceptions.NonEmptySchemaException;
+import org.apache.gravitino.spark.connector.PropertiesConverter;
+import org.apache.gravitino.spark.connector.SparkTransformConverter;
+import org.apache.gravitino.spark.connector.SparkTypeConverter;
+import org.apache.spark.SparkConf;
+import org.apache.spark.sql.catalyst.analysis.NonEmptyNamespaceException;
+import org.apache.spark.sql.connector.catalog.Identifier;
+import org.apache.spark.sql.connector.catalog.Table;
+import org.apache.spark.sql.connector.catalog.TableCatalog;
+import org.apache.spark.sql.util.CaseInsensitiveStringMap;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/** Unit tests for {@link BaseCatalog#dropNamespace}. */
+public class TestBaseCatalogDropNamespace {
+
+  private static final String SCHEMA = "db";
+
+  private SupportsSchemas schemas;
+  private BaseCatalog catalog;
+
+  @BeforeAll
+  static void initCatalogManager() {
+    GravitinoClient gravitinoClient = mock(GravitinoClient.class);
+    GravitinoCatalogManager.create(new SparkConf(false), "user", identity -> 
gravitinoClient);
+  }
+
+  @AfterAll
+  static void cleanupCatalogManager() {
+    GravitinoCatalogManager.get().close();
+  }
+
+  @BeforeEach
+  void setUp() {
+    Catalog gravitinoCatalog = mock(Catalog.class);
+    schemas = mock(SupportsSchemas.class);
+    when(gravitinoCatalog.asSchemas()).thenReturn(schemas);
+    catalog = new DropNamespaceTestCatalog();
+    catalog.gravitinoCatalogClient = gravitinoCatalog;
+  }
+
+  @Test
+  void testDropNamespaceWithoutCascadeThrowsNonEmptyNamespace() {
+    when(schemas.dropSchema(anyString(), anyBoolean()))
+        .thenThrow(new NonEmptySchemaException("Schema db has tables"));
+
+    assertThrows(
+        NonEmptyNamespaceException.class,
+        () -> catalog.dropNamespace(new String[] {SCHEMA}, false));
+  }
+
+  @Test
+  void testDropNamespaceWithCascadeKeepsServerReason() {
+    String reason = "Table db.orders is referenced by a table in another 
schema";
+    when(schemas.dropSchema(anyString(), anyBoolean()))
+        .thenThrow(new NonEmptySchemaException(reason));
+
+    NonEmptySchemaException e =
+        assertThrows(
+            NonEmptySchemaException.class,
+            () -> catalog.dropNamespace(new String[] {SCHEMA}, true));
+    assertEquals(reason, e.getMessage());
+  }
+
+  private static class DropNamespaceTestCatalog extends BaseCatalog {
+    @Override
+    protected TableCatalog createAndInitSparkCatalog(
+        String name, CaseInsensitiveStringMap options, Map<String, String> 
properties) {
+      return null;
+    }
+
+    @Override
+    protected Table createSparkTable(
+        Identifier identifier,
+        org.apache.gravitino.rel.Table gravitinoTable,
+        Table sparkTable,
+        TableCatalog sparkCatalog,
+        PropertiesConverter propertiesConverter,
+        SparkTransformConverter sparkTransformConverter,
+        SparkTypeConverter sparkTypeConverter) {
+      return null;
+    }
+
+    @Override
+    protected PropertiesConverter getPropertiesConverter() {
+      return null;
+    }
+
+    @Override
+    protected SparkTransformConverter getSparkTransformConverter() {
+      return null;
+    }
+  }
+}
diff --git 
a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
 
b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
index 03779f1032..0416b102a2 100644
--- 
a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
+++ 
b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
@@ -35,6 +35,7 @@ import javax.annotation.Nullable;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.exceptions.ConnectionFailedException;
 import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.NonEmptySchemaException;
 import org.apache.gravitino.exceptions.NotInUseException;
 import org.apache.gravitino.exceptions.RESTException;
 
@@ -126,12 +127,12 @@ public enum GravitinoErrorCode implements 
ErrorCodeSupplier {
    * Converts an exception into a Trino exception. A {@link TrinoException} is 
returned as is, so a
    * caller may route every failure of a guarded block through this method, 
including a {@link
    * TrinoException} it throws inside that block. An {@link 
ExecutionException} is classified by its
-   * cause. {@link ForbiddenException}, {@link NotInUseException}, {@link 
IllegalArgumentException}
-   * and {@link UnsupportedOperationException} map to {@code 
PERMISSION_DENIED}, {@code
-   * CATALOG_UNAVAILABLE}, {@link #GRAVITINO_ILLEGAL_ARGUMENT} and {@link
-   * #GRAVITINO_UNSUPPORTED_OPERATION}. A {@link ConnectionFailedException}, 
or a {@link
-   * RESTException} caused by a network failure, maps to {@link 
#GRAVITINO_CONNECTION_FAILED}.
-   * Anything else maps to {@code GENERIC_INTERNAL_ERROR}.
+   * cause. {@link ForbiddenException}, {@link NotInUseException}, {@link 
NonEmptySchemaException},
+   * {@link IllegalArgumentException} and {@link 
UnsupportedOperationException} map to {@code
+   * PERMISSION_DENIED}, {@code CATALOG_UNAVAILABLE}, {@link 
#GRAVITINO_SCHEMA_NOT_EMPTY}, {@link
+   * #GRAVITINO_ILLEGAL_ARGUMENT} and {@link 
#GRAVITINO_UNSUPPORTED_OPERATION}. A {@link
+   * ConnectionFailedException}, or a {@link RESTException} caused by a 
network failure, maps to
+   * {@link #GRAVITINO_CONNECTION_FAILED}. Anything else maps to {@code 
GENERIC_INTERNAL_ERROR}.
    *
    * @param exception the exception to convert
    * @param context describes the failed operation; it prefixes the message of 
an exception that
@@ -156,6 +157,9 @@ public enum GravitinoErrorCode implements ErrorCodeSupplier 
{
         || (e instanceof RESTException && isNetworkFailure(e.getCause()))) {
       return new TrinoException(GRAVITINO_CONNECTION_FAILED, 
firstLineMessage(e), e);
     }
+    if (e instanceof NonEmptySchemaException) {
+      return new TrinoException(GRAVITINO_SCHEMA_NOT_EMPTY, 
firstLineMessage(e), e);
+    }
     if (e instanceof IllegalArgumentException) {
       return new TrinoException(GRAVITINO_ILLEGAL_ARGUMENT, 
firstLineMessage(e), e);
     }
diff --git 
a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
 
b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
index 9d987c9d43..b72f06a3c5 100644
--- 
a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
+++ 
b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
@@ -42,7 +42,6 @@ import 
org.apache.gravitino.exceptions.NoSuchFunctionException;
 import org.apache.gravitino.exceptions.NoSuchSchemaException;
 import org.apache.gravitino.exceptions.NoSuchTableException;
 import org.apache.gravitino.exceptions.NoSuchViewException;
-import org.apache.gravitino.exceptions.NonEmptySchemaException;
 import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
 import org.apache.gravitino.exceptions.TableAlreadyExistsException;
 import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
@@ -311,10 +310,9 @@ public class CatalogConnectorMetadata {
     boolean success;
     try {
       success = schemaCatalog.dropSchema(schemaName, cascade);
-    } catch (NonEmptySchemaException e) {
-      throw new TrinoException(
-          GravitinoErrorCode.GRAVITINO_SCHEMA_NOT_EMPTY, "Schema does not 
empty", e);
     } catch (RuntimeException e) {
+      // A refused drop (NonEmptySchemaException) keeps its 
GRAVITINO_SCHEMA_NOT_EMPTY code and the
+      // server's reason, without the server stack trace a REST failure 
carries after the message.
       throw GravitinoErrorCode.toTrinoException(e);
     }
     if (!success) {
diff --git 
a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/TestGravitinoErrorCode.java
 
b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/TestGravitinoErrorCode.java
index 0306efb637..d9526d35d5 100644
--- 
a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/TestGravitinoErrorCode.java
+++ 
b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/TestGravitinoErrorCode.java
@@ -31,6 +31,7 @@ import java.util.concurrent.ExecutionException;
 import org.apache.gravitino.exceptions.ConnectionFailedException;
 import org.apache.gravitino.exceptions.ForbiddenException;
 import org.apache.gravitino.exceptions.MetalakeNotInUseException;
+import org.apache.gravitino.exceptions.NonEmptySchemaException;
 import org.apache.gravitino.exceptions.RESTException;
 import org.junit.jupiter.api.Test;
 
@@ -61,6 +62,16 @@ public class TestGravitinoErrorCode {
     assertEquals("Metalake m is not in use", e.getMessage());
   }
 
+  @Test
+  public void testNonEmptySchemaIsSchemaNotEmptyAndKeepsFirstLine() {
+    TrinoException e =
+        GravitinoErrorCode.toTrinoException(
+            new NonEmptySchemaException(
+                "Schema db is not empty\n\tat org.apache.gravitino.Server"));
+    assertEquals(GravitinoErrorCode.GRAVITINO_SCHEMA_NOT_EMPTY.toErrorCode(), 
e.getErrorCode());
+    assertEquals("Schema db is not empty", e.getMessage());
+  }
+
   @Test
   public void testIllegalArgumentIsIllegalArgument() {
     TrinoException e =
diff --git 
a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
 
b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
index 548b8af109..b66807b2ac 100644
--- 
a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
+++ 
b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
@@ -23,6 +23,7 @@ import static 
io.trino.spi.StandardErrorCode.PERMISSION_DENIED;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -38,6 +39,7 @@ import org.apache.gravitino.exceptions.ForbiddenException;
 import org.apache.gravitino.exceptions.IllegalNameIdentifierException;
 import org.apache.gravitino.exceptions.NoSuchCatalogException;
 import org.apache.gravitino.exceptions.NoSuchTableException;
+import org.apache.gravitino.exceptions.NonEmptySchemaException;
 import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
 import org.apache.gravitino.rel.TableCatalog;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
@@ -211,6 +213,44 @@ public class TestCatalogConnectorMetadataErrors {
     
assertEquals(GravitinoErrorCode.GRAVITINO_CATALOG_NOT_EXISTS.toErrorCode(), 
e.getErrorCode());
   }
 
+  @Test
+  public void testDropNonEmptySchemaKeepsServerReason() {
+    String reason = "Table db.orders depends on a table in this schema";
+    SupportsSchemas schemas = mock(SupportsSchemas.class);
+    when(schemas.dropSchema(anyString(), anyBoolean()))
+        .thenThrow(new NonEmptySchemaException(reason));
+    CatalogConnectorMetadata metadata = createMetadata(schemas, 
mock(TableCatalog.class));
+
+    TrinoException e = assertThrows(TrinoException.class, () -> 
metadata.dropSchema("s", true));
+    assertEquals(GravitinoErrorCode.GRAVITINO_SCHEMA_NOT_EMPTY.toErrorCode(), 
e.getErrorCode());
+    assertEquals(reason, e.getMessage());
+  }
+
+  @Test
+  public void testDropNonEmptySchemaDropsServerStackTrace() {
+    // The REST client appends the server stack trace to the message of a 
refusal, on cascade and
+    // non-cascade drops alike. Only the first line is the reason.
+    String reason = "Schema db is not empty";
+    String messageWithStack =
+        reason
+            + "\n"
+            + "org.apache.gravitino.exceptions.NonEmptySchemaException: "
+            + reason
+            + "\n"
+            + "\tat 
org.apache.gravitino.server.web.rest.SchemaOperations.dropSchema(SchemaOperations.java:1)";
+    SupportsSchemas schemas = mock(SupportsSchemas.class);
+    when(schemas.dropSchema(anyString(), anyBoolean()))
+        .thenThrow(new NonEmptySchemaException(messageWithStack));
+    CatalogConnectorMetadata metadata = createMetadata(schemas, 
mock(TableCatalog.class));
+
+    for (boolean cascade : new boolean[] {false, true}) {
+      TrinoException e =
+          assertThrows(TrinoException.class, () -> metadata.dropSchema("s", 
cascade));
+      
assertEquals(GravitinoErrorCode.GRAVITINO_SCHEMA_NOT_EMPTY.toErrorCode(), 
e.getErrorCode());
+      assertEquals(reason, e.getMessage());
+    }
+  }
+
   private static CatalogConnectorMetadata createMetadata(TableCatalog 
tableCatalog) {
     return createMetadata(mock(SupportsSchemas.class), tableCatalog);
   }

Reply via email to