Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14842] fix(spark-connector): Report the JDBC source error when a table cannot be read (#14843)

Qi Yu5d8d16651843
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 d822f4958e..a5e259d5ea 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,16 +41,22 @@ 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 {
@@ -51,6 +66,9 @@ public class GravitinoJdbcCatalog extends BaseCatalog {
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 +93,90 @@ 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;
+ }
+ }
+
+ // 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;
+ }
+
/**
* Overwrites the Spark JDBC user and password in {@code sparkProperties} with credentials
* obtained from the server via credential vending, if available.
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;
+ }
+}