This is an automated email from the ASF dual-hosted git repository.
mchades 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 5b0bb67b67 [#13549] fix(hive): Resolve SerDe-derived column types
(#13550)
5b0bb67b67 is described below
commit 5b0bb67b672699fb323c960956c5e36bf112b72e
Author: jarred0214 <[email protected]>
AuthorDate: Mon Nov 9 11:06:39 2026 +0800
[#13549] fix(hive): Resolve SerDe-derived column types (#13550)
### What changes were proposed in this pull request?
Resolve Hive storage columns containing `<derived from deserializer>`
through HMS `getFields` before converting single-table and full-schema
batch reads. Hive 3 uses the catalog-aware API; ordinary tables do not
add a schema-resolution RPC.
Hudi listing now filters raw storage input-format metadata without
converting schemas, so an unrelated unresolvable SerDe table cannot
break the listing. Full-schema batch reads remain strict and report
resolution failures.
Preserve original storage columns during metadata-only alters and
renames, reject column changes on SerDe-derived tables, and report
actionable HMS configuration errors. Fix inherited integration coverage
for non-default Hive catalogs and inject the required test configuration
into prebuilt containers before startup.
### Why are the changes needed?
The Hive marker is not a valid type and prevents table loading and
dependent operations such as GRANT. Hudi listing also previously
converted unrelated tables before filtering them. Hive 2's server-side
compatibility check can reject even metadata-only alters when it
attempts to parse the preserved marker.
Fix: #13549
### Does this PR introduce _any_ user-facing change?
Yes. SerDe-derived schemas can be loaded when HMS can resolve them. The
SerDe and its dependencies must be on the HMS classpath. Hive 3 requires
`metastore.storage.schema.reader.impl=org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader`
on the **HMS server**, followed by a restart; this also applies to Hive
2 clients connecting to Hive 3 HMS.
Property, table-comment, and rename operations preserve the original
storage schema. Hive 2 HMS can reject these operations when
`hive.metastore.disallow.incompatible.col.type.changes=true`. An HMS
administrator must evaluate disabling that check to permit
marker-preserving alters; this affects **all tables**, and Gravitino
does not change the server setting. Errors explain this limitation.
Column changes on derived tables are rejected; update their SerDe or
external schema definition instead.
Hudi listing avoids schema resolution for unrelated tables. Full-schema
batch reads fail if a requested table cannot be resolved, rather than
silently omitting it.
### How was this patch tested?
- Ran `./gradlew spotlessApply`.
- Ran `./gradlew :catalogs:hive-metastore-common:test
:catalogs:hive-metastore3-libs:test :catalogs:catalog-hive:test
:catalogs:catalog-lakehouse-hudi:test :integration-test-common:test
-PskipITs`: 178 tests passed.
- Added exact exception-type and retained-guidance assertions for both
shims, metadata-only Hudi listing coverage, and a test of the
prebuilt-container configuration script.
- Ran a real embedded Hive 2 HMS test covering OpenCSVSerde resolution,
full-schema batch loading, and a property alter preserving the stored
marker with the documented compatibility setting disabled.
- Updated inherited Hive 2/3 integration coverage to use catalog-aware
creation and Hive 3-compatible catalog-qualified reads, and to verify
marker preservation after rename. The integration tests compile, but
Docker is unavailable locally; container validation remains pending CI.
---------
Co-authored-by: Qi Yu <[email protected]>
Co-authored-by: mchades <[email protected]>
---
.../catalog/hive/HiveCatalogOperations.java | 9 +-
.../catalog/hive/TestHiveCatalogOperations.java | 63 +++++
.../hive/integration/test/CatalogHive2IT.java | 133 ++++++++++-
.../hive/integration/test/CatalogHive3IT.java | 6 +-
.../hive/integration/test/CatalogHiveABSIT.java | 4 +-
.../hive/integration/test/CatalogHiveGCSIT.java | 4 +-
.../hive/integration/test/CatalogHiveS3IT.java | 4 +-
.../test/TestHiveMetastoreDatabaseName.java | 37 +++
catalogs/catalog-lakehouse-hudi/build.gradle.kts | 1 +
.../hudi/backend/hms/HudiHMSBackendOps.java | 8 +-
.../backend/hms/TestHudiHMSMetadataListing.java | 76 ++++++
.../java/org/apache/gravitino/hive/HiveTable.java | 20 ++
.../apache/gravitino/hive/client/HiveClient.java | 14 ++
.../gravitino/hive/client/HiveClientImpl.java | 8 +
.../hive/client/HiveExceptionConverter.java | 23 ++
.../org/apache/gravitino/hive/client/HiveShim.java | 158 ++++++++++++-
.../hive/converter/HiveTableConverter.java | 14 ++
.../apache/gravitino/hive/TestHiveSerDeSchema.java | 112 +++++++++
.../hive/client/TestHiveShimGetTable.java | 257 +++++++++++++++++++++
.../gravitino/hive/client/hive3/HiveShimV3.java | 37 ++-
.../hive/client/hive3/TestHiveShimV3.java | 119 ++++++++++
dev/docker/hive/hive-site.xml | 6 +
docs/apache-hive-catalog.md | 35 +++
.../integration/test/container/HiveContainer.java | 11 +
.../TestHiveSerDeSchemaConfiguration.java | 95 ++++++++
.../resources/hive/enable-serde-schema-tests.sh | 35 +++
26 files changed, 1264 insertions(+), 25 deletions(-)
diff --git
a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
index 7859cb2bb7..6502502278 100644
---
a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
+++
b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java
@@ -735,6 +735,11 @@ public class HiveCatalogOperations
TableChange.RemoveProperty removeProperty =
(TableChange.RemoveProperty) change;
updatedProperties.remove(removeProperty.getProperty());
} else if (change instanceof TableChange.ColumnChange) {
+ if (!currentTable.originalStorageColumns().isEmpty()) {
+ throw new IllegalArgumentException(
+ "Cannot alter columns of a SerDe-derived table through
Gravitino. "
+ + "Update the schema through the table SerDe or its
external schema definition.");
+ }
applyColumnChange(updatedColumns, (TableChange.ColumnChange) change);
} else {
throw new IllegalArgumentException(
@@ -833,7 +838,9 @@ public class HiveCatalogOperations
if (comment != null) {
builder.withComment(comment);
}
- return builder.build();
+ HiveTable altered = builder.build();
+ altered.setOriginalStorageColumns(original.originalStorageColumns());
+ return altered;
}
private void applyColumnChange(List<Column> columns,
TableChange.ColumnChange change) {
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
index 1d2e97c38b..afa3b7f7ac 100644
---
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
@@ -52,6 +52,7 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@@ -97,6 +98,68 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
class TestHiveCatalogOperations {
+ @Test
+ void testDerivedSchemaMetadataAltersPreserveMarkerAndRejectColumnChanges()
throws Exception {
+ HiveCatalogOperations op = new HiveCatalogOperations();
+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);
+ CachedClientPool pool = mock(CachedClientPool.class);
+ HiveClient client = mock(HiveClient.class);
+ when(pool.run(any()))
+ .thenAnswer(
+ invocation -> {
+ ClientPool.Action<?, HiveClient, ?> action =
invocation.getArgument(0);
+ return action.run(client);
+ });
+ op.clientPool = pool;
+ HiveTable derived =
+ HiveTable.builder()
+ .withName("csv")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[] {Column.of("value",
Types.StringType.get())})
+ .withProperties(Maps.newHashMap())
+ .withAuditInfo(
+
AuditInfo.builder().withCreator("tester").withCreateTime(Instant.now()).build())
+ .build();
+ derived.setOriginalStorageColumns(
+ List.of(
+ Column.of("value", Types.UnparsedType.of("<derived from
deserializer>"), "original")));
+ when(client.getTable(anyString(), anyString(),
anyString())).thenReturn(derived);
+ ArgumentCaptor<HiveTable> altered =
ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(client)
+ .alterTable(anyString(), eq("db"), eq("csv"), altered.capture(),
anyBoolean());
+
+ op.alterTable(
+ NameIdentifier.of("db", "csv"),
+ TableChange.setProperty("key", "value"),
+ TableChange.updateComment("updated"));
+ HiveTable metadataOnly = altered.getValue();
+ Assertions.assertEquals("value", metadataOnly.properties().get("key"));
+ Assertions.assertEquals("updated", metadataOnly.comment());
+ Assertions.assertEquals(
+ "<derived from deserializer>",
+ ((Types.UnparsedType)
metadataOnly.originalStorageColumns().get(0).dataType())
+ .unparsedType());
+ op.alterTable(NameIdentifier.of("db", "csv"),
TableChange.rename("renamed"));
+ Assertions.assertEquals("renamed", altered.getValue().name());
+ Assertions.assertEquals(
+ derived.originalStorageColumns(),
altered.getValue().originalStorageColumns());
+
+ IllegalArgumentException failure =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ op.alterTable(
+ NameIdentifier.of("db", "csv"),
+ TableChange.addColumn(
+ new String[] {"added"},
+ Types.StringType.get(),
+ TableChange.ColumnPosition.defaultPos())));
+ Assertions.assertTrue(failure.getMessage().contains("SerDe-derived
table"));
+ verify(client, times(2)).alterTable(anyString(), anyString(), anyString(),
any(), anyBoolean());
+ }
+
@Test
void testPropertyMeta() {
Map<String, PropertyEntry<?>> propertyEntryMap =
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
index d3a42f12bb..3c5a5a225c 100644
---
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
@@ -113,6 +113,7 @@ import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.spark.sql.SparkSession;
import org.apache.thrift.TException;
import org.junit.jupiter.api.AfterAll;
@@ -160,6 +161,100 @@ public class CatalogHive2IT extends BaseIT {
return String.format("INSERT INTO %s.%s VALUES (%s)", dbName, tableName,
values);
}
+ @Test
+ void testLoadAndAlterSerDeDerivedTable() throws Exception {
+ HiveConf conf = new HiveConf();
+ conf.set(HiveConf.ConfVars.METASTOREURIS.varname, hiveMetastoreUris);
+ // The test JVM uses the Hive 2 client even when the server is Hive 3.
+ HiveMetaStoreClient metastore = new HiveMetaStoreClient(conf);
+ try (AutoCloseable closeMetastore = metastore::close) {
+ String csvTableName = GravitinoITUtils.genRandomName("serde_csv");
+ NameIdentifier identifier = NameIdentifier.of(schemaName, csvTableName);
+ // Start with an ordinary external table, then create a separate
SerDe-derived table
+ // directly through HMS so the test exercises the stored marker rather
than a mock.
+ catalog
+ .asTableCatalog()
+ .createTable(
+ identifier,
+ new Column[] {Column.of("value", Types.StringType.get())},
+ null,
+ ImmutableMap.of(TABLE_TYPE, "EXTERNAL_TABLE"),
+ Transforms.EMPTY_TRANSFORM);
+ HiveTable csvTable =
+ hiveClientPool.run(client -> client.getTable(hmsCatalog, schemaName,
csvTableName));
+ catalog.asTableCatalog().dropTable(identifier);
+ csvTable.setOriginalStorageColumns(
+ List.of(
+ Column.of(
+ "value", Types.UnparsedType.of("<derived from
deserializer>"), "CSV column")));
+ csvTable.properties().put(SERDE_LIB,
"org.apache.hadoop.hive.serde2.OpenCSVSerde");
+ csvTable.properties().put(INPUT_FORMAT,
"org.apache.hadoop.mapred.TextInputFormat");
+ csvTable
+ .properties()
+ .put(OUTPUT_FORMAT,
"org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat");
+ hiveClientPool.run(
+ client -> {
+ client.createTable(csvTable);
+ return null;
+ });
+ Assertions.assertEquals(
+ "<derived from deserializer>",
+ metastore
+ .getTable(metastoreDatabaseName(hmsCatalog, schemaName),
csvTableName)
+ .getSd()
+ .getCols()
+ .get(0)
+ .getType());
+
+ Table loaded = catalog.asTableCatalog().loadTable(identifier);
+ Assertions.assertEquals(1, loaded.columns().length);
+ Assertions.assertEquals(Types.StringType.get(),
loaded.columns()[0].dataType());
+ List<HiveTable> batch =
+ hiveClientPool.run(
+ client ->
+ client.getTableObjectsByName(hmsCatalog, schemaName,
List.of(csvTableName)));
+ Assertions.assertEquals(Types.StringType.get(),
batch.get(0).columns()[0].dataType());
+
+ catalog
+ .asTableCatalog()
+ .alterTable(identifier, TableChange.setProperty("serde_test",
"value"));
+ catalog.asTableCatalog().alterTable(identifier,
TableChange.updateComment("updated"));
+ var stored = metastore.getTable(metastoreDatabaseName(hmsCatalog,
schemaName), csvTableName);
+ Assertions.assertEquals(
+ "<derived from deserializer>",
stored.getSd().getCols().get(0).getType());
+ Assertions.assertEquals("value",
stored.getParameters().get("serde_test"));
+ Assertions.assertEquals("updated", stored.getParameters().get(COMMENT));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ catalog
+ .asTableCatalog()
+ .alterTable(
+ identifier,
+ TableChange.addColumn(
+ new String[] {"added"},
+ Types.StringType.get(),
+ TableChange.ColumnPosition.defaultPos())));
+ Assertions.assertEquals(
+ 1,
+ metastore
+ .getTable(metastoreDatabaseName(hmsCatalog, schemaName),
csvTableName)
+ .getSd()
+ .getColsSize());
+ String renamed = GravitinoITUtils.genRandomName("serde_renamed");
+ catalog.asTableCatalog().alterTable(identifier,
TableChange.rename(renamed));
+ Assertions.assertEquals(
+ "<derived from deserializer>",
+ metastore
+ .getTable(metastoreDatabaseName(hmsCatalog, schemaName), renamed)
+ .getSd()
+ .getCols()
+ .get(0)
+ .getType());
+ catalog.asTableCatalog().dropTable(NameIdentifier.of(schemaName,
renamed));
+ }
+ }
+
private static String getInsertWithPartitionSql(
String dbName, String tableName, String partitionExpressions, String
values) {
return String.format(
@@ -180,7 +275,11 @@ public class CatalogHive2IT extends BaseIT {
protected void startNecessaryContainer() {
containerSuite.startHiveContainer(
- ImmutableMap.of(HiveContainer.HIVE_RUNTIME_VERSION,
HiveContainer.HIVE2));
+ ImmutableMap.of(
+ HiveContainer.HIVE_RUNTIME_VERSION,
+ HiveContainer.HIVE2,
+ HiveContainer.ENABLE_SERDE_SCHEMA_TESTS,
+ "true"));
hiveMetastoreUris =
String.format(
@@ -1403,7 +1502,8 @@ public class CatalogHive2IT extends BaseIT {
checkColumnConstraintsOnAlter(tableCatalog, id);
- // test updateColumnPosition exception
+ // The SerDe fixtures disable HMS's incompatible column type check so
metadata-only alters
+ // can preserve the stored marker. Ordinary tables therefore also allow
this reorder.
Column col1 = Column.of("name", Types.StringType.get(), "comment");
Column col2 = Column.of("address", Types.StringType.get(), "comment");
Column col3 = Column.of("date_of_birth", Types.DateType.get(), "comment");
@@ -1425,15 +1525,20 @@ public class CatalogHive2IT extends BaseIT {
TableChange updatePos =
TableChange.updateColumnPosition(
new String[] {"date_of_birth"},
TableChange.ColumnPosition.first());
- exception =
- assertThrows(
- IllegalArgumentException.class,
- () -> tableCatalog.alterTable(tableIdentifier, updatePos));
- Assertions.assertTrue(
- exception
- .getMessage()
- .contains(
- "please ensure that the type of the new column position is
compatible with the old one"));
+ Table reordered = tableCatalog.alterTable(tableIdentifier, updatePos);
+ Column[] expectedColumns = new Column[] {col3, col1, col2};
+ Column[] storedColumns = loadHiveTable(schemaName,
tableIdentifier.name()).columns();
+ Assertions.assertEquals(expectedColumns.length,
reordered.columns().length);
+ Assertions.assertEquals(expectedColumns.length, storedColumns.length);
+ for (int index = 0; index < expectedColumns.length; index++) {
+ Column expected = expectedColumns[index];
+ Assertions.assertEquals(expected.name(),
reordered.columns()[index].name());
+ Assertions.assertEquals(expected.dataType(),
reordered.columns()[index].dataType());
+ Assertions.assertEquals(expected.comment(),
reordered.columns()[index].comment());
+ Assertions.assertEquals(expected.name(), storedColumns[index].name());
+ Assertions.assertEquals(expected.dataType(),
storedColumns[index].dataType());
+ Assertions.assertEquals(expected.comment(),
storedColumns[index].comment());
+ }
}
@Test
@@ -2041,4 +2146,10 @@ public class CatalogHive2IT extends BaseIT {
.findFirst()
.get();
}
+
+ static String metastoreDatabaseName(String hmsCatalog, String schemaName) {
+ return hmsCatalog == null || hmsCatalog.isEmpty() ||
"hive".equals(hmsCatalog)
+ ? schemaName
+ : "@" + hmsCatalog + "#" + schemaName;
+ }
}
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java
index 431dbded28..92da06502f 100644
---
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive3IT.java
@@ -44,7 +44,11 @@ public class CatalogHive3IT extends CatalogHive2IT {
protected void startNecessaryContainer() {
hmsCatalog = "hive";
containerSuite.startHiveContainer(
- ImmutableMap.of(HiveContainer.HIVE_RUNTIME_VERSION,
HiveContainer.HIVE3));
+ ImmutableMap.of(
+ HiveContainer.HIVE_RUNTIME_VERSION,
+ HiveContainer.HIVE3,
+ HiveContainer.ENABLE_SERDE_SCHEMA_TESTS,
+ "true"));
hiveMetastoreUris =
String.format(
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
index c09e1ef8b2..ce9e8834c4 100644
---
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveABSIT.java
@@ -54,7 +54,9 @@ public class CatalogHiveABSIT extends CatalogHive2IT {
"ABS_ACCOUNT_KEY",
ABS_USER_ACCOUNT_KEY,
HiveContainer.HIVE_RUNTIME_VERSION,
- HiveContainer.HIVE3);
+ HiveContainer.HIVE3,
+ HiveContainer.ENABLE_SERDE_SCHEMA_TESTS,
+ "true");
containerSuite.startHiveContainerWithS3(hiveContainerEnv);
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
index 2dee713bf4..12a5ed5d80 100644
---
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveGCSIT.java
@@ -49,7 +49,9 @@ public class CatalogHiveGCSIT extends CatalogHive2IT {
"SERVICE_ACCOUNT_FILE",
GCS_ACCOUNT_JSON_FILE_IN_CONTAINER,
HiveContainer.HIVE_RUNTIME_VERSION,
- HiveContainer.HIVE3);
+ HiveContainer.HIVE3,
+ HiveContainer.ENABLE_SERDE_SCHEMA_TESTS,
+ "true");
containerSuite.startHiveContainerWithS3(hiveContainerEnv);
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
index 2ef3d2e6a2..3192554d6c 100644
---
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveS3IT.java
@@ -109,7 +109,9 @@ public class CatalogHiveS3IT extends CatalogHive3IT {
S3_ENDPOINT,
getS3Endpoint,
HiveContainer.HIVE_RUNTIME_VERSION,
- HiveContainer.HIVE3);
+ HiveContainer.HIVE3,
+ HiveContainer.ENABLE_SERDE_SCHEMA_TESTS,
+ "true");
containerSuite.startHiveContainerWithS3(hiveContainerEnv);
diff --git
a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/TestHiveMetastoreDatabaseName.java
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/TestHiveMetastoreDatabaseName.java
new file mode 100644
index 0000000000..2cb0b9cae7
--- /dev/null
+++
b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/TestHiveMetastoreDatabaseName.java
@@ -0,0 +1,37 @@
+/*
+ * 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.catalog.hive.integration.test;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestHiveMetastoreDatabaseName {
+ @Test
+ void testHive2AndDefaultHive3CatalogsUseUnqualifiedDatabaseName() {
+ Assertions.assertEquals("schema", CatalogHive2IT.metastoreDatabaseName("",
"schema"));
+ Assertions.assertEquals("schema",
CatalogHive2IT.metastoreDatabaseName(null, "schema"));
+ Assertions.assertEquals("schema",
CatalogHive2IT.metastoreDatabaseName("hive", "schema"));
+ }
+
+ @Test
+ void testCustomHive3CatalogUsesEncodedDatabaseName() {
+ Assertions.assertEquals(
+ "@custom#schema", CatalogHive2IT.metastoreDatabaseName("custom",
"schema"));
+ }
+}
diff --git a/catalogs/catalog-lakehouse-hudi/build.gradle.kts
b/catalogs/catalog-lakehouse-hudi/build.gradle.kts
index 13d830fca0..957bdf931c 100644
--- a/catalogs/catalog-lakehouse-hudi/build.gradle.kts
+++ b/catalogs/catalog-lakehouse-hudi/build.gradle.kts
@@ -131,6 +131,7 @@ dependencies {
testImplementation(libs.commons.configuration2)
testImplementation(libs.re2j)
testImplementation(libs.junit.jupiter.api)
+ testImplementation(libs.mockito.core)
testImplementation(libs.mysql.driver)
testImplementation(libs.postgresql.driver)
testImplementation(libs.prometheus.dropwizard)
diff --git
a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
index cae2c3c4f0..975e9b572d 100644
---
a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
+++
b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/HudiHMSBackendOps.java
@@ -146,9 +146,11 @@ public class HudiHMSBackendOps implements
HudiCatalogBackendOps {
return clientPool.run(
c -> {
List<String> allTables = c.getAllTables(catalogName,
schemaIdent.name());
- return c.getTableObjectsByName(catalogName, schemaIdent.name(),
allTables).stream()
- .filter(this::checkHudiTable)
- .map(t -> NameIdentifier.of(namespace, t.name()))
+ return c
+ .getTableNamesByInputFormatPrefix(
+ catalogName, schemaIdent.name(), allTables,
HUDI_PACKAGE_PREFIX)
+ .stream()
+ .map(name -> NameIdentifier.of(namespace, name))
.toArray(NameIdentifier[]::new);
});
} catch (InterruptedException e) {
diff --git
a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSMetadataListing.java
b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSMetadataListing.java
new file mode 100644
index 0000000000..169edd12cc
--- /dev/null
+++
b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/backend/hms/TestHudiHMSMetadataListing.java
@@ -0,0 +1,76 @@
+/*
+ * 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.catalog.lakehouse.hudi.backend.hms;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
+import org.apache.gravitino.hive.CachedClientPool;
+import org.apache.gravitino.hive.client.HiveClient;
+import org.apache.gravitino.utils.ClientPool;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestHudiHMSMetadataListing {
+ @Test
+ void testListingUsesOnlyStorageMetadataAndPropagatesFailures() throws
Exception {
+ HudiHMSBackendOps ops = spy(new HudiHMSBackendOps());
+ ops.initialize(Map.of());
+ ops.clientPool.close();
+ CachedClientPool pool = mock(CachedClientPool.class);
+ HiveClient client = mock(HiveClient.class);
+ ops.clientPool = pool;
+ Namespace namespace = Namespace.of("db");
+ doReturn(true).when(ops).schemaExists(NameIdentifier.of("db"));
+ when(pool.run(any()))
+ .thenAnswer(
+ invocation -> {
+ ClientPool.Action<?, HiveClient, ?> action =
invocation.getArgument(0);
+ return action.run(client);
+ });
+ when(client.getAllTables("hive", "db")).thenReturn(List.of("hudi",
"broken_csv"));
+ when(client.getTableNamesByInputFormatPrefix(
+ "hive", "db", List.of("hudi", "broken_csv"), "org.apache.hudi"))
+ .thenReturn(List.of("hudi"));
+
+ Assertions.assertArrayEquals(
+ new NameIdentifier[] {NameIdentifier.of("db", "hudi")},
ops.listTables(namespace));
+ verify(client, never()).getTableObjectsByName(any(), anyString(),
anyList());
+ GravitinoRuntimeException failure = new
GravitinoRuntimeException("Metastore failed");
+ when(client.getTableNamesByInputFormatPrefix(
+ "hive", "db", List.of("hudi", "broken_csv"), "org.apache.hudi"))
+ .thenThrow(failure);
+ Assertions.assertSame(
+ failure,
+ Assertions.assertThrows(GravitinoRuntimeException.class, () ->
ops.listTables(namespace)));
+ }
+}
diff --git
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveTable.java
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveTable.java
index 89988f1aa9..6c22e48dff 100644
---
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveTable.java
+++
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveTable.java
@@ -33,6 +33,7 @@ import org.apache.gravitino.catalog.hive.TableType;
import org.apache.gravitino.connector.BaseTable;
import org.apache.gravitino.connector.ProxyPlugin;
import org.apache.gravitino.connector.TableOperations;
+import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.expressions.NamedReference;
import org.apache.gravitino.rel.expressions.transforms.Transform;
import org.apache.gravitino.rel.expressions.transforms.Transforms;
@@ -49,6 +50,7 @@ public class HiveTable extends BaseTable {
private String catalogName;
private String databaseName;
private String viewOriginalText;
+ private List<Column> originalStorageColumns = Collections.emptyList();
protected HiveTable() {}
@@ -62,6 +64,24 @@ public class HiveTable extends BaseTable {
return viewOriginalText;
}
+ /**
+ * Returns a copy of the original storage columns for a SerDe-derived schema.
+ *
+ * @return Original columns, or an empty list for an ordinary table.
+ */
+ public List<Column> originalStorageColumns() {
+ return List.copyOf(originalStorageColumns);
+ }
+
+ /**
+ * Records original storage columns so metadata-only alters preserve the
SerDe schema marker.
+ *
+ * @param columns The original storage columns, or an empty list for an
ordinary table.
+ */
+ public void setOriginalStorageColumns(List<Column> columns) {
+ originalStorageColumns = List.copyOf(columns);
+ }
+
public String catalogName() {
return catalogName;
}
diff --git
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java
index abe0ce0458..ad5fe84a03 100644
---
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java
+++
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java
@@ -111,6 +111,20 @@ public interface HiveClient extends AutoCloseable {
List<HiveTable> getTableObjectsByName(
String catalogName, String databaseName, List<String> allTables);
+ /**
+ * Returns names of tables whose storage input format starts with the
supplied prefix.
+ *
+ * <p>This metadata-only operation does not resolve column schemas or load
constraints.
+ *
+ * @param catalogName The Hive catalog name.
+ * @param databaseName The database name.
+ * @param allTables The table names to inspect.
+ * @param inputFormatPrefix The required input format prefix.
+ * @return Matching table names.
+ */
+ List<String> getTableNamesByInputFormatPrefix(
+ String catalogName, String databaseName, List<String> allTables, String
inputFormatPrefix);
+
List<String> getCatalogs();
default void createCatalog(String catalogName, String location) {
diff --git
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java
index 1c9384f9b8..7378ce3a79 100644
---
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java
+++
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java
@@ -183,6 +183,14 @@ public class HiveClientImpl implements HiveClient {
return shim.getTableObjectsByName(catalogName, databaseName, allTables);
}
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getTableNamesByInputFormatPrefix(
+ String catalogName, String databaseName, List<String> allTables, String
inputFormatPrefix) {
+ return shim.getTableNamesByInputFormatPrefix(
+ catalogName, databaseName, allTables, inputFormatPrefix);
+ }
+
@Override
public List<String> getCatalogs() {
return shim.getCatalogs();
diff --git
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
index cc262a6f51..c67d5f3b8c 100644
---
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
+++
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveExceptionConverter.java
@@ -169,6 +169,19 @@ public class HiveExceptionConverter {
return new IllegalArgumentException(cause.getMessage(), cause);
}
+ if (exceptionClassName.contains("MetaException")
+ && lowerMessage.contains("type expected")
+ && lowerMessage.contains("<derived from deserializer>")) {
+ return new GravitinoRuntimeException(
+ cause,
+ "Hive Metastore cannot alter table %s while preserving its
SerDe-derived storage schema. "
+ + "The HMS server's column type compatibility check cannot parse
"
+ + "<derived from deserializer>. Ask the metastore administrator
to evaluate "
+ + "hive.metastore.disallow.incompatible.col.type.changes=false
on the HMS server; "
+ + "this disables column type compatibility checks for all
tables.",
+ target.name());
+ }
+
if (exceptionClassName.contains("MetaException")) {
if (lowerMessage.contains("invalid partition key")) {
return new NoSuchPartitionException(
@@ -189,6 +202,16 @@ public class HiveExceptionConverter {
}
}
+ // Schema-resolution messages include table names, which may contain
connection keywords.
+ if (lowerMessage.startsWith(
+ "hive metastore did not resolve serde-derived column types for
table ")
+ && (exceptionClassName.equals("MetaException")
+ || cause instanceof IllegalArgumentException)) {
+ return cause instanceof IllegalArgumentException
+ ? (IllegalArgumentException) cause
+ : new GravitinoRuntimeException(cause, message);
+ }
+
if (isConnectionKeyword(lowerMessage) ||
exceptionClassName.contains("TransportException")) {
return new ConnectionFailedException(
cause,
diff --git
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java
index 5faa4b5480..1693d8cce9 100644
---
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java
+++
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java
@@ -22,21 +22,28 @@ import static
org.apache.gravitino.hive.client.Util.updateConfigurationFromPrope
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
+import javax.annotation.Nullable;
import org.apache.gravitino.hive.HivePartition;
import org.apache.gravitino.hive.HiveSchema;
import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.hive.client.HiveExceptionConverter.ExceptionTarget;
import org.apache.gravitino.hive.converter.HiveDatabaseConverter;
import org.apache.gravitino.hive.converter.HiveTableConverter;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.types.Types;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.thrift.TException;
/**
@@ -50,6 +57,9 @@ import org.apache.thrift.TException;
*/
public abstract class HiveShim {
+ /** Marker used by Hive when column types must be resolved from the table
SerDe. */
+ protected static final String TYPE_FROM_DESERIALIZER = "<derived from
deserializer>";
+
protected static final String RETRYING_META_STORE_CLIENT_CLASS =
"org.apache.hadoop.hive.metastore.RetryingMetaStoreClient";
protected static final String HIVE_CONF_CLASS =
"org.apache.hadoop.hive.conf.HiveConf";
@@ -168,8 +178,8 @@ public abstract class HiveShim {
public HiveTable getTable(String catalogName, String databaseName, String
tableName) {
try {
- var tb = client.getTable(databaseName, tableName);
- return HiveTableConverter.fromHiveTable(tb);
+ Table tb = client.getTable(databaseName, tableName);
+ return convertTable(catalogName, tb);
} catch (Exception e) {
throw HiveExceptionConverter.toGravitinoException(e,
ExceptionTarget.table(tableName));
}
@@ -303,7 +313,32 @@ public abstract class HiveShim {
try {
// Hive2 doesn't support catalog, so we ignore catalogName and use
databaseName
var tables = client.getTableObjectsByName(databaseName, allTables);
- return tables.stream().map(HiveTableConverter::fromHiveTable).toList();
+ List<HiveTable> converted = new ArrayList<>();
+ for (Table table : tables) {
+ converted.add(convertTable(catalogName, table));
+ }
+ return converted;
+ } catch (Exception e) {
+ throw HiveExceptionConverter.toGravitinoException(e,
ExceptionTarget.schema(databaseName));
+ }
+ }
+
+ /**
+ * Returns names of tables whose storage input format starts with the
supplied prefix.
+ *
+ * <p>This metadata-only operation does not resolve column schemas or load
constraints.
+ *
+ * @param catalogName The Hive catalog name.
+ * @param databaseName The database name.
+ * @param allTables The table names to inspect.
+ * @param inputFormatPrefix The required input format prefix.
+ * @return Matching table names.
+ */
+ public List<String> getTableNamesByInputFormatPrefix(
+ String catalogName, String databaseName, List<String> allTables, String
inputFormatPrefix) {
+ try {
+ return tableNamesByInputFormatPrefix(
+ client.getTableObjectsByName(databaseName, allTables),
inputFormatPrefix);
} catch (Exception e) {
throw HiveExceptionConverter.toGravitinoException(e,
ExceptionTarget.schema(databaseName));
}
@@ -334,4 +369,121 @@ public abstract class HiveShim {
return new EnvironmentContext(
Collections.singletonMap(StatsSetupConst.DO_NOT_UPDATE_STATS,
StatsSetupConst.TRUE));
}
+
+ /**
+ * Resolves storage schemas and converts a table without loading column
constraints.
+ *
+ * @param catalogName The Hive catalog name.
+ * @param table The metastore table.
+ * @return The converted table, retaining its original derived schema for
alters.
+ * @throws TException If the metastore cannot resolve the schema.
+ */
+ protected HiveTable convertTable(String catalogName, Table table) throws
TException {
+ List<Column> original = resolveDerivedColumns(catalogName, table);
+ HiveTable converted = HiveTableConverter.fromHiveTable(table);
+ converted.setOriginalStorageColumns(original);
+ return converted;
+ }
+
+ /**
+ * Resolves only tables containing the SerDe-derived type marker.
+ *
+ * @param catalogName The Hive catalog name.
+ * @param table The metastore table to update in memory.
+ * @return A copy of the original storage columns, or an empty list for an
ordinary table.
+ * @throws TException If the metastore cannot resolve the schema.
+ */
+ protected List<Column> resolveDerivedColumns(String catalogName, Table
table) throws TException {
+ if (!hasDerivedColumnTypes(table)) {
+ return Collections.emptyList();
+ }
+ List<Column> original =
+ table.getSd().getCols().stream()
+ .<Column>map(
+ field ->
+ Column.of(
+ field.getName(),
+ Types.UnparsedType.of(field.getType()),
+ field.getComment()))
+ .toList();
+ try {
+ replaceDerivedColumns(table, getFields(catalogName, table.getDbName(),
table.getTableName()));
+ } catch (MetaException e) {
+ MetaException failure = new MetaException(derivedSchemaError(table));
+ failure.initCause(e);
+ throw failure;
+ }
+ return original;
+ }
+
+ /**
+ * Fetches storage columns using the version-specific metastore API.
+ *
+ * @param catalogName The Hive catalog name.
+ * @param databaseName The database name.
+ * @param tableName The table name.
+ * @return Storage columns resolved by Hive Metastore.
+ * @throws TException If the metastore request fails.
+ */
+ protected List<FieldSchema> getFields(String catalogName, String
databaseName, String tableName)
+ throws TException {
+ return client.getFields(databaseName, tableName);
+ }
+
+ /**
+ * Returns whether a table contains column types that Hive expects its SerDe
to resolve.
+ *
+ * @param table The Hive metastore table.
+ * @return {@code true} if at least one storage column has a derived type
marker.
+ */
+ protected static boolean hasDerivedColumnTypes(Table table) {
+ return table.getSd() != null
+ && table.getSd().getCols() != null
+ && table.getSd().getCols().stream()
+ .anyMatch(field -> TYPE_FROM_DESERIALIZER.equals(field.getType()));
+ }
+
+ /**
+ * Replaces storage columns containing Hive's derived type marker with
columns resolved by the
+ * table SerDe.
+ *
+ * @param table The Hive metastore table to update in memory.
+ * @param resolvedColumns The storage columns resolved by the Hive metastore.
+ */
+ protected static void replaceDerivedColumns(
+ Table table, @Nullable List<FieldSchema> resolvedColumns) {
+ if (resolvedColumns == null
+ || resolvedColumns.isEmpty()
+ || resolvedColumns.stream()
+ .anyMatch(field ->
TYPE_FROM_DESERIALIZER.equals(field.getType()))) {
+ throw new IllegalArgumentException(derivedSchemaError(table));
+ }
+ table.getSd().setCols(resolvedColumns);
+ }
+
+ /**
+ * Filters raw metastore tables by their input format without converting
their schemas.
+ *
+ * @param tables The metastore tables.
+ * @param inputFormatPrefix The required input format prefix.
+ * @return Matching table names.
+ */
+ protected static List<String> tableNamesByInputFormatPrefix(
+ List<Table> tables, String inputFormatPrefix) {
+ return tables.stream()
+ .filter(table -> table.getSd() != null &&
table.getSd().getInputFormat() != null)
+ .filter(table ->
table.getSd().getInputFormat().startsWith(inputFormatPrefix))
+ .map(Table::getTableName)
+ .toList();
+ }
+
+ private static String derivedSchemaError(Table table) {
+ return String.format(
+ "Hive Metastore did not resolve SerDe-derived column types for table
%s.%s. "
+ + "Make sure the table SerDe is on the Hive Metastore classpath.
For Hive 3, "
+ + "set metastore.storage.schema.reader.impl="
+ + "org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader on
Hive Metastore "
+ + "and restart the service.",
+ table.getDbName(), table.getTableName());
+ }
}
diff --git
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveTableConverter.java
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveTableConverter.java
index 25b5da049a..35de4e45d4 100644
---
a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveTableConverter.java
+++
b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveTableConverter.java
@@ -58,6 +58,7 @@ import org.apache.gravitino.rel.expressions.sorts.SortOrder;
import org.apache.gravitino.rel.expressions.sorts.SortOrders;
import org.apache.gravitino.rel.expressions.transforms.Transform;
import org.apache.gravitino.rel.types.Type;
+import org.apache.gravitino.rel.types.Types;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
@@ -184,6 +185,19 @@ public class HiveTableConverter {
table.setPartitionKeys(partitionFields);
}
+ if (!hiveTable.originalStorageColumns().isEmpty()) {
+ table
+ .getSd()
+ .setCols(
+ hiveTable.originalStorageColumns().stream()
+ .map(
+ column ->
+ new FieldSchema(
+ column.name(),
+ ((Types.UnparsedType)
column.dataType()).unparsedType(),
+ column.comment()))
+ .collect(Collectors.toList()));
+ }
table.setParameters(buildTableParameters(hiveTable));
// Set AuditInfo to Hive's Table object. Hive's Table doesn't support
setting last modifier
diff --git
a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestHiveSerDeSchema.java
b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestHiveSerDeSchema.java
new file mode 100644
index 0000000000..e6b39087a1
--- /dev/null
+++
b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/TestHiveSerDeSchema.java
@@ -0,0 +1,112 @@
+/*
+ * 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.hive;
+
+import static org.apache.gravitino.catalog.hive.HiveConstants.INPUT_FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.OUTPUT_FORMAT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.SERDE_LIB;
+import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+class TestHiveSerDeSchema extends MiniHiveMetastoreService {
+ private static final String MARKER = "<derived from deserializer>";
+
+ /**
+ * Starts Hive 2 HMS with the compatibility setting needed to preserve SerDe
markers.
+ *
+ * @throws Exception If the metastore cannot start.
+ */
+ @BeforeAll
+ public static void startMetastore() throws Exception {
+ MiniHiveMetastoreService.startMetastore(
+ Map.of("hive.metastore.disallow.incompatible.col.type.changes",
"false"));
+ }
+
+ @Test
+ void testRealSerDeResolutionAndMarkerPreservingAlters() throws Exception {
+ Properties properties = new Properties();
+ properties.setProperty(
+ HiveConf.ConfVars.METASTOREURIS.varname,
+ hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname));
+ String name = "serde_" + genRandomName();
+ HiveTable table =
+ HiveTable.builder()
+ .withName(name)
+ .withCatalogName("hive")
+ .withDatabaseName(DB_NAME)
+ .withColumns(new Column[] {Column.of("value",
Types.StringType.get())})
+ .withProperties(
+ new HashMap<>(
+ Map.of(
+ SERDE_LIB,
"org.apache.hadoop.hive.serde2.OpenCSVSerde",
+ INPUT_FORMAT,
"org.apache.hadoop.mapred.TextInputFormat",
+ OUTPUT_FORMAT,
"org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
+ TABLE_TYPE, "EXTERNAL_TABLE")))
+ .withAuditInfo(
+
AuditInfo.builder().withCreator("tester").withCreateTime(Instant.now()).build())
+ .build();
+ table.setOriginalStorageColumns(List.of(Column.of("value",
Types.UnparsedType.of(MARKER))));
+ try (HiveClientPool pool = new HiveClientPool("serde", 1, properties)) {
+ pool.run(
+ client -> {
+ client.createTable(table);
+ return null;
+ });
+ Assertions.assertEquals(
+ MARKER, metastoreClient.getTable(DB_NAME,
name).getSd().getCols().get(0).getType());
+ HiveTable loaded = pool.run(client -> client.getTable("hive", DB_NAME,
name));
+ Assertions.assertEquals(Types.StringType.get(),
loaded.columns()[0].dataType());
+ Assertions.assertEquals(
+ Types.StringType.get(),
+ pool.run(client -> client.getTableObjectsByName("hive", DB_NAME,
List.of(name)))
+ .get(0)
+ .columns()[0]
+ .dataType());
+ loaded.properties().put("serde_test", "value");
+ pool.run(
+ client -> {
+ client.alterTable("hive", DB_NAME, name, loaded, true);
+ return null;
+ });
+ Assertions.assertEquals(
+ MARKER, metastoreClient.getTable(DB_NAME,
name).getSd().getCols().get(0).getType());
+ Assertions.assertEquals(
+ "value", metastoreClient.getTable(DB_NAME,
name).getParameters().get("serde_test"));
+ pool.run(
+ client -> {
+ client.dropTable("hive", DB_NAME, name, false, false);
+ return null;
+ });
+ }
+ }
+}
diff --git
a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.java
b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.java
new file mode 100644
index 0000000000..4f30999cfc
--- /dev/null
+++
b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.java
@@ -0,0 +1,257 @@
+/*
+ * 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.hive.client;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import org.apache.gravitino.catalog.hive.HiveConstants;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
+import org.apache.gravitino.exceptions.NoSuchTableException;
+import org.apache.gravitino.hive.HiveTable;
+import org.apache.gravitino.hive.converter.HiveTableConverter;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Unit tests for loading Hive 2.x table schemas through {@link HiveShim}. */
+class TestHiveShimGetTable {
+
+ private static final String CATALOG = "hive";
+ private static final String DB = "db";
+ private static final String TABLE = "tbl";
+
+ private static class MockHiveShim extends HiveShim {
+ MockHiveShim() {
+ super(HiveClientClassLoader.HiveVersion.HIVE2, new Properties());
+ }
+
+ @Override
+ public IMetaStoreClient createMetaStoreClient(Properties properties) {
+ return mock(IMetaStoreClient.class);
+ }
+
+ IMetaStoreClient metaStoreClient() {
+ return client;
+ }
+ }
+
+ @Test
+ void testGetTableSkipsFieldResolutionForRegularColumns() throws Exception {
+ MockHiveShim shim = new MockHiveShim();
+ IMetaStoreClient client = shim.metaStoreClient();
+ when(client.getTable(DB, TABLE)).thenReturn(hiveTable("string"));
+
+ HiveTable loaded = shim.getTable(CATALOG, DB, TABLE);
+
+ Assertions.assertEquals(Types.StringType.get(),
loaded.columns()[0].dataType());
+ verify(client, never()).getFields(anyString(), anyString());
+ }
+
+ @Test
+ void testGetTableResolvesDerivedColumnTypes() throws Exception {
+ MockHiveShim shim = new MockHiveShim();
+ IMetaStoreClient client = shim.metaStoreClient();
+ when(client.getTable(DB,
TABLE)).thenReturn(hiveTable(HiveShim.TYPE_FROM_DESERIALIZER));
+ when(client.getFields(DB, TABLE))
+ .thenReturn(List.of(new FieldSchema("value", "string", "from
deserializer")));
+
+ HiveTable loaded = shim.getTable(CATALOG, DB, TABLE);
+
+ Assertions.assertEquals(Types.StringType.get(),
loaded.columns()[0].dataType());
+ Assertions.assertEquals("from deserializer",
loaded.columns()[0].comment());
+ verify(client).getFields(DB, TABLE);
+ }
+
+ @Test
+ void testReplaceDerivedColumnsRejectsUnresolvedTypes() {
+ Table table = hiveTable(HiveShim.TYPE_FROM_DESERIALIZER);
+ List<FieldSchema> unresolvedColumns =
+ List.of(new FieldSchema("value", HiveShim.TYPE_FROM_DESERIALIZER,
"from deserializer"));
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> HiveShim.replaceDerivedColumns(table, unresolvedColumns));
+
+ Assertions.assertTrue(
+ exception.getMessage().contains("did not resolve SerDe-derived column
types"));
+ }
+
+ @Test
+ void testBatchResolvesOnlyDerivedTablesAndPreservesOriginalColumns() throws
Exception {
+ MockHiveShim shim = new MockHiveShim();
+ IMetaStoreClient client = shim.metaStoreClient();
+ Table derived = hiveTable(HiveShim.TYPE_FROM_DESERIALIZER);
+ Table regular = hiveTable("int");
+ regular.setTableName("regular");
+ derived.setPartitionKeys(List.of(new FieldSchema("part", "int",
"partition")));
+ when(client.getTableObjectsByName(DB, List.of(TABLE, "regular")))
+ .thenReturn(List.of(derived, regular));
+ when(client.getFields(DB, TABLE)).thenReturn(List.of(new
FieldSchema("value", "string", null)));
+
+ List<HiveTable> loaded = shim.getTableObjectsByName(CATALOG, DB,
List.of(TABLE, "regular"));
+
+ Assertions.assertEquals(Types.StringType.get(),
loaded.get(0).columns()[0].dataType());
+ Assertions.assertEquals(Types.IntegerType.get(),
loaded.get(0).columns()[1].dataType());
+ Assertions.assertEquals(Types.IntegerType.get(),
loaded.get(1).columns()[0].dataType());
+ Assertions.assertTrue(loaded.get(1).originalStorageColumns().isEmpty());
+ Table roundTrip = HiveTableConverter.toHiveTable(loaded.get(0));
+ Assertions.assertEquals(
+ HiveShim.TYPE_FROM_DESERIALIZER,
roundTrip.getSd().getCols().get(0).getType());
+ Assertions.assertEquals("int",
roundTrip.getPartitionKeys().get(0).getType());
+ verify(client).getFields(DB, TABLE);
+ verify(client, never()).getFields(DB, "regular");
+ }
+
+ @Test
+ void testGetFieldsFailureIncludesServerConfigurationGuidance() throws
Exception {
+ for (String tableName : List.of(TABLE, "network_events",
"connect_events")) {
+ MockHiveShim shim = new MockHiveShim();
+ IMetaStoreClient client = shim.metaStoreClient();
+ Table derived = hiveTable(HiveShim.TYPE_FROM_DESERIALIZER);
+ derived.setTableName(tableName);
+ when(client.getTable(DB, tableName)).thenReturn(derived);
+ when(client.getFields(DB, tableName))
+ .thenThrow(new MetaException("Storage schema reading not
supported"));
+
+ GravitinoRuntimeException failure =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class, () -> shim.getTable(CATALOG,
DB, tableName));
+
+ Assertions.assertTrue(failure.getMessage().contains("Metastore
classpath"));
+
Assertions.assertTrue(failure.getMessage().contains("metastore.storage.schema.reader.impl="));
+ Assertions.assertNotNull(failure.getCause());
+ Assertions.assertEquals(GravitinoRuntimeException.class,
failure.getClass());
+ }
+ }
+
+ @Test
+ void testGetFieldsPreservesMissingTableException() throws Exception {
+ MockHiveShim shim = new MockHiveShim();
+ IMetaStoreClient client = shim.metaStoreClient();
+ when(client.getTable(DB,
TABLE)).thenReturn(hiveTable(HiveShim.TYPE_FROM_DESERIALIZER));
+ when(client.getFields(DB, TABLE)).thenThrow(new
NoSuchObjectException("Table disappeared"));
+ Assertions.assertThrows(NoSuchTableException.class, () ->
shim.getTable(CATALOG, DB, TABLE));
+ }
+
+ @Test
+ void testRejectsMissingResolvedColumns() {
+ for (List<FieldSchema> fields : Arrays.asList(null,
List.<FieldSchema>of())) {
+ IllegalArgumentException failure =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ HiveShim.replaceDerivedColumns(
+ hiveTable(HiveShim.TYPE_FROM_DESERIALIZER), fields));
+
Assertions.assertTrue(failure.getMessage().contains("metastore.storage.schema.reader.impl="));
+ }
+ }
+
+ @Test
+ void testGetTableRejectsUnresolvedSchemaAfterExceptionConversion() throws
Exception {
+ for (String tableName : List.of(TABLE, "network_events",
"connect_events")) {
+ MockHiveShim shim = new MockHiveShim();
+ Table derived = hiveTable(HiveShim.TYPE_FROM_DESERIALIZER);
+ derived.setTableName(tableName);
+ when(shim.metaStoreClient().getTable(DB, tableName)).thenReturn(derived);
+ when(shim.metaStoreClient().getFields(DB, tableName))
+ .thenReturn(List.of(new FieldSchema("value",
HiveShim.TYPE_FROM_DESERIALIZER, null)));
+ IllegalArgumentException failure =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> shim.getTable(CATALOG, DB,
tableName));
+
Assertions.assertTrue(failure.getMessage().contains("metastore.storage.schema.reader.impl="));
+ Assertions.assertEquals(IllegalArgumentException.class,
failure.getClass());
+ }
+ }
+
+ @Test
+ void testMetadataListingDoesNotResolveUnrelatedDerivedSchemas() throws
Exception {
+ MockHiveShim shim = new MockHiveShim();
+ Table derived = hiveTable(HiveShim.TYPE_FROM_DESERIALIZER);
+ derived.getSd().setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
+ Table hudi = hiveTable("int");
+ hudi.setTableName("hudi");
+
hudi.getSd().setInputFormat("org.apache.hudi.hadoop.HoodieParquetInputFormat");
+ Table missingFormat = hiveTable("int");
+ missingFormat.getSd().setInputFormat(null);
+ Table missingStorage = hiveTable("int");
+ missingStorage.setSd(null);
+ when(shim.metaStoreClient().getTableObjectsByName(DB, List.of(TABLE,
"hudi")))
+ .thenReturn(List.of(derived, hudi, missingFormat, missingStorage));
+ when(shim.metaStoreClient().getFields(DB, TABLE)).thenThrow(new
MetaException("SerDe missing"));
+ Assertions.assertEquals(
+ List.of("hudi"),
+ shim.getTableNamesByInputFormatPrefix(
+ CATALOG, DB, List.of(TABLE, "hudi"), "org.apache.hudi"));
+ verify(shim.metaStoreClient(), never()).getFields(anyString(),
anyString());
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> shim.getTableObjectsByName(CATALOG, DB, List.of(TABLE, "hudi")));
+ }
+
+ @Test
+ void testAlterMarkerCompatibilityFailureProvidesServerGuidance() {
+ MetaException cause =
+ new MetaException(
+ "java.lang.IllegalArgumentException: Error: type expected at the
position 0 of '<derived from deserializer>' but '<' is found.");
+ RuntimeException failure =
+ HiveExceptionConverter.toGravitinoException(
+ cause, HiveExceptionConverter.ExceptionTarget.table(TABLE));
+ Assertions.assertInstanceOf(GravitinoRuntimeException.class, failure);
+ Assertions.assertSame(cause, failure.getCause());
+ Assertions.assertTrue(
+ failure
+ .getMessage()
+
.contains("hive.metastore.disallow.incompatible.col.type.changes=false"));
+ Assertions.assertTrue(failure.getMessage().contains("all tables"));
+ }
+
+ private static Table hiveTable(String columnType) {
+ HiveTable table =
+ HiveTable.builder()
+ .withName(TABLE)
+ .withColumns(new Column[] {Column.of("value",
Types.StringType.get())})
+ .withProperties(Map.of(HiveConstants.LOCATION,
"hdfs://ns/warehouse/db.db/tbl"))
+ .withAuditInfo(
+
AuditInfo.builder().withCreator("tester").withCreateTime(Instant.now()).build())
+ .withCatalogName(CATALOG)
+ .withDatabaseName(DB)
+ .build();
+ Table hiveTable = HiveTableConverter.toHiveTable(table);
+ hiveTable.getSd().getCols().get(0).setType(columnType);
+ return hiveTable;
+ }
+}
diff --git
a/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java
b/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java
index dfc76ca5aa..8b45e37ba0 100644
---
a/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java
+++
b/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java
@@ -47,11 +47,13 @@ import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.Catalog;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.DefaultConstraintsRequest;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.NotNullConstraintsRequest;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.SQLDefaultConstraint;
import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -158,9 +160,21 @@ public class HiveShimV3 extends HiveShim {
if (TableType.VIRTUAL_VIEW.name().equalsIgnoreCase(tb.getTableType())) {
return HiveTableConverter.fromHiveTable(tb);
}
+ List<Column> original =
+ invoke(ExceptionTarget.table(tableName), () ->
resolveDerivedColumns(catalogName, tb));
ColumnConstraints constraints = loadColumnConstraints(catalogName,
databaseName, tableName);
- return HiveTableConverter.fromHiveTable(
- tb, notNullColumns(constraints), defaultValues(constraints));
+ HiveTable converted =
+ HiveTableConverter.fromHiveTable(
+ tb, notNullColumns(constraints), defaultValues(constraints));
+ converted.setOriginalStorageColumns(original);
+ return converted;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected List<FieldSchema> getFields(String catalogName, String
databaseName, String tableName)
+ throws TException {
+ return client.getFields(catalogName, databaseName, tableName);
}
@Override
@@ -348,7 +362,24 @@ public class HiveShimV3 extends HiveShim {
// This batch API is used to inspect tables while listing a schema.
Loading constraints here
// would add two sequential metastore calls per table. Full column
metadata remains available
// through getTable.
- return tables.stream().map(HiveTableConverter::fromHiveTable).toList();
+ return tables.stream()
+ .map(
+ table ->
+ invoke(
+ ExceptionTarget.table(table.getTableName()),
+ () -> convertTable(catalogName, table)))
+ .toList();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public List<String> getTableNamesByInputFormatPrefix(
+ String catalogName, String databaseName, List<String> allTables, String
inputFormatPrefix) {
+ return tableNamesByInputFormatPrefix(
+ invoke(
+ ExceptionTarget.schema(databaseName),
+ () -> client.getTableObjectsByName(catalogName, databaseName,
allTables)),
+ inputFormatPrefix);
}
@Override
diff --git
a/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java
b/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java
index b7ac7e0e14..03144f1538 100644
---
a/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java
+++
b/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java
@@ -40,6 +40,7 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.gravitino.catalog.hive.HiveConstants;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.hive.converter.HiveTableConverter;
import org.apache.gravitino.meta.AuditInfo;
@@ -49,6 +50,7 @@ import org.apache.gravitino.rel.types.Types;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.DefaultConstraintsRequest;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NotNullConstraintsRequest;
import org.apache.hadoop.hive.metastore.api.SQLDefaultConstraint;
@@ -339,6 +341,123 @@ class TestHiveShimV3 {
verify(client, never()).getDefaultConstraints(any());
}
+ @Test
+ void testGetTableResolvesDerivedColumnTypesWithCatalog() throws Exception {
+ MockHiveShimV3 shim = new MockHiveShimV3();
+ IMetaStoreClient client = shim.metaStoreClient();
+
+ Column plainColumn = Column.of("value", Types.StringType.get(), null,
true, false, null);
+ Table hiveTable = HiveTableConverter.toHiveTable(testTable(plainColumn));
+ hiveTable.setCatName(CATALOG);
+ hiveTable.getSd().getCols().get(0).setType("<derived from deserializer>");
+ when(client.getTable(CATALOG, DB, TABLE)).thenReturn(hiveTable);
+ when(client.getFields(CATALOG, DB, TABLE))
+ .thenReturn(List.of(new FieldSchema("value", "string", "from
deserializer")));
+
+ HiveTable loaded = shim.getTable(CATALOG, DB, TABLE);
+
+ assertEquals(Types.StringType.get(), loaded.columns()[0].dataType());
+ assertEquals("from deserializer", loaded.columns()[0].comment());
+ verify(client).getFields(CATALOG, DB, TABLE);
+ }
+
+ @Test
+ void testBatchResolvesDerivedColumnsWithCatalog() throws Exception {
+ MockHiveShimV3 shim = new MockHiveShimV3();
+ IMetaStoreClient client = shim.metaStoreClient();
+ Table derived =
+ HiveTableConverter.toHiveTable(testTable(Column.of("value",
Types.StringType.get())));
+ derived.getSd().getCols().get(0).setType("<derived from deserializer>");
+ Table regular =
+ HiveTableConverter.toHiveTable(testTable(Column.of("value",
Types.IntegerType.get())));
+ regular.setTableName("regular");
+ when(client.getTableObjectsByName(CATALOG, DB, List.of(TABLE, "regular")))
+ .thenReturn(List.of(derived, regular));
+ when(client.getFields(CATALOG, DB, TABLE))
+ .thenReturn(List.of(new FieldSchema("value", "string", null)));
+
+ List<HiveTable> loaded = shim.getTableObjectsByName(CATALOG, DB,
List.of(TABLE, "regular"));
+
+ assertEquals(Types.StringType.get(),
loaded.get(0).columns()[0].dataType());
+ assertEquals(Types.IntegerType.get(),
loaded.get(1).columns()[0].dataType());
+ assertEquals(
+ "<derived from deserializer>",
+
HiveTableConverter.toHiveTable(loaded.get(0)).getSd().getCols().get(0).getType());
+ verify(client).getFields(CATALOG, DB, TABLE);
+ verify(client, never()).getFields(CATALOG, DB, "regular");
+ verify(client, never()).getNotNullConstraints(any());
+ verify(client, never()).getDefaultConstraints(any());
+ }
+
+ @Test
+ void testGetFieldsFailureIncludesServerConfigurationGuidance() throws
Exception {
+ for (String tableName : List.of(TABLE, "network_events",
"connect_events")) {
+ MockHiveShimV3 shim = new MockHiveShimV3();
+ IMetaStoreClient client = shim.metaStoreClient();
+ Table derived =
+ HiveTableConverter.toHiveTable(testTable(Column.of("value",
Types.StringType.get())));
+ derived.getSd().getCols().get(0).setType("<derived from deserializer>");
+ derived.setTableName(tableName);
+ when(client.getTable(CATALOG, DB, tableName)).thenReturn(derived);
+ when(client.getFields(CATALOG, DB, tableName))
+ .thenThrow(new MetaException("Storage schema reading not
supported"));
+
+ GravitinoRuntimeException failure =
+ assertThrows(
+ GravitinoRuntimeException.class, () -> shim.getTable(CATALOG,
DB, tableName));
+
+
assertTrue(failure.getMessage().contains("metastore.storage.schema.reader.impl="));
+ verify(client, never()).getNotNullConstraints(any());
+ assertEquals(GravitinoRuntimeException.class, failure.getClass());
+ }
+ }
+
+ @Test
+ void testMetadataListingUsesCatalogWithoutResolvingSchemas() throws
Exception {
+ MockHiveShimV3 shim = new MockHiveShimV3();
+ IMetaStoreClient client = shim.metaStoreClient();
+ Table derived =
+ HiveTableConverter.toHiveTable(testTable(Column.of("value",
Types.StringType.get())));
+ derived.getSd().getCols().get(0).setType("<derived from deserializer>");
+ derived.getSd().setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
+ Table hudi =
+ HiveTableConverter.toHiveTable(testTable(Column.of("value",
Types.IntegerType.get())));
+ hudi.setTableName("hudi");
+
hudi.getSd().setInputFormat("org.apache.hudi.hadoop.HoodieParquetInputFormat");
+ when(client.getTableObjectsByName(CATALOG, DB, List.of(TABLE, "hudi")))
+ .thenReturn(List.of(derived, hudi));
+ when(client.getFields(CATALOG, DB, TABLE)).thenThrow(new
MetaException("SerDe missing"));
+ assertEquals(
+ List.of("hudi"),
+ shim.getTableNamesByInputFormatPrefix(
+ CATALOG, DB, List.of(TABLE, "hudi"), "org.apache.hudi"));
+ verify(client, never()).getFields(anyString(), anyString(), anyString());
+ verify(client, never()).getNotNullConstraints(any());
+ verify(client, never()).getDefaultConstraints(any());
+ assertThrows(
+ GravitinoRuntimeException.class,
+ () -> shim.getTableObjectsByName(CATALOG, DB, List.of(TABLE, "hudi")));
+ }
+
+ @Test
+ void testGetTableRejectsUnresolvedSchemaAfterExceptionConversion() throws
Exception {
+ for (String tableName : List.of(TABLE, "network_events",
"connect_events")) {
+ MockHiveShimV3 shim = new MockHiveShimV3();
+ IMetaStoreClient client = shim.metaStoreClient();
+ Table derived =
+ HiveTableConverter.toHiveTable(testTable(Column.of("value",
Types.StringType.get())));
+ derived.getSd().getCols().get(0).setType("<derived from deserializer>");
+ derived.setTableName(tableName);
+ when(client.getTable(CATALOG, DB, tableName)).thenReturn(derived);
+ when(client.getFields(CATALOG, DB,
tableName)).thenReturn(derived.getSd().getCols());
+ IllegalArgumentException failure =
+ assertThrows(IllegalArgumentException.class, () ->
shim.getTable(CATALOG, DB, tableName));
+
assertTrue(failure.getMessage().contains("metastore.storage.schema.reader.impl="));
+ verify(client, never()).getNotNullConstraints(any());
+ assertEquals(IllegalArgumentException.class, failure.getClass());
+ }
+ }
+
@Test
void testGetTableObjectsByNameDoesNotLoadConstraints() throws Exception {
MockHiveShimV3 shim = new MockHiveShimV3();
diff --git a/dev/docker/hive/hive-site.xml b/dev/docker/hive/hive-site.xml
index 1750539b78..efeecbed15 100644
--- a/dev/docker/hive/hive-site.xml
+++ b/dev/docker/hive/hive-site.xml
@@ -83,4 +83,10 @@
<value>SERVICE_ACCOUNT_FILE</value>
</property>
+ <!-- Resolve SerDe-derived storage schemas on Hive 3 HMS. Hive 2 ignores
this setting. -->
+ <property>
+ <name>metastore.storage.schema.reader.impl</name>
+ <value>org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader</value>
+ </property>
+
</configuration>
diff --git a/docs/apache-hive-catalog.md b/docs/apache-hive-catalog.md
index 37038ed3b1..7ce0da6265 100644
--- a/docs/apache-hive-catalog.md
+++ b/docs/apache-hive-catalog.md
@@ -259,3 +259,38 @@ Refer to [Manage view metadata using
Gravitino](./manage-view-metadata-using-gra
To create a Hive catalog with S3 storage, you can refer to the [Hive catalog
with S3](./hive-catalog-with-cloud-storage.md) documentation. No special
configurations are required for the Hive catalog to work with S3 storage.
The only difference is the storage location of the files, which is in S3. Use
`location` to specify the S3 path for the database or table.
+
+### SerDe-derived schemas
+
+Tables with `<derived from deserializer>` storage column types are resolved
through Hive
+Metastore's `getFields` API when loaded individually or in a batch. Ordinary
tables do not
+require an additional schema-resolution request. Hudi table listing filters
raw storage
+metadata without resolving unrelated table schemas, so an unresolvable
non-Hudi SerDe
+table does not prevent Hudi tables from being listed. Full schema batch reads
still fail
+if a requested table cannot be resolved. The table SerDe and its dependencies
must
+be available on the Hive Metastore classpath.
+
+Hive 3's default storage schema reader cannot resolve these schemas. Configure
the following
+property in the **Hive Metastore server's** `hive-site.xml` and restart Hive
Metastore:
+
+```xml
+<property>
+ <name>metastore.storage.schema.reader.impl</name>
+ <value>org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader</value>
+</property>
+```
+
+This server setting is also required when a Hive 2 client connects to a Hive 3
Metastore.
+If resolution fails or returns unresolved types, Gravitino reports an error
with configuration
+guidance rather than treating the marker as a Hive data type.
+
+Property, table-comment, and table-name changes preserve the original storage
column schema
+in Hive Metastore. Hive 2 HMS can reject even metadata-only alters when
+`hive.metastore.disallow.incompatible.col.type.changes=true`, because its
compatibility
+check attempts to parse the stored marker as a type. Preserving the marker
requires an
+HMS administrator to evaluate setting this property to `false` on the server
and restarting
+HMS. This disables column type compatibility checks for **all tables**;
Gravitino does not
+change this server setting. If the check rejects the marker, the error
explains this limitation.
+
+Column changes on SerDe-derived tables are rejected: modify those schemas
+through the SerDe or its external schema definition (for example,
`avro.schema.url`) instead.
diff --git
a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/HiveContainer.java
b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/HiveContainer.java
index 874116d31e..6db7a17bba 100644
---
a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/HiveContainer.java
+++
b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/HiveContainer.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.integration.test.container;
import static java.lang.String.format;
import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
+import static org.testcontainers.utility.MountableFile.forClasspathResource;
import com.google.common.collect.ImmutableSet;
import java.io.File;
@@ -50,6 +51,9 @@ public class HiveContainer extends BaseContainer {
public static final String HIVE2 = "hive2"; // The Hive container default
version
public static final String HIVE3 = "hive3";
public static final String ENABLE_SQL_BASE_AUTHORIZATION =
"ENABLE_SQL_BASE_AUTHORIZATION";
+ /** Enables HMS schema resolution and metadata alters for the SerDe schema
test fixtures. */
+ public static final String ENABLE_SERDE_SCHEMA_TESTS =
"ENABLE_SERDE_SCHEMA_TESTS";
+
private static final int MYSQL_PORT = 3306;
public static final int HDFS_DEFAULTFS_PORT = 9000;
public static final int HIVE_METASTORE_PORT = 9083;
@@ -80,6 +84,13 @@ public class HiveContainer extends BaseContainer {
@Override
protected void setupContainer() {
super.setupContainer();
+ if ("true".equals(container.getEnvMap().get(ENABLE_SERDE_SCHEMA_TESTS))) {
+ container.withCopyFileToContainer(
+ forClasspathResource("hive/enable-serde-schema-tests.sh"),
+ "/tmp/enable-serde-schema-tests.sh");
+ container.withCreateContainerCmdModifier(
+ command -> command.withEntrypoint("/bin/bash",
"/tmp/enable-serde-schema-tests.sh"));
+ }
withLogConsumer(new PrintingContainerLog(format("%-14s| ",
"HiveContainer-" + hostName)));
}
diff --git
a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TestHiveSerDeSchemaConfiguration.java
b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TestHiveSerDeSchemaConfiguration.java
new file mode 100644
index 0000000000..ae82f1d3ef
--- /dev/null
+++
b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TestHiveSerDeSchemaConfiguration.java
@@ -0,0 +1,95 @@
+/*
+ * 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.integration.test.container;
+
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+import org.junit.jupiter.api.io.TempDir;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+class TestHiveSerDeSchemaConfiguration {
+ @TempDir Path configurationDirectory;
+
+ @Test
+ @EnabledOnOs({OS.LINUX, OS.MAC})
+ void testPrebuiltImageConfigurationPreservesExistingProperties() throws
Exception {
+ String script;
+ try (InputStream source =
+ getClass().getResourceAsStream("/hive/enable-serde-schema-tests.sh")) {
+ Assertions.assertNotNull(source);
+ script = new String(source.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ // Run the actual configuration commands without starting the image's
services.
+ script = script.substring(0, script.indexOf("exec /bin/bash"));
+ List<String> files = List.of("hive-site.xml",
"hive-site-for-sql-base-auth.xml");
+ for (String file : files) {
+ Files.writeString(
+ configurationDirectory.resolve(file),
+ "<configuration>\n"
+ +
"<property><name>existing</name><value>keep</value></property>\n"
+ +
"<property><name>hive.metastore.disallow.incompatible.col.type.changes</name><value>true</value></property>\n"
+ + "</configuration>\n");
+ }
+ ProcessBuilder builder = new ProcessBuilder("bash", "-c",
script).redirectErrorStream(true);
+ builder.environment().put("HIVE_TMP_CONF_DIR",
configurationDirectory.toString());
+ Process process = builder.start();
+ try {
+ Assertions.assertTrue(process.waitFor(10, TimeUnit.SECONDS));
+ try (InputStream output = process.getInputStream()) {
+ Assertions.assertEquals(
+ 0, process.exitValue(), new String(output.readAllBytes(),
StandardCharsets.UTF_8));
+ }
+ } finally {
+ process.destroyForcibly();
+ }
+ for (String file : files) {
+ NodeList properties =
+ DocumentBuilderFactory.newInstance()
+ .newDocumentBuilder()
+ .parse(configurationDirectory.resolve(file).toFile())
+ .getElementsByTagName("property");
+ Map<String, String> values = new HashMap<>();
+ for (int index = 0; index < properties.getLength(); index++) {
+ Element property = (Element) properties.item(index);
+ values.put(
+ property.getElementsByTagName("name").item(0).getTextContent(),
+ property.getElementsByTagName("value").item(0).getTextContent());
+ }
+ Assertions.assertEquals("keep", values.get("existing"));
+ Assertions.assertEquals(
+ "false",
values.get("hive.metastore.disallow.incompatible.col.type.changes"));
+ Assertions.assertEquals(
+ "org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader",
+ values.get("metastore.storage.schema.reader.impl"));
+ }
+ }
+}
diff --git
a/integration-test-common/src/test/resources/hive/enable-serde-schema-tests.sh
b/integration-test-common/src/test/resources/hive/enable-serde-schema-tests.sh
new file mode 100644
index 0000000000..61b6bc3751
--- /dev/null
+++
b/integration-test-common/src/test/resources/hive/enable-serde-schema-tests.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+#
+# 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.
+#
+
+set -eu
+
+# Patch the configuration inside the prebuilt image before HMS starts.
+# Hive 2's compatibility check parses even unchanged SerDe markers as ordinary
types.
+for config in "${HIVE_TMP_CONF_DIR}/hive-site.xml"
"${HIVE_TMP_CONF_DIR}/hive-site-for-sql-base-auth.xml"; do
+ awk '
+ /<\/configuration>/ {
+ print "
<property><name>metastore.storage.schema.reader.impl</name><value>org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader</value></property>"
+ print "
<property><name>hive.metastore.disallow.incompatible.col.type.changes</name><value>false</value></property>"
+ }
+ { print }
+ ' "$config" > "$config.serde"
+ mv "$config.serde" "$config"
+done
+exec /bin/bash /usr/local/sbin/start.sh