This is an automated email from the ASF dual-hosted git repository.
jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/branch-1.3 by this push:
new b8f5d68f33 [Cherry-pick to branch-1.3] [#14842] fix(spark-connector):
Report the JDBC source error when a table cannot be read (#14843) (#14852)
b8f5d68f33 is described below
commit b8f5d68f331b389548c6eeb64830b72aea881c0e
Author: github-actions[bot]
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Wed Nov 11 09:40:22 2026 +0800
[Cherry-pick to branch-1.3] [#14842] fix(spark-connector): Report the JDBC
source error when a table cannot be read (#14843) (#14852)
### What changes were proposed in this pull request?
Cherry-pick #14843 (original commit
`5d8d16651843be3f43755ce51f403bd56dfe0d42`) to `branch-1.3`.
Resolve the import conflict and add the logger required by the target
branch. When Spark reports an unreadable JDBC table as missing, repeat
the schema read with the catalog options and preserve the source
SQLException in the error. Keep the previous error when no SQL error
explains the failure.
### Why are the changes needed?
Spark 3.x drops the JDBC source error, making missing privileges look
like a missing table.
Fix: #14842
### Does this PR introduce _any_ user-facing change?
Unreadable JDBC tables report the source's error and SQL cause instead
of only a table-not-found message.
### How was this patch tested?
- Relevant JDBC tests: Spark 3.3 (26), 3.4 (89), and 3.5 (152), all 267
passed with no skips.
- Includes H2 permission-denial tests that reach the real Spark JDBC
schema reader.
- Shared-source Spotless check and full `spotlessCheck --rerun-tasks`
passed (364 tasks executed).
- No external database or Spark cluster integration tests were run
locally.
- Disabling source-error reporting makes the production-path regression
test fail; restoring the fix makes all four source-error tests pass
again.
---------
Co-authored-by: Qi Yu <[email protected]>
Co-authored-by: yuqi <[email protected]>
---
.../spark/connector/jdbc/GravitinoJdbcCatalog.java | 103 +++++++++++++++
.../jdbc/TestGravitinoJdbcCatalogSourceError.java | 143 +++++++++++++++++++++
2 files changed, 246 insertions(+)
diff --git
a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java
b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java
index f19c7fcb07..db781e954e 100644
---
a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java
+++
b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java
@@ -22,7 +22,16 @@ package org.apache.gravitino.spark.connector.jdbc;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
import org.apache.commons.collections4.MapUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.credential.Credential;
@@ -32,21 +41,34 @@ import
org.apache.gravitino.spark.connector.SparkTransformConverter;
import org.apache.gravitino.spark.connector.SparkTypeConverter;
import org.apache.gravitino.spark.connector.catalog.BaseCatalog;
import org.apache.spark.sql.catalyst.analysis.NamespaceAlreadyExistsException;
+import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
import org.apache.spark.sql.connector.catalog.Identifier;
import org.apache.spark.sql.connector.catalog.SupportsNamespaces;
import org.apache.spark.sql.connector.catalog.Table;
import org.apache.spark.sql.connector.catalog.TableCatalog;
import org.apache.spark.sql.errors.QueryCompilationErrors;
+import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions;
+import org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD;
import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTable;
import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog;
+import org.apache.spark.sql.jdbc.JdbcDialect;
+import org.apache.spark.sql.jdbc.JdbcDialects;
import org.apache.spark.sql.util.CaseInsensitiveStringMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.Tuple2;
public class GravitinoJdbcCatalog extends BaseCatalog {
+ private static final Logger LOG =
LoggerFactory.getLogger(GravitinoJdbcCatalog.class);
+
private static final String PREFER_TIMESTAMP_NTZ = "preferTimestampNTZ";
private boolean useTimestampNtz;
+ // The Spark JDBC options the catalog was initialized with, used to read a
table's schema again.
+ private Map<String, String> jdbcOptions = Collections.emptyMap();
+
@Override
protected TableCatalog createAndInitSparkCatalog(
String name, CaseInsensitiveStringMap options, Map<String, String>
properties) {
@@ -75,9 +97,74 @@ public class GravitinoJdbcCatalog extends BaseCatalog {
// outside PostgreSQL, including when Spark's session timestamp type
defaults to NTZ.
setPreferTimestampNtz(all, useTimestampNtz);
jdbcTableCatalog.initialize(name, new CaseInsensitiveStringMap(all));
+ jdbcOptions = new HashMap<>(all);
return jdbcTableCatalog;
}
+ /**
+ * Loads the table from Spark's JDBC catalog. Spark reports any failure to
read the table schema,
+ * such as a permission the catalog user lacks, as a missing table.
Gravitino has already found
+ * the table, so read the schema again and report the source's own error
instead.
+ *
+ * @param ident the Spark table identifier
+ * @return the Spark JDBC table
+ */
+ @Override
+ protected Table loadSparkTable(Identifier ident) {
+ try {
+ return sparkCatalog.loadTable(ident);
+ } catch (NoSuchTableException e) {
+ String table = String.join(".", getDatabase(ident), ident.name());
+ SQLException sourceError = sourceError(jdbcOptions, ident);
+ if (sourceError != null) {
+ throw new RuntimeException(
+ String.format(
+ "Failed to read table %s from the JDBC source: %s",
+ table, sourceError.getMessage()),
+ sourceError);
+ }
+ throw new RuntimeException(String.format("Failed to load the real
sparkTable: %s", table), e);
+ }
+ }
+
+ /**
+ * Reads a table's schema the way Spark's JDBC catalog does and returns the
source's error.
+ *
+ * @param options the catalog's Spark JDBC options
+ * @param ident the Spark table identifier
+ * @return the source's error, or null if the schema can be read or no SQL
error explains it
+ */
+ @VisibleForTesting
+ @Nullable
+ static SQLException sourceError(Map<String, String> options, Identifier
ident) {
+ String url = options.get(JDBCOptions.JDBC_URL());
+ if (url == null) {
+ return null;
+ }
+ JdbcDialect dialect = JdbcDialects.get(url);
+ String table =
+ Stream.concat(Arrays.stream(ident.namespace()),
Stream.of(ident.name()))
+ .map(dialect::quoteIdentifier)
+ .collect(Collectors.joining("."));
+ Map<String, String> tableOptions = new HashMap<>(options);
+ tableOptions.put(JDBCOptions.JDBC_TABLE_NAME(), table);
+ try {
+ JDBCRDD.resolveTable(new JDBCOptions(toScalaMap(tableOptions)));
+ return null;
+ } catch (Exception e) {
+ // Scala does not declare checked exceptions, so the SQLException
arrives as Exception and
+ // can be wrapped. Track visited causes by identity so a cause cycle
ends the walk.
+ Set<Throwable> visited = Collections.newSetFromMap(new
IdentityHashMap<>());
+ for (Throwable t = e; t != null && visited.add(t); t = t.getCause()) {
+ if (t instanceof SQLException) {
+ return (SQLException) t;
+ }
+ }
+ LOG.debug("Failed to read the schema of {} again", table, e);
+ return null;
+ }
+ }
+
/**
* Overwrites the Spark JDBC user and password in {@code sparkProperties}
with credentials
* obtained from the server via credential vending, if available.
@@ -187,6 +274,22 @@ public class GravitinoJdbcCatalog extends BaseCatalog {
properties.put(PREFER_TIMESTAMP_NTZ, String.valueOf(value));
}
+ // The cast is redundant on Scala 2.12 and required on Scala 2.13.
+ @SuppressWarnings({"unchecked", "cast"})
+ private static scala.collection.immutable.Map<String, String> toScalaMap(
+ Map<String, String> map) {
+ // Built entry by entry because the Java-to-Scala map converters differ
between Scala 2.12
+ // and 2.13.
+ scala.collection.immutable.Map<String, String> result =
+ scala.collection.immutable.Map$.MODULE$.empty();
+ for (Map.Entry<String, String> entry : map.entrySet()) {
+ result =
+ (scala.collection.immutable.Map<String, String>)
+ result.$plus(new Tuple2<>(entry.getKey(), entry.getValue()));
+ }
+ return result;
+ }
+
/**
* Resolves the opt-in NTZ option. A Spark catalog option wins over a
Gravitino catalog property
* with the {@code spark.bypass.} prefix, as in {@link
diff --git
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalogSourceError.java
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalogSourceError.java
new file mode 100644
index 0000000000..2bfe4d0e09
--- /dev/null
+++
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalogSourceError.java
@@ -0,0 +1,143 @@
+/*
+ * 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.jdbc;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.credential.JdbcCredential;
+import org.apache.gravitino.credential.SupportsCredentials;
+import org.apache.gravitino.spark.connector.catalog.GravitinoCatalogManager;
+import org.apache.spark.sql.connector.catalog.Identifier;
+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.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+/** Tests that a table the catalog user cannot read reports the source's
error. */
+public class TestGravitinoJdbcCatalogSourceError {
+
+ private static final String URL =
"jdbc:h2:mem:spark_jdbc_source_error;DB_CLOSE_DELAY=-1";
+ private static final String ADMIN = "SA";
+ private static final String NO_RIGHTS = "NORIGHTS";
+ private static final String PASSWORD = "pw";
+ private static final Identifier TABLE = Identifier.of(new String[] {"S"},
"T");
+
+ private static Connection keepAlive;
+
+ @BeforeAll
+ static void setUp() throws SQLException {
+ keepAlive = DriverManager.getConnection(URL, ADMIN, "");
+ try (Statement statement = keepAlive.createStatement()) {
+ statement.execute("CREATE SCHEMA S");
+ statement.execute("CREATE TABLE S.T (ID INT)");
+ statement.execute("CREATE USER " + NO_RIGHTS + " PASSWORD '" + PASSWORD
+ "'");
+ }
+ }
+
+ @AfterAll
+ static void tearDown() throws SQLException {
+ try (Statement statement = keepAlive.createStatement()) {
+ statement.execute("SHUTDOWN");
+ }
+ }
+
+ @Test
+ void testSourceErrorNamesTheMissingPrivilege() {
+ SQLException error = GravitinoJdbcCatalog.sourceError(options(NO_RIGHTS,
PASSWORD), TABLE);
+ Assertions.assertNotNull(error);
+ Assertions.assertTrue(error.getMessage().contains("rights"),
error.getMessage());
+ }
+
+ @Test
+ void testNoSourceErrorWhenTheSchemaCanBeRead() {
+ Assertions.assertNull(GravitinoJdbcCatalog.sourceError(options(ADMIN, ""),
TABLE));
+ }
+
+ @Test
+ void testNoSourceErrorWithoutUrl() {
+ Assertions.assertNull(GravitinoJdbcCatalog.sourceError(new HashMap<>(),
TABLE));
+ }
+
+ @Test
+ void testLoadReportsTheSourceErrorInsteadOfNotFound() throws Exception {
+ try (MockedStatic<GravitinoCatalogManager> global =
mockStatic(GravitinoCatalogManager.class)) {
+
global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));
+ SupportsCredentials credentials = mock(SupportsCredentials.class);
+ when(credentials.getCredentials())
+ .thenReturn(new Credential[] {new JdbcCredential(NO_RIGHTS,
PASSWORD)});
+ Catalog source = mock(Catalog.class);
+ when(source.provider()).thenReturn("jdbc-h2");
+ when(source.supportsCredentials()).thenReturn(credentials);
+ GravitinoJdbcCatalog catalog = new GravitinoJdbcCatalog();
+ FieldUtils.writeField(catalog, "gravitinoCatalogClient", source, true);
+
+ Map<String, String> properties = new HashMap<>();
+ properties.put("jdbc-url", URL);
+ properties.put("jdbc-driver", "org.h2.Driver");
+ TableCatalog physical =
+ catalog.createAndInitSparkCatalog(
+ "test", new CaseInsensitiveStringMap(new HashMap<>()),
properties);
+ FieldUtils.writeField(catalog, "sparkCatalog", physical, true);
+
+ // Spark 3.x reports the failed schema read as a missing table, which
the catalog replaces
+ // with the source's error. Spark 4.0 already reports it as FAILED_JDBC
with the source
+ // error as the cause. Either way the source's reason must reach the
caller.
+ Exception error =
+ Assertions.assertThrows(Exception.class, () ->
catalog.loadSparkTable(TABLE));
+ Assertions.assertFalse(
+ String.valueOf(error.getMessage()).contains("Failed to load the real
sparkTable"),
+ error.getMessage());
+ Assertions.assertNotNull(
+ sqlCause(error), "the source's SQL error must be in the cause
chain");
+ }
+ }
+
+ private static SQLException sqlCause(Throwable error) {
+ for (Throwable t = error; t != null; t = t.getCause()) {
+ if (t instanceof SQLException) {
+ return (SQLException) t;
+ }
+ }
+ return null;
+ }
+
+ private static Map<String, String> options(String user, String password) {
+ Map<String, String> options = new HashMap<>();
+ options.put("url", URL);
+ options.put("driver", "org.h2.Driver");
+ options.put("user", user);
+ options.put("password", password);
+ return options;
+ }
+}