World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13350] fix(catalog-hive): Support NOT NULL and DEFAULT column constraints on Hive 3 metastore (#13351)
Yuhui460cacfb8431
diff --git a/build.gradle.kts b/build.gradle.ktsindex 583c1d3deb..035403d7e5 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -352,15 +352,16 @@ subprojects {return@subprojects}- if (project.path == ":catalogs:hive-metastore2-libs" ||- project.path == ":catalogs:hive-metastore3-libs"- ) {- return@subprojects- }+ val isHiveMetastoreLib = project.path in setOf(+ ":catalogs:hive-metastore2-libs",+ ":catalogs:hive-metastore3-libs"+ )apply(plugin = "jacoco")- apply(plugin = "maven-publish")apply(plugin = "java")+ if (!isHiveMetastoreLib) {+ apply(plugin = "maven-publish")+ }// Force upgrade commons-beanutils/snappy-java for all subprojects to resolve outdated transitive versions// commons-beanutils: pulled by Hadoop, Hive, Spark, Flink, etc.@@ -596,61 +597,63 @@ subprojects {}}- apply(plugin = "signing")- publishing {- publications {- create<MavenPublication>("MavenJava") {- if (project.name == "docs" ||- project.name == "integration-test" ||- project.name == "integration-test-common" ||- project.name == "web"- ) {- setArtifacts(emptyList<Any>())- } else {- from(components["java"])- artifact(sourcesJar)- artifact(javadocJar)- }-- artifactId = "${rootProject.name.lowercase()}-${project.name}"+ if (!isHiveMetastoreLib) {+ apply(plugin = "signing")+ publishing {+ publications {+ create<MavenPublication>("MavenJava") {+ if (project.name == "docs" ||+ project.name == "integration-test" ||+ project.name == "integration-test-common" ||+ project.name == "web"+ ) {+ setArtifacts(emptyList<Any>())+ } else {+ from(components["java"])+ artifact(sourcesJar)+ artifact(javadocJar)+ }- pom {- name.set("Gravitino")- description.set("Gravitino is a high-performance, geo-distributed and federated metadata lake.")- url.set("https://gravitino.apache.org")- licenses {- license {- name.set("The Apache Software License, Version 2.0")- url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")+ artifactId = "${rootProject.name.lowercase()}-${project.name}"++ pom {+ name.set("Gravitino")+ description.set("Gravitino is a high-performance, geo-distributed and federated metadata lake.")+ url.set("https://gravitino.apache.org")+ licenses {+ license {+ name.set("The Apache Software License, Version 2.0")+ url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")+ }}- }- developers {- developer {- id.set("The Gravitino community")- name.set("support")- email.set("[email protected]")+ developers {+ developer {+ id.set("The Gravitino community")+ name.set("support")+ email.set("[email protected]")+ }+ }+ scm {+ url.set("https://github.com/apache/gravitino")+ connection.set("scm:git:git://github.com/apache/gravitino.git")}- }- scm {- url.set("https://github.com/apache/gravitino")- connection.set("scm:git:git://github.com/apache/gravitino.git")}}}}- }- configure<SigningExtension> {- val taskNames = gradle.getStartParameter().getTaskNames()- taskNames.forEach() {- if (it.contains("publishToMavenLocal")) setRequired(false)- }+ configure<SigningExtension> {+ val taskNames = gradle.getStartParameter().getTaskNames()+ taskNames.forEach() {+ if (it.contains("publishToMavenLocal")) setRequired(false)+ }- val gpgId = System.getenv("GPG_ID")- val gpgSecretKey = System.getenv("GPG_PRIVATE_KEY")- val gpgKeyPassword = System.getenv("GPG_PASSPHRASE")- useInMemoryPgpKeys(gpgId, gpgSecretKey, gpgKeyPassword)- sign(publishing.publications)+ val gpgId = System.getenv("GPG_ID")+ val gpgSecretKey = System.getenv("GPG_PRIVATE_KEY")+ val gpgKeyPassword = System.getenv("GPG_PASSPHRASE")+ useInMemoryPgpKeys(gpgId, gpgSecretKey, gpgKeyPassword)+ sign(publishing.publications)+ }}tasks.configureEach<Test> {diff --git a/catalogs/catalog-hive/build.gradle.kts b/catalogs/catalog-hive/build.gradle.ktsindex 6f913cb9aa..5fa39a7360 100644--- a/catalogs/catalog-hive/build.gradle.kts+++ b/catalogs/catalog-hive/build.gradle.kts@@ -127,6 +127,16 @@ dependencies {}tasks {+ // HiveClientClassLoader loads the version-specific client and shim jars from these modules at+ // runtime. Build them together with the Hive catalog so every downstream integration test that+ // depends on this jar has a complete Hive client runtime.+ jar {+ dependsOn(+ ":catalogs:hive-metastore2-libs:jar",+ ":catalogs:hive-metastore3-libs:jar"+ )+ }+register("runtimeJars", Copy::class) {from(configurations.runtimeClasspath)into("build/libs")@@ -173,6 +183,12 @@ tasks {}tasks.test {+ // Unit tests can create Hive clients without building this project's jar first.+ dependsOn(+ ":catalogs:hive-metastore2-libs:jar",+ ":catalogs:hive-metastore3-libs:jar"+ )+val skipITs = project.hasProperty("skipITs")if (skipITs) {// Exclude integration testsdiff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.javaindex afaaafd961..6fcccdf210 100644--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalog.java@@ -23,10 +23,15 @@ import org.apache.gravitino.connector.BaseCatalog;import org.apache.gravitino.connector.CatalogOperations;import org.apache.gravitino.connector.PropertiesMetadata;import org.apache.gravitino.connector.capability.Capability;+import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/** Implementation of an Apache Hive catalog in Apache Gravitino. */public class HiveCatalog extends BaseCatalog<HiveCatalog> {+ private static final Logger LOG = LoggerFactory.getLogger(HiveCatalog.class);+static final HiveCatalogPropertiesMetadata CATALOG_PROPERTIES_METADATA =new HiveCatalogPropertiesMetadata();@@ -54,13 +59,13 @@ public class HiveCatalog extends BaseCatalog<HiveCatalog> {*/@Overrideprotected CatalogOperations newOps(Map<String, String> config) {- HiveCatalogOperations ops = new HiveCatalogOperations();- return ops;+ return new HiveCatalogOperations();}@Overridepublic Capability newCapability() {- return new HiveCatalogCapability();+ ClassLoader catalogClassLoader = Thread.currentThread().getContextClassLoader();+ return new HiveCatalogCapability(() -> hiveVersion(catalogClassLoader));}@Override@@ -77,4 +82,32 @@ public class HiveCatalog extends BaseCatalog<HiveCatalog> {public PropertiesMetadata tablePropertiesMetadata() throws UnsupportedOperationException {return TABLE_PROPERTIES_METADATA;}++ /**+ * Resolves the Hive Metastore version through the catalog operations. Custom catalog operations+ * (ops-impl) do not expose the metastore version, so only what every supported Hive version+ * accepts is allowed.+ */+ private HiveVersion hiveVersion() {+ CatalogOperations ops = ops();+ if (!(ops instanceof HiveCatalogOperations)) {+ LOG.warn(+ "Catalog operations {} do not expose a Hive Metastore version; using the conservative "+ + "{} capability fallback",+ ops.getClass(),+ HiveVersion.HIVE2);+ return HiveVersion.HIVE2;+ }+ return ((HiveCatalogOperations) ops).hiveVersion();+ }++ private HiveVersion hiveVersion(ClassLoader catalogClassLoader) {+ ClassLoader original = Thread.currentThread().getContextClassLoader();+ Thread.currentThread().setContextClassLoader(catalogClassLoader);+ try {+ return hiveVersion();+ } finally {+ Thread.currentThread().setContextClassLoader(original);+ }+ }}diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.javaindex 5455fc1f02..1201f3e703 100644--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java@@ -18,26 +18,43 @@*/package org.apache.gravitino.catalog.hive;+import static org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion.HIVE3;++import java.util.function.Supplier;import org.apache.gravitino.connector.capability.Capability;import org.apache.gravitino.connector.capability.CapabilityResult;+import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;+/**+ * Capabilities of the Hive catalog. Column constraint support depends on the version of the+ * connected Hive Metastore, which is resolved and cached on first use.+ */public class HiveCatalogCapability implements Capability {++ private final Supplier<HiveVersion> hiveVersionSupplier;+ private volatile HiveVersion hiveVersion;++ /**+ * Creates a capability bound to the connected Hive Metastore version.+ *+ * @param hiveVersionSupplier Supplies the connected Hive Metastore version.+ */+ public HiveCatalogCapability(Supplier<HiveVersion> hiveVersionSupplier) {+ this.hiveVersionSupplier = hiveVersionSupplier;+ }+@Overridepublic CapabilityResult columnNotNull() {// The NOT NULL constraint for column is supported since Hive 3.0, see// https://issues.apache.org/jira/browse/HIVE-16575- return CapabilityResult.unsupported(- "The NOT NULL constraint for column is only supported since Hive 3.0, "- + "but the current Gravitino Hive catalog only supports Hive 2.x.");+ return requireHive3("NOT NULL");}@Overridepublic CapabilityResult columnDefaultValue() {// The DEFAULT constraint for column is supported since Hive 3.0, see// https://issues.apache.org/jira/browse/HIVE-18726- return CapabilityResult.unsupported(- "The DEFAULT constraint for column is only supported since Hive 3.0, "- + "but the current Gravitino Hive catalog only supports Hive 2.x.");+ return requireHive3("DEFAULT");}@Override@@ -53,4 +70,32 @@ public class HiveCatalogCapability implements Capability {return CapabilityResult.SUPPORTED;}}++ private CapabilityResult requireHive3(String constraint) {+ HiveVersion version = hiveVersion();+ if (version == HIVE3) {+ return CapabilityResult.SUPPORTED;+ }+ return CapabilityResult.unsupported(+ "The "+ + constraint+ + " constraint for column is only supported since Hive 3.0, "+ + "but the connected Hive Metastore version is "+ + version+ + ".");+ }++ private HiveVersion hiveVersion() {+ HiveVersion version = hiveVersion;+ if (version == null) {+ synchronized (this) {+ version = hiveVersion;+ if (version == null) {+ version = hiveVersionSupplier.get();+ hiveVersion = version;+ }+ }+ }+ return version;+ }}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.javaindex d510da7946..fd9971aa84 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@@ -70,6 +70,8 @@ import org.apache.gravitino.exceptions.ViewAlreadyExistsException;import org.apache.gravitino.hive.CachedClientPool;import org.apache.gravitino.hive.HiveSchema;import org.apache.gravitino.hive.HiveTable;+import org.apache.gravitino.hive.client.HiveClient;+import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;@@ -101,6 +103,8 @@ public class HiveCatalogOperations@VisibleForTesting CachedClientPool clientPool;+ private volatile HiveVersion hiveVersion;+@SuppressWarnings("UnusedVariable")private CatalogInfo info;@@ -1092,6 +1096,33 @@ public class HiveCatalogOperationsreturn clientPool;}+ /**+ * Returns the version of the connected Hive Metastore. The version is resolved once from the+ * client pool and cached, since it cannot change for the lifetime of the catalog.+ *+ * @return The connected Hive Metastore version.+ */+ HiveVersion hiveVersion() {+ if (hiveVersion == null) {+ synchronized (this) {+ if (hiveVersion == null) {+ Preconditions.checkState(+ clientPool != null, "Hive catalog operations are not initialized");+ try {+ hiveVersion =+ Preconditions.checkNotNull(+ clientPool.run(HiveClient::hiveVersion),+ "Hive client returned a null metastore version");+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw ExceptionMessages.wrap("Failed to resolve Hive Metastore version", e);+ }+ }+ }+ }+ return hiveVersion;+ }+@VisibleForTestingvoid setViewCatalogOperations(HiveViewCatalogOperations viewCatalogOperations) {this.viewCatalogOperations = viewCatalogOperations;diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.javaindex 831b2e5bd7..8fdb8dabae 100644--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalog.java@@ -23,14 +23,22 @@ import static org.apache.gravitino.catalog.hive.HiveCatalog.SCHEMA_PROPERTIES_MEimport static org.apache.gravitino.catalog.hive.HiveCatalog.TABLE_PROPERTIES_METADATA;import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.METASTORE_URIS;+import com.google.common.collect.ImmutableMap;import com.google.common.collect.Maps;+import java.io.IOException;import java.time.Instant;import java.util.List;import java.util.Map;import org.apache.gravitino.Namespace;import org.apache.gravitino.catalog.PropertiesMetadataHelpers;+import org.apache.gravitino.connector.BaseCatalog;+import org.apache.gravitino.connector.CatalogInfo;+import org.apache.gravitino.connector.CatalogOperations;import org.apache.gravitino.connector.HasPropertyMetadata;import org.apache.gravitino.connector.PropertiesMetadata;+import org.apache.gravitino.connector.capability.Capability;+import org.apache.gravitino.connector.capability.CapabilityResult;+import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;import org.apache.gravitino.hive.hms.MiniHiveMetastoreService;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.CatalogEntity;@@ -40,6 +48,36 @@ import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;public class TestHiveCatalog extends MiniHiveMetastoreService {++ /** Catalog operations used to verify the conservative capability fallback for custom ops. */+ public static class CustomCatalogOperations implements CatalogOperations {++ @Override+ public void initialize(+ Map<String, String> config, CatalogInfo info, HasPropertyMetadata propertiesMetadata) {}++ @Override+ public void close() throws IOException {}+ }++ /** Hive operations that record the context used to resolve the metastore version. */+ public static class ClassLoaderCapturingHiveCatalogOperations extends HiveCatalogOperations {+ private static ClassLoader initializationClassLoader;+ private static int hiveVersionCalls;++ @Override+ public void initialize(+ Map<String, String> config, CatalogInfo info, HasPropertyMetadata propertiesMetadata) {+ initializationClassLoader = Thread.currentThread().getContextClassLoader();+ }++ @Override+ HiveVersion hiveVersion() {+ hiveVersionCalls++;+ return HiveVersion.HIVE3;+ }+ }+public static final HasPropertyMetadata HIVE_PROPERTIES_METADATA =new HasPropertyMetadata() {@Override@@ -107,6 +145,60 @@ public class TestHiveCatalog extends MiniHiveMetastoreService {}}+ @Test+ void testCapabilityResolvedBeforeOps() {+ // The capability is preloaded by the catalog manager before the operations are created, so+ // it must be able to resolve the metastore version on its own.+ HiveCatalog catalog = TestHiveTable.initHiveCatalog();+ CapabilityResult notNull = catalog.capability().columnNotNull();+ Assertions.assertFalse(notNull.supported());+ Assertions.assertTrue(+ notNull.unsupportedMessage().contains("HIVE2"), notNull.unsupportedMessage());+ Assertions.assertFalse(catalog.capability().columnDefaultValue().supported());+ }++ @Test+ void testCapabilityWithCustomOperations() {+ HiveCatalog catalog =+ TestHiveTable.initHiveCatalog(+ ImmutableMap.of(+ BaseCatalog.CATALOG_OPERATION_IMPL, CustomCatalogOperations.class.getName()));+ CapabilityResult notNull = catalog.capability().columnNotNull();+ Assertions.assertFalse(notNull.supported());+ Assertions.assertTrue(+ notNull.unsupportedMessage().contains("HIVE2"), notNull.unsupportedMessage());+ }++ @Test+ void testCapabilityResolvesAndCachesVersionInCreationContext() {+ ClassLoader original = Thread.currentThread().getContextClassLoader();+ ClassLoader catalogClassLoader = new ClassLoader(original) {};+ ClassLoaderCapturingHiveCatalogOperations.initializationClassLoader = null;+ ClassLoaderCapturingHiveCatalogOperations.hiveVersionCalls = 0;++ HiveCatalog catalog =+ TestHiveTable.initHiveCatalog(+ ImmutableMap.of(+ BaseCatalog.CATALOG_OPERATION_IMPL,+ ClassLoaderCapturingHiveCatalogOperations.class.getName()));+ Capability capability;+ try {+ Thread.currentThread().setContextClassLoader(catalogClassLoader);+ capability = catalog.capability();+ } finally {+ Thread.currentThread().setContextClassLoader(original);+ }++ Assertions.assertNull(ClassLoaderCapturingHiveCatalogOperations.initializationClassLoader);+ Assertions.assertEquals(0, ClassLoaderCapturingHiveCatalogOperations.hiveVersionCalls);+ Assertions.assertTrue(capability.columnNotNull().supported());+ Assertions.assertSame(+ catalogClassLoader, ClassLoaderCapturingHiveCatalogOperations.initializationClassLoader);+ Assertions.assertEquals(1, ClassLoaderCapturingHiveCatalogOperations.hiveVersionCalls);+ Assertions.assertTrue(capability.columnDefaultValue().supported());+ Assertions.assertEquals(1, ClassLoaderCapturingHiveCatalogOperations.hiveVersionCalls);+ }+@Testvoid testCatalogProperty() {Map<String, String> properties = Maps.newHashMap();diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.javanew file mode 100644index 0000000000..919d411d0f--- /dev/null+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.java@@ -0,0 +1,66 @@+/*+ * 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;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import org.apache.gravitino.connector.capability.CapabilityResult;+import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;+import org.junit.jupiter.api.Test;++public class TestHiveCatalogCapability {++ @Test+ public void testColumnConstraintsOnHive2() {+ HiveCatalogCapability capability = new HiveCatalogCapability(() -> HiveVersion.HIVE2);++ CapabilityResult notNull = capability.columnNotNull();+ assertFalse(notNull.supported());+ assertTrue(notNull.unsupportedMessage().contains("connected Hive Metastore version is HIVE2"));++ CapabilityResult defaultValue = capability.columnDefaultValue();+ assertFalse(defaultValue.supported());+ assertTrue(+ defaultValue.unsupportedMessage().contains("connected Hive Metastore version is HIVE2"));+ }++ @Test+ public void testColumnConstraintsOnHive3() {+ HiveCatalogCapability capability = new HiveCatalogCapability(() -> HiveVersion.HIVE3);+ assertTrue(capability.columnNotNull().supported());+ assertTrue(capability.columnDefaultValue().supported());+ }++ @Test+ public void testVersionIsResolvedLazilyAndCached() {+ int[] resolutions = {0};+ HiveCatalogCapability capability =+ new HiveCatalogCapability(+ () -> {+ resolutions[0]++;+ return HiveVersion.HIVE3;+ });+ assertEquals(0, resolutions[0]);+ assertTrue(capability.columnNotNull().supported());+ assertTrue(capability.columnDefaultValue().supported());+ assertEquals(1, resolutions[0]);+ }+}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.javaindex 6bcf0814fb..508b33dda1 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@@ -44,6 +44,7 @@ import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.doNothing;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -67,6 +68,7 @@ import org.apache.gravitino.hive.CachedClientPool;import org.apache.gravitino.hive.HiveSchema;import org.apache.gravitino.hive.HiveTable;import org.apache.gravitino.hive.client.HiveClient;+import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.SQLRepresentation;@@ -175,6 +177,45 @@ class TestHiveCatalogOperations {Assertions.assertNull(pp.getProperty(""));}+ @Test+ void testHiveVersionIsCached() throws Exception {+ HiveCatalogOperations op = new HiveCatalogOperations();+ HiveClient hiveClient = mock(HiveClient.class);+ when(hiveClient.hiveVersion()).thenReturn(HiveVersion.HIVE3);+ CachedClientPool clientPool = mock(CachedClientPool.class);+ when(clientPool.run(any()))+ .thenAnswer(+ invocation -> {+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);+ return action.run(hiveClient);+ });+ op.clientPool = clientPool;++ Assertions.assertEquals(HiveVersion.HIVE3, op.hiveVersion());+ Assertions.assertEquals(HiveVersion.HIVE3, op.hiveVersion());+ verify(hiveClient, times(1)).hiveVersion();+ }++ @Test+ void testHiveVersionRetriesAfterFailure() throws Exception {+ HiveCatalogOperations op = new HiveCatalogOperations();+ CachedClientPool clientPool = mock(CachedClientPool.class);+ when(clientPool.run(any()))+ .thenThrow(new ConnectionFailedException("mock connection exception"))+ .thenReturn(HiveVersion.HIVE2);+ op.clientPool = clientPool;++ Assertions.assertThrows(ConnectionFailedException.class, op::hiveVersion);+ Assertions.assertEquals(HiveVersion.HIVE2, op.hiveVersion());+ }++ @Test+ void testHiveVersionBeforeInitialize() {+ HiveCatalogOperations op = new HiveCatalogOperations();+ IllegalStateException e = Assertions.assertThrows(IllegalStateException.class, op::hiveVersion);+ Assertions.assertTrue(e.getMessage().contains("not initialized"));+ }+@Testvoid testTestConnection() throws InterruptedException {HiveCatalogOperations op = new HiveCatalogOperations();diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.javaindex f2fc5188af..fd2bc77622 100644--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveTable.java@@ -29,6 +29,7 @@ import com.google.common.collect.ImmutableMap;import com.google.common.collect.Maps;import java.time.Instant;import java.util.Arrays;+import java.util.Collections;import java.util.Locale;import java.util.Map;import org.apache.gravitino.NameIdentifier;@@ -102,6 +103,10 @@ public class TestHiveTable extends MiniHiveMetastoreService {}protected static HiveCatalog initHiveCatalog() {+ return initHiveCatalog(Collections.emptyMap());+ }++ protected static HiveCatalog initHiveCatalog(Map<String, String> extraConf) {AuditInfo auditInfo =AuditInfo.builder().withCreator("testHiveUser").withCreateTime(Instant.now()).build();@@ -131,6 +136,7 @@ public class TestHiveTable extends MiniHiveMetastoreService {CATALOG_BYPASS_PREFIX + HiveConf.ConfVars.HIVE_IN_TEST.varname,hiveConf.get(HiveConf.ConfVars.HIVE_IN_TEST.varname));+ conf.putAll(extraConf);return new HiveCatalog().withCatalogConf(conf).withCatalogEntity(entity);}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.javaindex 8b3d9a9158..cc80bbe190 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@@ -408,10 +408,112 @@ public class CatalogHive2IT extends BaseIT {"Unsupported column type for sample value: " + column.dataType());}- private HiveTable loadHiveTable(String schema, String table) throws InterruptedException {+ protected HiveTable loadHiveTable(String schema, String table) throws InterruptedException {return hiveClientPool.run(client -> client.getTable(hmsCatalog, schema, table));}+ /**+ * Verifies how NOT NULL and DEFAULT columns are handled on table creation. Hive 2.x metastores do+ * not support column constraints, so both are rejected.+ */+ protected void checkColumnConstraintsOnCreate(+ NameIdentifier nameIdentifier, Map<String, String> properties) {+ // test column not null+ Column illegalColumn =+ Column.of("not_null_column", Types.StringType.get(), "not null column", false, false, null);+ IllegalArgumentException exception =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog+ .asTableCatalog()+ .createTable(+ nameIdentifier,+ new Column[] {illegalColumn},+ TABLE_COMMENT,+ properties,+ Transforms.EMPTY_TRANSFORM));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains(+ "The NOT NULL constraint for column is only supported since Hive 3.0, "+ + "but the connected Hive Metastore version is HIVE2"));++ // test column default value+ Column withDefault =+ Column.of(+ "default_column", Types.StringType.get(), "default column", true, false, Literals.NULL);+ exception =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ catalog+ .asTableCatalog()+ .createTable(+ nameIdentifier,+ new Column[] {withDefault},+ TABLE_COMMENT,+ properties,+ Transforms.EMPTY_TRANSFORM));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains(+ "The DEFAULT constraint for column is only supported since Hive 3.0, "+ + "but the connected Hive Metastore version is HIVE2"),+ "The exception message is: " + exception.getMessage());+ }++ /**+ * Verifies how NOT NULL and DEFAULT column changes are handled on table alteration. Hive 2.x+ * metastores do not support column constraints, so all of them are rejected.+ */+ protected void checkColumnConstraintsOnAlter(TableCatalog tableCatalog, NameIdentifier id) {+ // test add column with default value exception+ TableChange withDefaultValue =+ TableChange.addColumn(+ new String[] {"col_3"}, Types.ByteType.get(), "comment", Literals.NULL);+ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> tableCatalog.alterTable(id, withDefaultValue));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains(+ "The DEFAULT constraint for column is only supported since Hive 3.0, "+ + "but the connected Hive Metastore version is HIVE2"),+ "The exception message is: " + exception.getMessage());++ // test alter column nullability exception+ TableChange alterColumnNullability =+ TableChange.updateColumnNullability(new String[] {HIVE_COL_NAME1}, false);+ exception =+ assertThrows(+ IllegalArgumentException.class,+ () -> tableCatalog.alterTable(id, alterColumnNullability));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains(+ "The NOT NULL constraint for column is only supported since Hive 3.0,"+ + " but the connected Hive Metastore version is HIVE2. Illegal column: hive_col_name1"));++ // test update column default value exception+ TableChange updateDefaultValue =+ TableChange.updateColumnDefaultValue(new String[] {HIVE_COL_NAME1}, Literals.NULL);+ exception =+ assertThrows(+ IllegalArgumentException.class, () -> tableCatalog.alterTable(id, updateDefaultValue));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains(+ "The DEFAULT constraint for column is only supported since Hive 3.0, "+ + "but the connected Hive Metastore version is HIVE2"),+ "The exception message is: " + exception.getMessage());+ }+private HivePartition loadHivePartition(String schema, String table, String partition)throws InterruptedException {return hiveClientPool.run(@@ -642,51 +744,7 @@ public class CatalogHive2IT extends BaseIT {assertTableEquals(createdTable1, hiveTable1);checkTableReadWrite(hiveTable1);- // test column not null- Column illegalColumn =- Column.of("not_null_column", Types.StringType.get(), "not null column", false, false, null);- IllegalArgumentException exception =- assertThrows(- IllegalArgumentException.class,- () ->- catalog- .asTableCatalog()- .createTable(- nameIdentifier,- new Column[] {illegalColumn},- TABLE_COMMENT,- properties,- Transforms.EMPTY_TRANSFORM));- Assertions.assertTrue(- exception- .getMessage()- .contains(- "The NOT NULL constraint for column is only supported since Hive 3.0, "- + "but the current Gravitino Hive catalog only supports Hive 2.x"));-- // test column default value- Column withDefault =- Column.of(- "default_column", Types.StringType.get(), "default column", true, false, Literals.NULL);- exception =- assertThrows(- IllegalArgumentException.class,- () ->- catalog- .asTableCatalog()- .createTable(- nameIdentifier,- new Column[] {withDefault},- TABLE_COMMENT,- properties,- Transforms.EMPTY_TRANSFORM));- Assertions.assertTrue(- exception- .getMessage()- .contains(- "The DEFAULT constraint for column is only supported since Hive 3.0, "- + "but the current Gravitino Hive catalog only supports Hive 2.x"),- "The exception message is: " + exception.getMessage());+ checkColumnConstraintsOnCreate(nameIdentifier, properties);}@Test@@ -1326,48 +1384,7 @@ public class CatalogHive2IT extends BaseIT {});Assertions.assertTrue(exception.getMessage().contains("Cannot alter partition column"));- // test add column with default value exception- TableChange withDefaultValue =- TableChange.addColumn(- new String[] {"col_3"}, Types.ByteType.get(), "comment", Literals.NULL);- exception =- Assertions.assertThrows(- IllegalArgumentException.class, () -> tableCatalog.alterTable(id, withDefaultValue));- Assertions.assertTrue(- exception- .getMessage()- .contains(- "The DEFAULT constraint for column is only supported since Hive 3.0, "- + "but the current Gravitino Hive catalog only supports Hive 2.x"),- "The exception message is: " + exception.getMessage());-- // test alter column nullability exception- TableChange alterColumnNullability =- TableChange.updateColumnNullability(new String[] {HIVE_COL_NAME1}, false);- exception =- assertThrows(- IllegalArgumentException.class,- () -> tableCatalog.alterTable(id, alterColumnNullability));- Assertions.assertTrue(- exception- .getMessage()- .contains(- "The NOT NULL constraint for column is only supported since Hive 3.0,"- + " but the current Gravitino Hive catalog only supports Hive 2.x. Illegal column: hive_col_name1"));-- // test update column default value exception- TableChange updateDefaultValue =- TableChange.updateColumnDefaultValue(new String[] {HIVE_COL_NAME1}, Literals.NULL);- exception =- assertThrows(- IllegalArgumentException.class, () -> tableCatalog.alterTable(id, updateDefaultValue));- Assertions.assertTrue(- exception- .getMessage()- .contains(- "The DEFAULT constraint for column is only supported since Hive 3.0, "- + "but the current Gravitino Hive catalog only supports Hive 2.x"),- "The exception message is: " + exception.getMessage());+ checkColumnConstraintsOnAlter(tableCatalog, id);// test updateColumnPosition exceptionColumn col1 = Column.of("name", Types.StringType.get(), "comment");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.javaindex a678fa8c9d..431dbded28 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@@ -19,9 +19,22 @@package org.apache.gravitino.catalog.hive.integration.test;import com.google.common.collect.ImmutableMap;+import java.util.Arrays;+import java.util.Map;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.integration.test.container.HiveContainer;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableCatalog;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.types.Types;+import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Tag;import org.junit.jupiter.api.TestInstance;+import org.testcontainers.containers.Container.ExecResult;@Tag("gravitino-docker-test")@TestInstance(TestInstance.Lifecycle.PER_CLASS)@@ -39,4 +52,198 @@ public class CatalogHive3IT extends CatalogHive2IT {containerSuite.getHiveContainer().getContainerIpAddress(),HiveContainer.HIVE_METASTORE_PORT);}++ /** Returns the Hive container used by this test suite. */+ protected HiveContainer hiveContainer() {+ return containerSuite.getHiveContainer();+ }++ /** Hive 3.x metastores support NOT NULL and DEFAULT constraints, which must round-trip to HMS. */+ @Override+ protected void checkColumnConstraintsOnCreate(+ NameIdentifier nameIdentifier, Map<String, String> properties) {+ NameIdentifier constraintsIdent =+ NameIdentifier.of(schemaName, nameIdentifier.name() + "_constraints");+ Column notNullColumn =+ Column.of("not_null_column", Types.StringType.get(), "not null column", false, false, null);+ Column defaultColumn =+ Column.of(+ "default_column",+ Types.IntegerType.get(),+ "default column",+ true,+ false,+ Literals.integerLiteral(42));+ Column defaultStringColumn =+ Column.of(+ "default_string_column",+ Types.StringType.get(),+ null,+ false,+ false,+ Literals.stringLiteral("it's"));+ Column plainColumn = Column.of("plain_column", Types.StringType.get(), "plain column");++ catalog+ .asTableCatalog()+ .createTable(+ constraintsIdent,+ new Column[] {notNullColumn, defaultColumn, defaultStringColumn, plainColumn},+ TABLE_COMMENT,+ properties,+ Transforms.EMPTY_TRANSFORM);++ Table loaded = catalog.asTableCatalog().loadTable(constraintsIdent);+ assertColumnConstraints(loaded.columns());+ // Read back straight from HMS to make sure the constraints were persisted+ assertColumnConstraints(loadHiveTableColumns(schemaName, constraintsIdent.name()));+ executeHiveSql(+ String.format(+ "INSERT INTO TABLE %s.%s (not_null_column, plain_column) "+ + "VALUES ('required', 'plain')",+ schemaName, constraintsIdent.name()));+ ExecResult queryResult =+ executeHiveSql(+ String.format(+ "SELECT default_column, default_string_column FROM %s.%s",+ schemaName, constraintsIdent.name()));+ Assertions.assertEquals("42\tit's", queryResult.getStdout().trim());++ // Property-only alters must leave the constraints untouched+ catalog.asTableCatalog().alterTable(constraintsIdent, TableChange.setProperty("k1", "v1"));+ assertColumnConstraints(loadHiveTableColumns(schemaName, constraintsIdent.name()));++ // Constraints follow the table when it is renamed+ NameIdentifier renamedIdent =+ NameIdentifier.of(schemaName, constraintsIdent.name() + "_renamed");+ catalog.asTableCatalog().alterTable(constraintsIdent, TableChange.rename(renamedIdent.name()));+ assertColumnConstraints(catalog.asTableCatalog().loadTable(renamedIdent).columns());+ assertColumnConstraints(loadHiveTableColumns(schemaName, renamedIdent.name()));++ catalog.asTableCatalog().dropTable(renamedIdent);++ NameIdentifier partitionedIdent =+ NameIdentifier.of(schemaName, nameIdentifier.name() + "_partition_constraints");+ Column valueColumn = Column.of("value_column", Types.StringType.get());+ Column partitionColumn =+ Column.of(+ "partition_column", Types.StringType.get(), "partition column", false, false, null);+ catalog+ .asTableCatalog()+ .createTable(+ partitionedIdent,+ new Column[] {valueColumn, partitionColumn},+ TABLE_COMMENT,+ properties,+ new Transform[] {Transforms.identity(partitionColumn.name())});+ Assertions.assertFalse(+ findColumn(catalog.asTableCatalog().loadTable(partitionedIdent), partitionColumn.name())+ .nullable());+ Assertions.assertFalse(+ findColumn(+ loadHiveTableColumns(schemaName, partitionedIdent.name()), partitionColumn.name())+ .nullable());+ catalog.asTableCatalog().dropTable(partitionedIdent);++ NameIdentifier hiveDdlIdent =+ NameIdentifier.of(schemaName, nameIdentifier.name() + "_hive_default");+ executeHiveSql(+ String.format(+ "CREATE TABLE %s.%s (quoted_string STRING DEFAULT 'it''s')",+ schemaName, hiveDdlIdent.name()));+ try {+ Assertions.assertEquals(+ Literals.stringLiteral("it's"),+ findColumn(catalog.asTableCatalog().loadTable(hiveDdlIdent), "quoted_string")+ .defaultValue());+ } finally {+ executeHiveSql(String.format("DROP TABLE %s.%s", schemaName, hiveDdlIdent.name()));+ }+ }++ private ExecResult executeHiveSql(String sql) {+ ExecResult result = hiveContainer().executeInContainer("hive", "-S", "-e", sql);+ Assertions.assertEquals(+ 0,+ result.getExitCode(),+ String.format(+ "Failed to execute SQL with hive cli. SQL: %s, stdout: %s, stderr: %s",+ sql, result.getStdout(), result.getStderr()));+ return result;+ }++ private Column[] loadHiveTableColumns(String schema, String table) {+ try {+ return loadHiveTable(schema, table).columns();+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new RuntimeException(e);+ }+ }++ private void assertColumnConstraints(Column[] columns) {+ Assertions.assertEquals(4, columns.length);+ Assertions.assertFalse(columns[0].nullable());+ Assertions.assertEquals(Column.DEFAULT_VALUE_NOT_SET, columns[0].defaultValue());+ Assertions.assertTrue(columns[1].nullable());+ Assertions.assertEquals(Literals.integerLiteral(42), columns[1].defaultValue());+ Assertions.assertFalse(columns[2].nullable());+ Assertions.assertEquals(Literals.stringLiteral("it's"), columns[2].defaultValue());+ Assertions.assertTrue(columns[3].nullable());+ Assertions.assertEquals(Column.DEFAULT_VALUE_NOT_SET, columns[3].defaultValue());+ }++ /** Hive 3.x metastores support NOT NULL and DEFAULT constraints, which are synced on alter. */+ @Override+ protected void checkColumnConstraintsOnAlter(TableCatalog tableCatalog, NameIdentifier id) {+ // add column with default value+ Table altered =+ tableCatalog.alterTable(+ id,+ TableChange.addColumn(+ new String[] {"col_3"}, Types.ByteType.get(), "comment", Literals.NULL));+ Column col3 = findColumn(altered, "col_3");+ Assertions.assertEquals(Literals.NULL, col3.defaultValue());++ // set column NOT NULL and a default value+ altered =+ tableCatalog.alterTable(+ id,+ TableChange.updateColumnNullability(new String[] {HIVE_COL_NAME1}, false),+ TableChange.updateColumnDefaultValue(+ new String[] {HIVE_COL_NAME1}, Literals.integerLiteral(7)));+ Column col1 = findColumn(altered, HIVE_COL_NAME1);+ Assertions.assertFalse(col1.nullable());+ Assertions.assertEquals(Literals.integerLiteral(7), col1.defaultValue());+ col1 = findColumn(tableCatalog.loadTable(id), HIVE_COL_NAME1);+ Assertions.assertFalse(col1.nullable());+ Assertions.assertEquals(Literals.integerLiteral(7), col1.defaultValue());++ // change the default value and make the column nullable again+ tableCatalog.alterTable(+ id,+ TableChange.updateColumnNullability(new String[] {HIVE_COL_NAME1}, true),+ TableChange.updateColumnDefaultValue(+ new String[] {HIVE_COL_NAME1}, Literals.integerLiteral(8)));+ col1 = findColumn(tableCatalog.loadTable(id), HIVE_COL_NAME1);+ Assertions.assertTrue(col1.nullable());+ Assertions.assertEquals(Literals.integerLiteral(8), col1.defaultValue());++ // dropping the column removes its constraints+ tableCatalog.alterTable(id, TableChange.deleteColumn(new String[] {"col_3"}, false));+ Table reloaded = tableCatalog.loadTable(id);+ Assertions.assertTrue(+ Arrays.stream(reloaded.columns()).noneMatch(c -> c.name().equals("col_3")));+ }++ private Column findColumn(Table table, String name) {+ return findColumn(table.columns(), name);+ }++ private Column findColumn(Column[] columns, String name) {+ return Arrays.stream(columns)+ .filter(c -> c.name().equals(name))+ .findFirst()+ .orElseThrow(() -> new AssertionError("Column not found: " + name));+ }}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.javaindex 04d1b80e5f..2ef3d2e6a2 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@@ -120,6 +120,12 @@ public class CatalogHiveS3IT extends CatalogHive3IT {HiveContainer.HIVE_METASTORE_PORT);}+ /** {@inheritDoc} */+ @Override+ protected HiveContainer hiveContainer() {+ return containerSuite.getHiveContainerWithS3();+ }+@Overrideprotected void initFileSystem() throws IOException {// Use S3a file systemdiff --git a/catalogs/catalog-lakehouse-hudi/build.gradle.kts b/catalogs/catalog-lakehouse-hudi/build.gradle.ktsindex 29c5f39a50..13d830fca0 100644--- a/catalogs/catalog-lakehouse-hudi/build.gradle.kts+++ b/catalogs/catalog-lakehouse-hudi/build.gradle.kts@@ -185,6 +185,13 @@ tasks {}tasks.test {+ // Hudi uses HiveClientClassLoader directly without depending on catalog-hive, so prepare the+ // version-specific Hive client and shim jars before its tests run.+ dependsOn(+ ":catalogs:hive-metastore2-libs:jar",+ ":catalogs:hive-metastore3-libs:jar"+ )+val skipITs = project.hasProperty("skipITs")if (skipITs) {// Exclude integration testsdiff --git a/catalogs/hive-metastore-common/build.gradle.kts b/catalogs/hive-metastore-common/build.gradle.ktsindex 7780854589..8c361ffc6c 100644--- a/catalogs/hive-metastore-common/build.gradle.kts+++ b/catalogs/hive-metastore-common/build.gradle.kts@@ -156,12 +156,15 @@ artifacts {add("testArtifacts", testJar)}-// Ensure the shaded Hive metastore lib jars exist before compiling this module,-// since compileOnly(project(":catalogs:hive-metastore{2,3}-libs")) puts those-// jars on the compile classpath and they are produced by the copyDepends tasks.-tasks.named<JavaCompile>("compileJava") {+// Ensure the shaded Hive metastore lib jars (plus the HiveShimV2/HiveShimV3 classes compiled in+// those modules) exist before running tests: HiveClientClassLoader loads every jar under+// hive-metastore{2,3}-libs/build/libs at test time (GRAVITINO_TEST), so their own compiled-source+// jars must be built too, not just their copyDepends-copied external dependency jars. This is on+// "test" rather than "compileJava": those two modules compileOnly this module (for the shared+// HiveShim base class), so depending on their "jar" task from "compileJava" would be circular.+tasks.named<Test>("test") {dependsOn(- ":catalogs:hive-metastore2-libs:copyDepends",- ":catalogs:hive-metastore3-libs:copyDepends"+ ":catalogs:hive-metastore2-libs:jar",+ ":catalogs:hive-metastore3-libs:jar")}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.javaindex ec52dc6485..abe0ce0458 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@@ -122,4 +122,11 @@ public interface HiveClient extends AutoCloseable {void close();UserGroupInformation getUser();++ /**+ * Returns the Hive version of the metastore backend this client is connected to.+ *+ * @return The resolved Hive version.+ */+ HiveClientClassLoader.HiveVersion hiveVersion();}diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.javaindex aa18c95340..72de829bff 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientClassLoader.java@@ -250,8 +250,14 @@ public final class HiveClientClassLoader extends URLClassLoader {return true;}- // Gravitino classes- if (name.startsWith("org.apache.gravitino.")) {+ // Gravitino classes, except the version-specific shim implementations (HiveShimV2/HiveShimV3):+ // those are compiled only into their own hive-metastore{2,3}-libs module and are not on the+ // base classloader's classpath, so sharing them would always miss and fall through to the+ // isolated classloader anyway; excluding them here makes that isolated loading deterministic+ // instead of relying on the ClassNotFoundException fallback in loadSharedClass.+ if (name.startsWith("org.apache.gravitino.")+ && !name.startsWith("org.apache.gravitino.hive.client.hive2.")+ && !name.startsWith("org.apache.gravitino.hive.client.hive3.")) {return true;}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.javaindex 1f7818a9c8..1c9384f9b8 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@@ -32,23 +32,36 @@ import org.apache.hadoop.security.UserGroupInformation;*/public class HiveClientImpl implements HiveClient {+ // Fully-qualified name of the HiveShim implementation for each Hive version. Each one lives in+ // its own module (hive-metastore{2,3}-libs), compiled directly against that version's real+ // metastore client jar, so it cannot be constructed with `new` from this class: the isolated+ // Hive-version classloader that is already active for this HiveClientImpl instance is asked to+ // load and construct it instead.+ private static final String HIVE2_SHIM_CLASS =+ "org.apache.gravitino.hive.client.hive2.HiveShimV2";+ private static final String HIVE3_SHIM_CLASS =+ "org.apache.gravitino.hive.client.hive3.HiveShimV3";+private final HiveShim shim;public HiveClientImpl(HiveClientClassLoader.HiveVersion hiveVersion, Properties properties) {+ String shimClassName;switch (hiveVersion) {case HIVE2:- {- shim = new HiveShimV2(properties);- break;- }+ shimClassName = HIVE2_SHIM_CLASS;+ break;case HIVE3:- {- shim = new HiveShimV3(properties);- break;- }+ shimClassName = HIVE3_SHIM_CLASS;+ break;default:throw new IllegalArgumentException("Unsupported Hive version: " + hiveVersion);}+ try {+ Class<?> shimClass = getClass().getClassLoader().loadClass(shimClassName);+ this.shim = (HiveShim) shimClass.getConstructor(Properties.class).newInstance(properties);+ } catch (Exception e) {+ throw ExceptionMessages.wrap("Failed to create Hive metastore shim for " + hiveVersion, e);+ }}@Override@@ -197,4 +210,9 @@ public class HiveClientImpl implements HiveClient {throw ExceptionMessages.wrap("Failed to get current user", e);}}++ @Override+ public HiveClientClassLoader.HiveVersion hiveVersion() {+ return shim.hiveVersion();+ }}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.javaindex 7dbdca1426..5faa4b5480 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@@ -18,20 +18,35 @@*/package org.apache.gravitino.hive.client;+import static org.apache.gravitino.hive.client.Util.updateConfigurationFromProperties;++import java.lang.reflect.Constructor;+import java.lang.reflect.Method;+import java.util.Collections;import java.util.List;import java.util.Properties;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.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.thrift.TException;/*** Java translation of Scala's `Shim` sealed abstract class.*- * <p>This class declares the compatibility layer between Spark and different Hive versions.- * Concrete subclasses (e.g. HiveShimV2, HiveShimV3 ...) must implement these methods according to- * the behavior of the corresponding Hive release.+ * <p>This class provides the Hive 2.x-compatible behavior of the metastore client, which is also+ * the baseline every later Hive release stays compatible with. Version-specific subclasses (e.g.+ * the Hive 3.x implementation, which adds multi-catalog support and column constraints) live in+ * their own module, compiled directly against their own metastore client jar, and override+ * whichever methods behave differently for that version.*/public abstract class HiveShim {@@ -49,7 +64,37 @@ public abstract class HiveShim {this.version = version;}- public abstract IMetaStoreClient createMetaStoreClient(Properties properties);+ /**+ * Returns the Hive version this shim was created for, which is the version Gravitino detected for+ * the connected metastore.+ *+ * @return The Hive version of this shim.+ */+ public HiveClientClassLoader.HiveVersion hiveVersion() {+ return version;+ }++ public IMetaStoreClient createMetaStoreClient(Properties properties) {+ try {+ ClassLoader classLoader = this.getClass().getClassLoader();+ Class<?> clientClass = classLoader.loadClass(RETRYING_META_STORE_CLIENT_CLASS);+ Class<?> hiveConfClass = classLoader.loadClass(HIVE_CONF_CLASS);+ Class<?> confClass = classLoader.loadClass(CONFIGURATION_CLASS);++ Object conf = confClass.getDeclaredConstructor().newInstance();+ updateConfigurationFromProperties(properties, (Configuration) conf);++ Constructor<?> hiveConfCtor = hiveConfClass.getConstructor(confClass, Class.class);+ Object hiveConfInstance = hiveConfCtor.newInstance(conf, hiveConfClass);++ Method getProxyMethod = clientClass.getMethod(METHOD_GET_PROXY, hiveConfClass, boolean.class);+ return (IMetaStoreClient) getProxyMethod.invoke(null, hiveConfInstance, false);++ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(+ e, ExceptionTarget.other("MetaStoreClient"));+ }+ }public List<String> getAllDatabases(String catalogName) {try {@@ -60,66 +105,233 @@ public abstract class HiveShim {}}- public abstract void createDatabase(HiveSchema database);+ public void createDatabase(HiveSchema database) {+ try {+ Database db = HiveDatabaseConverter.toHiveDb(database);+ client.createDatabase(db);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(database.name()));+ }+ }- public abstract HiveSchema getDatabase(String catalogName, String databaseName);+ public HiveSchema getDatabase(String catalogName, String databaseName) {+ try {+ Database db = client.getDatabase(databaseName);+ return HiveDatabaseConverter.fromHiveDB(db);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract void alterDatabase(String catalogName, String databaseName, HiveSchema database);+ public void alterDatabase(String catalogName, String databaseName, HiveSchema database) {+ try {+ Database db = HiveDatabaseConverter.toHiveDb(database);+ client.alterDatabase(databaseName, db);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract void dropDatabase(String catalogName, String databaseName, boolean cascade);+ public void dropDatabase(String catalogName, String databaseName, boolean cascade) {+ try {+ client.dropDatabase(databaseName, false, false, cascade);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract List<String> getAllTables(String catalogName, String databaseName);+ public List<String> getAllTables(String catalogName, String databaseName) {+ try {+ return client.getAllTables(databaseName);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract List<String> listTablesByType(- String catalogName, String databaseName, String tablePattern, String tableType);+ public List<String> listTablesByType(+ String catalogName, String databaseName, String tablePattern, String tableType) {+ try {+ return client.getTables(databaseName, tablePattern, TableType.valueOf(tableType));+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract List<String> listTableNamesByFilter(- String catalogName, String databaseName, String filter, short pageSize);+ public List<String> listTableNamesByFilter(+ String catalogName, String databaseName, String filter, short pageSize) {+ try {+ return client.listTableNamesByFilter(databaseName, filter, pageSize);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract HiveTable getTable(String catalogName, String databaseName, String tableName);+ public HiveTable getTable(String catalogName, String databaseName, String tableName) {+ try {+ var tb = client.getTable(databaseName, tableName);+ return HiveTableConverter.fromHiveTable(tb);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));+ }+ }- public abstract void alterTable(+ public void alterTable(String catalogName,String databaseName,String tableName,HiveTable alteredHiveTable,- boolean skipStatsUpdate);+ boolean skipStatsUpdate) {+ try {+ var tb = HiveTableConverter.toHiveTable(alteredHiveTable);+ if (skipStatsUpdate) {+ // Instruct the metastore not to recompute statistics for this alter, so it does not access+ // the table's storage location. Hive 2.x has no catalog-aware alter, so the database name+ // is used directly.+ client.alter_table_with_environmentContext(+ databaseName, tableName, tb, doNotUpdateStatsContext());+ } else {+ client.alter_table(databaseName, tableName, tb);+ }+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));+ }+ }- public abstract void dropTable(+ public void dropTable(String catalogName,String databaseName,String tableName,boolean deleteData,- boolean ifPurge);+ boolean ifPurge) {+ try {+ client.dropTable(databaseName, tableName, deleteData, ifPurge);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));+ }+ }- public abstract void createTable(HiveTable hiveTable);+ public void createTable(HiveTable hiveTable) {+ try {+ var tb = HiveTableConverter.toHiveTable(hiveTable);+ client.createTable(tb);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(hiveTable.name()));+ }+ }- public abstract List<String> listPartitionNames(HiveTable table, short pageSize);+ public List<String> listPartitionNames(HiveTable table, short pageSize) {+ try {+ String databaseName = table.databaseName();+ return client.listPartitionNames(databaseName, table.name(), pageSize);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(table.name()));+ }+ }- public abstract List<HivePartition> listPartitions(HiveTable table, short pageSize);+ public List<HivePartition> listPartitions(HiveTable table, short pageSize) {+ try {+ String databaseName = table.databaseName();+ var partitions = client.listPartitions(databaseName, table.name(), pageSize);+ return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(table.name()));+ }+ }- public abstract List<HivePartition> listPartitions(- HiveTable table, List<String> filterPartitionValueList, short pageSize);+ public List<HivePartition> listPartitions(+ HiveTable table, List<String> filterPartitionValueList, short pageSize) {+ try {+ String databaseName = table.databaseName();+ var partitions =+ client.listPartitions(databaseName, table.name(), filterPartitionValueList, pageSize);+ return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(table.name()));+ }+ }- public abstract HivePartition getPartition(HiveTable table, String partitionName);+ public HivePartition getPartition(HiveTable table, String partitionName) {+ try {+ String databaseName = table.databaseName();+ var partitionValues = HivePartition.extractPartitionValues(partitionName);+ var partition = client.getPartition(databaseName, table.name(), partitionValues);+ return HiveTableConverter.fromHivePartition(table, partition);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(+ e, ExceptionTarget.partition(partitionName));+ }+ }- public abstract HivePartition addPartition(HiveTable table, HivePartition partition);+ public HivePartition addPartition(HiveTable table, HivePartition partition) {+ try {+ String databaseName = table.databaseName();+ var hivePartition = HiveTableConverter.toHivePartition(databaseName, table, partition);+ var addedPartition = client.add_partition(hivePartition);+ return HiveTableConverter.fromHivePartition(table, addedPartition);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(+ e, ExceptionTarget.partition(partition.name()));+ }+ }- public abstract void dropPartition(- String catalogName, String databaseName, String tableName, String partitionName, boolean b);+ public void dropPartition(+ String catalogName,+ String databaseName,+ String tableName,+ String partitionName,+ boolean deleteData) {+ try {+ var partitionValues = HivePartition.extractPartitionValues(partitionName);+ client.dropPartition(databaseName, tableName, partitionValues, deleteData);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(+ e, ExceptionTarget.partition(partitionName));+ }+ }- public abstract String getDelegationToken(String finalPrincipalName, String userName);+ public String getDelegationToken(String finalPrincipalName, String userName) {+ try {+ return client.getDelegationToken(finalPrincipalName, userName);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(+ e, ExceptionTarget.other(finalPrincipalName));+ }+ }- public abstract List<HiveTable> getTableObjectsByName(- String catalogName, String databaseName, List<String> allTables);+ public List<HiveTable> getTableObjectsByName(+ String catalogName, String databaseName, List<String> allTables) {+ 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();+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));+ }+ }- public abstract List<String> getCatalogs();+ public List<String> getCatalogs() {+ return List.of();+ }- public abstract void createCatalog(String catalogName, String location, String description);+ public void createCatalog(String catalogName, String location, String description) {+ throw new UnsupportedOperationException(+ "Catalog creation is not supported in Hive 2.x. Please upgrade to Hive 3.x.");+ }public void close() throws Exception {if (client != null) {client.close();}}++ /**+ * Builds an {@link EnvironmentContext} that tells the metastore not to recompute table statistics+ * during an alter, avoiding an access to the table's storage location.+ *+ * @return An environment context with {@code DO_NOT_UPDATE_STATS} set to {@code true}.+ */+ protected EnvironmentContext doNotUpdateStatsContext() {+ return new EnvironmentContext(+ Collections.singletonMap(StatsSetupConst.DO_NOT_UPDATE_STATS, StatsSetupConst.TRUE));+ }}diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShimV2.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShimV2.javadeleted file mode 100644index 97b7586d51..0000000000--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShimV2.java+++ /dev/null@@ -1,323 +0,0 @@-/*- * 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.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion.HIVE2;-import static org.apache.gravitino.hive.client.Util.updateConfigurationFromProperties;--import java.lang.reflect.Constructor;-import java.lang.reflect.Method;-import java.util.Collections;-import java.util.List;-import java.util.Properties;-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.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;--class HiveShimV2 extends HiveShim {-- HiveShimV2(Properties properties) {- super(HIVE2, properties);- }-- HiveShimV2(HiveClientClassLoader.HiveVersion version, Properties properties) {- super(version, properties);- }-- @Override- public IMetaStoreClient createMetaStoreClient(Properties properties) {- try {- ClassLoader classLoader = this.getClass().getClassLoader();- Class<?> clientClass = classLoader.loadClass(RETRYING_META_STORE_CLIENT_CLASS);- Class<?> hiveConfClass = classLoader.loadClass(HIVE_CONF_CLASS);- Class<?> confClass = classLoader.loadClass(CONFIGURATION_CLASS);-- Object conf = confClass.getDeclaredConstructor().newInstance();- updateConfigurationFromProperties(properties, (Configuration) conf);-- Constructor<?> hiveConfCtor = hiveConfClass.getConstructor(confClass, Class.class);- Object hiveConfInstance = hiveConfCtor.newInstance(conf, hiveConfClass);-- Method getProxyMethod = clientClass.getMethod(METHOD_GET_PROXY, hiveConfClass, boolean.class);- return (IMetaStoreClient) getProxyMethod.invoke(null, hiveConfInstance, false);-- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(- e, ExceptionTarget.other("MetaStoreClient"));- }- }-- @Override- public void createDatabase(HiveSchema database) {- try {- Database db = HiveDatabaseConverter.toHiveDb(database);- client.createDatabase(db);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(database.name()));- }- }-- @Override- public HiveSchema getDatabase(String catalogName, String databaseName) {- try {- Database db = client.getDatabase(databaseName);- return HiveDatabaseConverter.fromHiveDB(db);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public void alterDatabase(String catalogName, String databaseName, HiveSchema database) {- try {- Database db = HiveDatabaseConverter.toHiveDb(database);- client.alterDatabase(databaseName, db);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public void dropDatabase(String catalogName, String databaseName, boolean cascade) {- try {- client.dropDatabase(databaseName, false, false, cascade);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public List<String> getAllTables(String catalogName, String databaseName) {- try {- return client.getAllTables(databaseName);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public List<String> listTablesByType(- String catalogName, String databaseName, String tablePattern, String tableType) {- try {- return client.getTables(databaseName, tablePattern, TableType.valueOf(tableType));- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public List<String> listTableNamesByFilter(- String catalogName, String databaseName, String filter, short pageSize) {- try {- return client.listTableNamesByFilter(databaseName, filter, pageSize);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public HiveTable getTable(String catalogName, String databaseName, String tableName) {- try {- var tb = client.getTable(databaseName, tableName);- return HiveTableConverter.fromHiveTable(tb);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));- }- }-- @Override- public void alterTable(- String catalogName,- String databaseName,- String tableName,- HiveTable alteredHiveTable,- boolean skipStatsUpdate) {- try {- var tb = HiveTableConverter.toHiveTable(alteredHiveTable);- if (skipStatsUpdate) {- // Instruct the metastore not to recompute statistics for this alter, so it does not access- // the table's storage location. Hive 2.x has no catalog-aware alter, so the database name- // is used directly.- client.alter_table_with_environmentContext(- databaseName, tableName, tb, doNotUpdateStatsContext());- } else {- client.alter_table(databaseName, tableName, tb);- }- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));- }- }-- @Override- public void dropTable(- String catalogName,- String databaseName,- String tableName,- boolean deleteData,- boolean ifPurge) {- try {- client.dropTable(databaseName, tableName, deleteData, ifPurge);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));- }- }-- @Override- public void createTable(HiveTable hiveTable) {- try {- var tb = HiveTableConverter.toHiveTable(hiveTable);- client.createTable(tb);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(hiveTable.name()));- }- }-- @Override- public List<String> listPartitionNames(HiveTable table, short pageSize) {- try {- String databaseName = table.databaseName();- return client.listPartitionNames(databaseName, table.name(), pageSize);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(table.name()));- }- }-- @Override- public List<HivePartition> listPartitions(HiveTable table, short pageSize) {- try {- String databaseName = table.databaseName();- var partitions = client.listPartitions(databaseName, table.name(), pageSize);- return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(table.name()));- }- }-- @Override- public List<HivePartition> listPartitions(- HiveTable table, List<String> filterPartitionValueList, short pageSize) {- try {- String databaseName = table.databaseName();- var partitions =- client.listPartitions(databaseName, table.name(), filterPartitionValueList, pageSize);- return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(table.name()));- }- }-- @Override- public HivePartition getPartition(HiveTable table, String partitionName) {- try {- String databaseName = table.databaseName();- var partitionValues = HivePartition.extractPartitionValues(partitionName);- var partition = client.getPartition(databaseName, table.name(), partitionValues);- return HiveTableConverter.fromHivePartition(table, partition);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(- e, ExceptionTarget.partition(partitionName));- }- }-- @Override- public HivePartition addPartition(HiveTable table, HivePartition partition) {- try {- String databaseName = table.databaseName();- var hivePartition = HiveTableConverter.toHivePartition(databaseName, table, partition);- var addedPartition = client.add_partition(hivePartition);- return HiveTableConverter.fromHivePartition(table, addedPartition);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(- e, ExceptionTarget.partition(partition.name()));- }- }-- @Override- public void dropPartition(- String catalogName,- String databaseName,- String tableName,- String partitionName,- boolean deleteData) {- try {- var partitionValues = HivePartition.extractPartitionValues(partitionName);- client.dropPartition(databaseName, tableName, partitionValues, deleteData);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(- e, ExceptionTarget.partition(partitionName));- }- }-- @Override- public String getDelegationToken(String finalPrincipalName, String userName) {- try {- return client.getDelegationToken(finalPrincipalName, userName);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(- e, ExceptionTarget.other(finalPrincipalName));- }- }-- @Override- public List<HiveTable> getTableObjectsByName(- String catalogName, String databaseName, List<String> allTables) {- 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();- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.schema(databaseName));- }- }-- @Override- public List<String> getCatalogs() {- return List.of();- }-- @Override- public void createCatalog(String catalogName, String location, String description) {- throw new UnsupportedOperationException(- "Catalog creation is not supported in Hive 2.x. Please upgrade to Hive 3.x.");- }-- @Override- public void close() throws Exception {- client.close();- }-- /**- * Builds an {@link EnvironmentContext} that tells the metastore not to recompute table statistics- * during an alter, avoiding an access to the table's storage location.- *- * @return An environment context with {@code DO_NOT_UPDATE_STATS} set to {@code true}.- */- protected EnvironmentContext doNotUpdateStatsContext() {- return new EnvironmentContext(- Collections.singletonMap(StatsSetupConst.DO_NOT_UPDATE_STATS, StatsSetupConst.TRUE));- }-}diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShimV3.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShimV3.javadeleted file mode 100644index da6400991c..0000000000--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShimV3.java+++ /dev/null@@ -1,552 +0,0 @@-/*- * 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.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion.HIVE3;-import static org.apache.gravitino.hive.client.Util.updateConfigurationFromProperties;--import java.lang.reflect.Constructor;-import java.lang.reflect.Method;-import java.util.List;-import java.util.Properties;-import org.apache.commons.lang3.StringUtils;-import org.apache.commons.lang3.reflect.MethodUtils;-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.hadoop.conf.Configuration;-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.Table;--class HiveShimV3 extends HiveShimV2 {-- private static final String CATALOG_CLASS = "org.apache.hadoop.hive.metastore.api.Catalog";-- private final Method createDatabaseMethod;- private final Method getDatabaseMethod;- private final Method getAllDatabasesMethod;- private final Method alterDatabaseMethod;- private final Method dropDatabaseMethod;- private final Method getTableMethod;- private final Method createTableMethod;- private final Method alterTableMethod;- private final Method alterTableWithEnvironmentContextMethod;- private final Method dropTableMethod;- private final Method getAllTablesMethod;- private final Method getTablesByTypeMethod;- private final Method listTableNamesByFilterMethod;- private final Method listPartitionNamesMethod;- private final Method listPartitionsMethod;- private final Method listPartitionsWithFilterMethod;- private final Method getPartitionMethod;- private final Method addPartitionMethod;- private final Method dropPartitionMethod;- private final Method getTableObjectsByNameMethod;- private final Method databaseSetCatalogNameMethod;- private final Method getCatalogsMethod;- private final Method createCatalogMethod;-- private final Method tableSetCatalogNameMethod;- private final Method partitionSetCatalogNameMethod;- private final Method catalogSetDescriptionMethod;-- private final Class<?> catalogClass;- private final Constructor<?> catalogCreator;-- HiveShimV3(Properties properties) {- super(HIVE3, properties);- try {- // Hive3 database methods with catalog support- this.createDatabaseMethod =- IMetaStoreClient.class.getMethod("createDatabase", Database.class);- this.getDatabaseMethod =- IMetaStoreClient.class.getMethod("getDatabase", String.class, String.class);- this.getAllDatabasesMethod =- IMetaStoreClient.class.getMethod("getAllDatabases", String.class);- this.alterDatabaseMethod =- IMetaStoreClient.class.getMethod(- "alterDatabase", String.class, String.class, Database.class);- this.dropDatabaseMethod =- IMetaStoreClient.class.getMethod(- "dropDatabase",- String.class,- String.class,- boolean.class,- boolean.class,- boolean.class);-- // Hive3 table methods with catalog support- this.getTableMethod =- IMetaStoreClient.class.getMethod("getTable", String.class, String.class, String.class);- this.createTableMethod =- IMetaStoreClient.class.getMethod(- "createTable", org.apache.hadoop.hive.metastore.api.Table.class);- this.alterTableMethod =- IMetaStoreClient.class.getMethod(- "alter_table",- String.class,- String.class,- String.class,- org.apache.hadoop.hive.metastore.api.Table.class);- this.alterTableWithEnvironmentContextMethod =- IMetaStoreClient.class.getMethod(- "alter_table",- String.class,- String.class,- String.class,- Table.class,- EnvironmentContext.class);- this.dropTableMethod =- IMetaStoreClient.class.getMethod(- "dropTable", String.class, String.class, String.class, boolean.class, boolean.class);- this.getAllTablesMethod =- IMetaStoreClient.class.getMethod("getAllTables", String.class, String.class);- this.getTablesByTypeMethod =- IMetaStoreClient.class.getMethod(- "getTables", String.class, String.class, String.class, TableType.class);- this.listTableNamesByFilterMethod =- IMetaStoreClient.class.getMethod(- "listTableNamesByFilter", String.class, String.class, String.class, int.class);-- // Hive3 partition methods with catalog support (using int for pageSize)- this.listPartitionNamesMethod =- IMetaStoreClient.class.getMethod(- "listPartitionNames", String.class, String.class, String.class, int.class);- this.listPartitionsMethod =- IMetaStoreClient.class.getMethod(- "listPartitions", String.class, String.class, String.class, int.class);- this.listPartitionsWithFilterMethod =- IMetaStoreClient.class.getMethod(- "listPartitions", String.class, String.class, String.class, List.class, int.class);- this.getPartitionMethod =- IMetaStoreClient.class.getMethod(- "getPartition", String.class, String.class, String.class, List.class);- this.addPartitionMethod =- IMetaStoreClient.class.getMethod(- "add_partition", org.apache.hadoop.hive.metastore.api.Partition.class);- this.dropPartitionMethod =- IMetaStoreClient.class.getMethod(- "dropPartition", String.class, String.class, String.class, List.class, boolean.class);- // Hive3 getTableObjectsByName with catalog parameter- this.getTableObjectsByNameMethod =- IMetaStoreClient.class.getMethod(- "getTableObjectsByName", String.class, String.class, List.class);- this.getCatalogsMethod = IMetaStoreClient.class.getMethod("getCatalogs");-- this.catalogClass = this.getClass().getClassLoader().loadClass(CATALOG_CLASS);- this.catalogCreator = this.catalogClass.getDeclaredConstructor(String.class, String.class);- this.createCatalogMethod = IMetaStoreClient.class.getMethod("createCatalog", catalogClass);- this.catalogSetDescriptionMethod = catalogClass.getMethod("setDescription", String.class);-- // SetCatalogName methods for Hive3- this.databaseSetCatalogNameMethod =- MethodUtils.getAccessibleMethod(Database.class, "setCatalogName", String.class);- this.tableSetCatalogNameMethod =- MethodUtils.getAccessibleMethod(- org.apache.hadoop.hive.metastore.api.Table.class, "setCatName", String.class);- this.partitionSetCatalogNameMethod =- MethodUtils.getAccessibleMethod(- org.apache.hadoop.hive.metastore.api.Partition.class, "setCatName", String.class);-- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.other("HiveShimV3"));- }- }-- @Override- public IMetaStoreClient createMetaStoreClient(Properties properties) {- try {- ClassLoader classLoader = this.getClass().getClassLoader();- Class<?> clientClass = classLoader.loadClass(RETRYING_META_STORE_CLIENT_CLASS);- Class<?> confClass = classLoader.loadClass(CONFIGURATION_CLASS);-- Object conf = confClass.getDeclaredConstructor().newInstance();- updateConfigurationFromProperties(properties, (Configuration) conf);-- Method getProxyMethod = clientClass.getMethod(METHOD_GET_PROXY, confClass, boolean.class);- return (IMetaStoreClient) getProxyMethod.invoke(null, conf, false);-- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(- e, ExceptionTarget.other("MetaStoreClient"));- }- }-- @Override- public void createDatabase(HiveSchema database) {- Database db = HiveDatabaseConverter.toHiveDb(database);- String catalogName = database.catalogName();- invoke(ExceptionTarget.other(""), db, databaseSetCatalogNameMethod, catalogName);- invoke(ExceptionTarget.schema(database.name()), client, createDatabaseMethod, db);- }-- @Override- public List<String> getAllDatabases(String catalogName) {- return (List<String>)- invoke(ExceptionTarget.catalog(catalogName), client, getAllDatabasesMethod, catalogName);- }-- @Override- public HiveSchema getDatabase(String catalogName, String databaseName) {- Database db =- (Database)- invoke(- ExceptionTarget.schema(databaseName),- client,- getDatabaseMethod,- catalogName,- databaseName);- return HiveDatabaseConverter.fromHiveDB(db);- }-- @Override- public void alterDatabase(String catalogName, String databaseName, HiveSchema database) {- Database db = HiveDatabaseConverter.toHiveDb(database);- invoke(ExceptionTarget.other(""), db, databaseSetCatalogNameMethod, catalogName);- invoke(- ExceptionTarget.schema(databaseName),- client,- alterDatabaseMethod,- catalogName,- databaseName,- db);- }-- @Override- public void dropDatabase(String catalogName, String databaseName, boolean cascade) {- invoke(- ExceptionTarget.schema(databaseName),- client,- dropDatabaseMethod,- catalogName,- databaseName,- true,- false,- cascade);- }-- @Override- public List<String> getAllTables(String catalogName, String databaseName) {- return (List<String>)- invoke(- ExceptionTarget.schema(databaseName),- client,- getAllTablesMethod,- catalogName,- databaseName);- }-- @Override- public List<String> listTablesByType(- String catalogName, String databaseName, String tablePattern, String tableType) {- TableType hiveTableType = TableType.valueOf(tableType);- return (List<String>)- invoke(- ExceptionTarget.schema(databaseName),- client,- getTablesByTypeMethod,- catalogName,- databaseName,- tablePattern,- hiveTableType);- }-- @Override- public List<String> listTableNamesByFilter(- String catalogName, String databaseName, String filter, short pageSize) {- Object pageSizeArg = convertPageSize(listTableNamesByFilterMethod, 3, pageSize);- return (List<String>)- invoke(- ExceptionTarget.schema(databaseName),- client,- listTableNamesByFilterMethod,- catalogName,- databaseName,- filter,- pageSizeArg);- }-- @Override- public HiveTable getTable(String catalogName, String databaseName, String tableName) {- var tb =- (org.apache.hadoop.hive.metastore.api.Table)- invoke(- ExceptionTarget.table(tableName),- client,- getTableMethod,- catalogName,- databaseName,- tableName);- return HiveTableConverter.fromHiveTable(tb);- }-- @Override- public void alterTable(- String catalogName,- String databaseName,- String tableName,- HiveTable alteredHiveTable,- boolean skipStatsUpdate) {- var tb = HiveTableConverter.toHiveTable(alteredHiveTable);- invoke(ExceptionTarget.other(""), tb, tableSetCatalogNameMethod, catalogName);- if (skipStatsUpdate) {- // Instruct the metastore not to recompute statistics for this alter, so it does not access- // the table's storage location.- invoke(- ExceptionTarget.table(tableName),- client,- alterTableWithEnvironmentContextMethod,- catalogName,- databaseName,- tableName,- tb,- doNotUpdateStatsContext());- } else {- invoke(- ExceptionTarget.table(tableName),- client,- alterTableMethod,- catalogName,- databaseName,- tableName,- tb);- }- }-- @Override- public void dropTable(- String catalogName,- String databaseName,- String tableName,- boolean deleteData,- boolean ifPurge) {- invoke(- ExceptionTarget.table(tableName),- client,- dropTableMethod,- catalogName,- databaseName,- tableName,- deleteData,- ifPurge);- }-- @Override- public void createTable(HiveTable hiveTable) {- String catalogName = hiveTable.catalogName();- var tb = HiveTableConverter.toHiveTable(hiveTable);- invoke(ExceptionTarget.other(""), tb, tableSetCatalogNameMethod, catalogName);- invoke(ExceptionTarget.table(hiveTable.name()), client, createTableMethod, tb);- }-- @Override- public List<String> listPartitionNames(HiveTable table, short pageSize) {- String catalogName = table.catalogName();- String databaseName = table.databaseName();- Object pageSizeArg = convertPageSize(listPartitionNamesMethod, 3, pageSize);- return (List<String>)- invoke(- ExceptionTarget.table(table.name()),- client,- listPartitionNamesMethod,- catalogName,- databaseName,- table.name(),- pageSizeArg);- }-- @Override- public List<HivePartition> listPartitions(HiveTable table, short pageSize) {- String catalogName = table.catalogName();- String databaseName = table.databaseName();- Object pageSizeArg = convertPageSize(listPartitionsMethod, 3, pageSize);- var partitions =- (List<org.apache.hadoop.hive.metastore.api.Partition>)- invoke(- ExceptionTarget.table(table.name()),- client,- listPartitionsMethod,- catalogName,- databaseName,- table.name(),- pageSizeArg);- return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();- }-- @Override- public List<HivePartition> listPartitions(- HiveTable table, List<String> filterPartitionValueList, short pageSize) {- String catalogName = table.catalogName();- String databaseName = table.databaseName();- Object pageSizeArg = convertPageSize(listPartitionsWithFilterMethod, 4, pageSize);- var partitions =- (List<org.apache.hadoop.hive.metastore.api.Partition>)- invoke(- ExceptionTarget.table(table.name()),- client,- listPartitionsWithFilterMethod,- catalogName,- databaseName,- table.name(),- filterPartitionValueList,- pageSizeArg);- return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();- }-- @Override- public HivePartition getPartition(HiveTable table, String partitionName) {- String catalogName = table.catalogName();- String databaseName = table.databaseName();- var partitionValues = HivePartition.extractPartitionValues(partitionName);- var partition =- (org.apache.hadoop.hive.metastore.api.Partition)- invoke(- ExceptionTarget.partition(partitionName),- client,- getPartitionMethod,- catalogName,- databaseName,- table.name(),- partitionValues);- return HiveTableConverter.fromHivePartition(table, partition);- }-- @Override- public HivePartition addPartition(HiveTable table, HivePartition partition) {- String catalogName = table.catalogName();- String databaseName = table.databaseName();- var hivePartition = HiveTableConverter.toHivePartition(databaseName, table, partition);- invoke(ExceptionTarget.other(""), hivePartition, partitionSetCatalogNameMethod, catalogName);- var addedPartition =- (org.apache.hadoop.hive.metastore.api.Partition)- invoke(- ExceptionTarget.partition(partition.name()),- client,- addPartitionMethod,- hivePartition);- return HiveTableConverter.fromHivePartition(table, addedPartition);- }-- @Override- public void dropPartition(- String catalogName,- String databaseName,- String tableName,- String partitionName,- boolean deleteData) {- var partitionValues = HivePartition.extractPartitionValues(partitionName);- invoke(- ExceptionTarget.partition(partitionName),- client,- dropPartitionMethod,- catalogName,- databaseName,- tableName,- partitionValues,- deleteData);- }-- @Override- public List<HiveTable> getTableObjectsByName(- String catalogName, String databaseName, List<String> allTables) {- var tables =- (List<Table>)- invoke(- ExceptionTarget.schema(databaseName),- client,- getTableObjectsByNameMethod,- catalogName,- databaseName,- allTables);- return tables.stream().map(HiveTableConverter::fromHiveTable).toList();- }-- @Override- public List<String> getCatalogs() {- return (List<String>) invoke(ExceptionTarget.other(""), client, getCatalogsMethod);- }-- @Override- public void createCatalog(String catalogName, String location, String description) {- Object catalog =- invoke(ExceptionTarget.other(catalogName), catalogCreator, catalogName, location);- if (StringUtils.isNotBlank(description)) {- invoke(ExceptionTarget.other(catalogName), catalog, catalogSetDescriptionMethod, description);- }- invoke(ExceptionTarget.catalog(catalogName), client, createCatalogMethod, catalog);- }-- /**- * Invokes a method on an object and converts any exception to a Gravitino exception.- *- * @param target Hive object info used in error messages and exception mapping- * @param object The object to invoke the method on- * @param method The method to invoke- * @param args The arguments to pass to the method- * @return The result of the method invocation- */- private Object invoke(ExceptionTarget target, Object object, Method method, Object... args) {- try {- return method.invoke(object, args);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, target);- }- }-- /**- * Creates an object using a constructor and converts any exception to a Gravitino exception.- *- * @param target Hive object info used in error messages and exception mapping- * @param constructor The constructor to use for creating the object- * @param args The arguments to pass to the constructor- * @return The created object- */- private Object invoke(ExceptionTarget target, Constructor<?> constructor, Object... args) {- try {- return constructor.newInstance(args);- } catch (Exception e) {- throw HiveExceptionConverter.toGravitinoException(e, target);- }- }-- /**- * Converts pageSize from short to int if the method parameter expects int type.- *- * @param method The method to check parameter types- * @param paramIndex The index of the pageSize parameter- * @param pageSize The pageSize value as short- * @return The pageSize as Object (short or int)- */- private Object convertPageSize(Method method, int paramIndex, short pageSize) {- if (method.getParameterTypes()[paramIndex] == int.class) {- return (int) pageSize;- }- return pageSize;- }-- @Override- public void close() throws Exception {- client.close();- }-}diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveColumnDefaultValueConverter.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveColumnDefaultValueConverter.javanew file mode 100644index 0000000000..fbbba759e9--- /dev/null+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/converter/HiveColumnDefaultValueConverter.java@@ -0,0 +1,216 @@+/*+ * 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.converter;++import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;++import java.time.LocalDate;+import java.time.LocalDateTime;+import java.time.format.DateTimeFormatter;+import java.time.format.DateTimeFormatterBuilder;+import java.time.format.DateTimeParseException;+import java.time.temporal.ChronoField;+import org.apache.gravitino.rel.expressions.Expression;+import org.apache.gravitino.rel.expressions.FunctionExpression;+import org.apache.gravitino.rel.expressions.UnparsedExpression;+import org.apache.gravitino.rel.expressions.literals.Literal;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.types.Decimal;+import org.apache.gravitino.rel.types.Type;+import org.apache.gravitino.rel.types.Types;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Converts column default values between Gravitino {@link Expression}s and the SQL expression+ * strings stored by the Hive Metastore in {@code SQLDefaultConstraint}. Literals and zero-argument+ * functions are modeled; any other expression is carried verbatim as an {@link UnparsedExpression}+ * so it round-trips unchanged.+ */+public class HiveColumnDefaultValueConverter {++ private static final Logger LOG = LoggerFactory.getLogger(HiveColumnDefaultValueConverter.class);+ private static final String NULL = "NULL";+ private static final DateTimeFormatter DATE_TIME_FORMATTER =+ new DateTimeFormatterBuilder()+ .appendPattern("yyyy-MM-dd HH:mm:ss")+ .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)+ .toFormatter();++ private HiveColumnDefaultValueConverter() {}++ /**+ * Renders a Gravitino default value as a Hive SQL expression string.+ *+ * @param defaultValue The Gravitino default value expression.+ * @return The Hive SQL expression, or {@code null} when no default value is set.+ */+ public static String fromGravitino(Expression defaultValue) {+ if (defaultValue == null || DEFAULT_VALUE_NOT_SET.equals(defaultValue)) {+ return null;+ }++ if (defaultValue instanceof UnparsedExpression) {+ return ((UnparsedExpression) defaultValue).unparsedExpression();+ }++ if (defaultValue instanceof FunctionExpression) {+ FunctionExpression function = (FunctionExpression) defaultValue;+ if (function.arguments().length == 0) {+ // Hive requires parentheses for functions such as CURRENT_TIMESTAMP(); the trailing "()"+ // is also what toGravitino keys on to recognize a function+ return function.functionName().toUpperCase() + "()";+ }+ throw new IllegalArgumentException(+ "Hive catalog does not support function default value with arguments: " + defaultValue);+ }++ if (defaultValue instanceof Literal) {+ Literal<?> literal = (Literal<?>) defaultValue;+ Type type = literal.dataType();+ if (literal.value() == null || type.name() == Type.Name.NULL) {+ return NULL;+ }+ if (type instanceof Type.NumericType || type instanceof Types.BooleanType) {+ return literal.value().toString();+ }+ if (type instanceof Types.TimestampType && literal.value() instanceof LocalDateTime) {+ return quote(((LocalDateTime) literal.value()).format(DATE_TIME_FORMATTER));+ }+ if (type instanceof Types.StringType+ || type instanceof Types.VarCharType+ || type instanceof Types.FixedCharType+ || type instanceof Types.DateType) {+ return quote(literal.value().toString());+ }+ throw new IllegalArgumentException(+ "Hive catalog does not support column default value literal of type "+ + type+ + ": "+ + defaultValue);+ }++ throw new IllegalArgumentException("Not a supported column default value: " + defaultValue);+ }++ /**+ * Parses a Hive SQL default value expression into a Gravitino {@link Expression}.+ *+ * @param type The Gravitino type of the column that owns the default value.+ * @param defaultValue The Hive SQL expression string.+ * @return The Gravitino default value expression.+ */+ public static Expression toGravitino(Type type, String defaultValue) {+ return toGravitino(type, defaultValue, null);+ }++ /**+ * Parses a Hive SQL default value expression into a Gravitino {@link Expression}.+ *+ * @param type The Gravitino type of the column that owns the default value.+ * @param defaultValue The Hive SQL expression string.+ * @param columnName The name of the column that owns the default value, used only to give context+ * in log messages; may be {@code null} when unknown.+ * @return The Gravitino default value expression.+ */+ public static Expression toGravitino(Type type, String defaultValue, String columnName) {+ if (defaultValue == null) {+ return DEFAULT_VALUE_NOT_SET;+ }+ String value = defaultValue.trim();+ if (value.equalsIgnoreCase(NULL)) {+ return Literals.NULL;+ }+ if (value.endsWith("()") && value.length() > 2) {+ return FunctionExpression.of(value.substring(0, value.length() - 2).toLowerCase());+ }+ boolean quoted = value.length() >= 2 && value.startsWith("'") && value.endsWith("'");+ if (quoted) {+ value = unquote(value);+ }++ Type.Name typeName = type.name();+ try {+ switch (typeName) {+ case BOOLEAN:+ // Boolean.valueOf() maps anything but "true" to false, so only accept the two literals+ if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {+ return Literals.booleanLiteral(Boolean.valueOf(value));+ }+ break;+ case BYTE:+ return Literals.byteLiteral(Byte.valueOf(value));+ case SHORT:+ return Literals.shortLiteral(Short.valueOf(value));+ case INTEGER:+ return Literals.integerLiteral(Integer.valueOf(value));+ case LONG:+ return Literals.longLiteral(Long.valueOf(value));+ case FLOAT:+ return Literals.floatLiteral(Float.valueOf(value));+ case DOUBLE:+ return Literals.doubleLiteral(Double.valueOf(value));+ case DECIMAL:+ Types.DecimalType decimalType = (Types.DecimalType) type;+ return Literals.decimalLiteral(+ Decimal.of(value, decimalType.precision(), decimalType.scale()));+ case DATE:+ return Literals.dateLiteral(LocalDate.parse(value));+ case TIMESTAMP:+ return Literals.timestampLiteral(LocalDateTime.parse(value, DATE_TIME_FORMATTER));+ case STRING:+ case VARCHAR:+ case FIXEDCHAR:+ // An unquoted value is an expression such as CAST(...) rather than a string literal+ if (quoted) {+ return Literals.of(value, type);+ }+ break;+ default:+ break;+ }+ } catch (IllegalArgumentException | DateTimeParseException e) {+ // The metastore stores arbitrary SQL text; whatever cannot be modeled as a literal of the+ // column type is deliberately kept verbatim instead of failing the table load.+ LOG.warn(+ "Cannot parse Hive default value '{}' as a literal of type {} for column '{}'; keeping "+ + "it as an unparsed expression",+ defaultValue,+ type,+ columnName == null ? "<unknown>" : columnName,+ e);+ }+ return UnparsedExpression.of(defaultValue);+ }++ private static String quote(String value) {+ // Hive 3 evaluates default values read directly from the metastore with backslash escaping.+ // SQL-standard doubled quotes are accepted by the DDL parser, but storing them in HMS causes+ // an omitted-column INSERT to lose the quote (for example, "it's" becomes "its").+ return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'";+ }++ private static String unquote(String quoted) {+ return quoted+ .substring(1, quoted.length() - 1)+ .replace("''", "'")+ .replace("\\'", "'")+ .replace("\\\\", "\\");+ }+}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.javaindex efe8f3bc58..25b5da049a 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@@ -68,6 +68,21 @@ import org.apache.hadoop.hive.metastore.api.StorageDescriptor;public class HiveTableConverter {public static HiveTable fromHiveTable(org.apache.hadoop.hive.metastore.api.Table table) {+ return fromHiveTable(table, Collections.emptySet(), Collections.emptyMap());+ }++ /**+ * Converts a Hive metastore table together with its column constraints.+ *+ * @param table The Hive metastore table.+ * @param notNullColumns Names of the columns that carry a NOT NULL constraint.+ * @param defaultValues Column name to Hive SQL default value expression.+ * @return The converted {@link HiveTable}.+ */+ public static HiveTable fromHiveTable(+ org.apache.hadoop.hive.metastore.api.Table table,+ Set<String> notNullColumns,+ Map<String, String> defaultValues) {Preconditions.checkArgument(table != null, "Table cannot be null");AuditInfo auditInfo = HiveTableConverter.getAuditInfo(table);@@ -75,7 +90,7 @@ public class HiveTableConverter {SortOrder[] sortOrders = HiveTableConverter.getSortOrders(table);- Column[] columns = HiveTableConverter.getColumns(table);+ Column[] columns = HiveTableConverter.getColumns(table, notNullColumns, defaultValues);Transform[] partitioning = HiveTableConverter.getPartitioning(table);@@ -343,6 +358,22 @@ public class HiveTableConverter {}public static Column[] getColumns(org.apache.hadoop.hive.metastore.api.Table table) {+ return getColumns(table, Collections.emptySet(), Collections.emptyMap());+ }++ /**+ * Converts the storage and partition columns of a Hive metastore table, applying the given column+ * constraints.+ *+ * @param table The Hive metastore table.+ * @param notNullColumns Names of the columns that carry a NOT NULL constraint.+ * @param defaultValues Column name to Hive SQL default value expression.+ * @return The converted columns, storage columns first followed by partition columns.+ */+ public static Column[] getColumns(+ org.apache.hadoop.hive.metastore.api.Table table,+ Set<String> notNullColumns,+ Map<String, String> defaultValues) {StorageDescriptor sd = table.getSd();List<FieldSchema> storageColumns =sd == null || sd.getCols() == null ? Collections.emptyList() : sd.getCols();@@ -359,7 +390,9 @@ public class HiveTableConverter {buildColumn(f.getName(),HiveDataTypeConverter.CONVERTER.toGravitino(f.getType()),- f.getComment())),+ f.getComment(),+ notNullColumns,+ defaultValues)),partitionKeys.stream()// Filter out partition keys that already exist in sd.getCols().filter(p -> !columnNames.contains(p.getName()))@@ -368,13 +401,25 @@ public class HiveTableConverter {buildColumn(p.getName(),HiveDataTypeConverter.CONVERTER.toGravitino(p.getType()),- p.getComment())))+ p.getComment(),+ notNullColumns,+ defaultValues))).toArray(Column[]::new);}- private static Column buildColumn(String name, Type type, String comment) {+ private static Column buildColumn(+ String name,+ Type type,+ String comment,+ Set<String> notNullColumns,+ Map<String, String> defaultValues) {HiveColumn.Builder builder =- HiveColumn.builder().withName(name).withType(type).withNullable(true);+ HiveColumn.builder()+ .withName(name)+ .withType(type)+ .withNullable(!notNullColumns.contains(name))+ .withDefaultValue(+ HiveColumnDefaultValueConverter.toGravitino(type, defaultValues.get(name), name));if (comment != null) {builder.withComment(comment);}diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimAlterTable.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimAlterTable.javaindex 251cccd450..32134ad30a 100644--- a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimAlterTable.java+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimAlterTable.java@@ -53,13 +53,16 @@ class TestHiveShimAlterTable {private static final String TABLE = "tbl";/**- * A {@link HiveShimV2} that uses a mocked metastore client instead of connecting to a real Hive+ * A {@link HiveShim} that uses a mocked metastore client instead of connecting to a real Hive* Metastore. The mock is created inside {@link #createMetaStoreClient(Properties)} because that* method is invoked from the superclass constructor, before any subclass field is initialized.+ * {@link HiveShim} itself carries the Hive 2.x-compatible {@code alterTable} behavior that every+ * Hive version starts from, so testing it directly covers both the Hive 2.x shim (a trivial+ * subclass with no overrides) and the baseline that the Hive 3.x shim builds on.*/- private static class MockHiveShimV2 extends HiveShimV2 {- MockHiveShimV2() {- super(new Properties());+ private static class MockHiveShim extends HiveShim {+ MockHiveShim() {+ super(HiveClientClassLoader.HiveVersion.HIVE2, new Properties());}@Override@@ -88,7 +91,7 @@ class TestHiveShimAlterTable {@Testvoid testSkipStatsUpdateSendsDoNotUpdateStats() throws Exception {- MockHiveShimV2 shim = new MockHiveShimV2();+ MockHiveShim shim = new MockHiveShim();IMetaStoreClient client = shim.metaStoreClient();shim.alterTable(CATALOG, DB, TABLE, testTable(), true);@@ -104,7 +107,7 @@ class TestHiveShimAlterTable {@Testvoid testDefaultUsesPlainAlter() throws Exception {- MockHiveShimV2 shim = new MockHiveShimV2();+ MockHiveShim shim = new MockHiveShim();IMetaStoreClient client = shim.metaStoreClient();shim.alterTable(CATALOG, DB, TABLE, testTable(), false);diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveColumnDefaultValueConverter.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveColumnDefaultValueConverter.javanew file mode 100644index 0000000000..5321683d5a--- /dev/null+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveColumnDefaultValueConverter.java@@ -0,0 +1,174 @@+/*+ * 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.converter;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import java.time.LocalDate;+import java.time.LocalDateTime;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.Expression;+import org.apache.gravitino.rel.expressions.FunctionExpression;+import org.apache.gravitino.rel.expressions.UnparsedExpression;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.types.Decimal;+import org.apache.gravitino.rel.types.Type;+import org.apache.gravitino.rel.types.Types;+import org.junit.jupiter.api.Test;++public class TestHiveColumnDefaultValueConverter {++ @Test+ public void testFromGravitino() {+ assertNull(HiveColumnDefaultValueConverter.fromGravitino(null));+ assertNull(HiveColumnDefaultValueConverter.fromGravitino(Column.DEFAULT_VALUE_NOT_SET));+ assertEquals("NULL", HiveColumnDefaultValueConverter.fromGravitino(Literals.NULL));+ assertEquals(+ "NULL",+ HiveColumnDefaultValueConverter.fromGravitino(Literals.of("NULL", Types.NullType.get())));+ assertEquals("42", HiveColumnDefaultValueConverter.fromGravitino(Literals.integerLiteral(42)));+ assertEquals("1.5", HiveColumnDefaultValueConverter.fromGravitino(Literals.doubleLiteral(1.5)));+ assertEquals(+ "true", HiveColumnDefaultValueConverter.fromGravitino(Literals.booleanLiteral(true)));+ assertEquals(+ "'abc'", HiveColumnDefaultValueConverter.fromGravitino(Literals.stringLiteral("abc")));+ assertEquals(+ "'it\\'s'", HiveColumnDefaultValueConverter.fromGravitino(Literals.stringLiteral("it's")));+ assertEquals(+ "'2024-01-02'",+ HiveColumnDefaultValueConverter.fromGravitino(+ Literals.dateLiteral(LocalDate.of(2024, 1, 2))));+ assertEquals(+ "'2024-01-02 03:04:05'",+ HiveColumnDefaultValueConverter.fromGravitino(+ Literals.timestampLiteral(LocalDateTime.of(2024, 1, 2, 3, 4, 5))));+ assertEquals(+ "CURRENT_TIMESTAMP()",+ HiveColumnDefaultValueConverter.fromGravitino(Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMP));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ HiveColumnDefaultValueConverter.fromGravitino(+ FunctionExpression.of("substr", Literals.stringLiteral("abc"))));+ // Unparsed expressions are written back verbatim so a loaded table can be altered as-is+ assertEquals(+ "CAST('x' AS STRING)",+ HiveColumnDefaultValueConverter.fromGravitino(+ UnparsedExpression.of("CAST('x' AS STRING)")));+ // Literal types with no defined Hive SQL rendering must not be silently serialized via+ // Object#toString()+ assertThrows(+ IllegalArgumentException.class,+ () ->+ HiveColumnDefaultValueConverter.fromGravitino(+ Literals.of(new byte[] {1, 2, 3}, Types.BinaryType.get())));+ }++ @Test+ public void testToGravitino() {+ assertEquals(+ Column.DEFAULT_VALUE_NOT_SET,+ HiveColumnDefaultValueConverter.toGravitino(Types.IntegerType.get(), null));+ assertEquals(+ Literals.NULL,+ HiveColumnDefaultValueConverter.toGravitino(Types.IntegerType.get(), "null"));+ assertEquals(+ Literals.integerLiteral(42),+ HiveColumnDefaultValueConverter.toGravitino(Types.IntegerType.get(), "42"));+ assertEquals(+ Literals.longLiteral(42L),+ HiveColumnDefaultValueConverter.toGravitino(Types.LongType.get(), "42"));+ assertEquals(+ Literals.booleanLiteral(true),+ HiveColumnDefaultValueConverter.toGravitino(Types.BooleanType.get(), "true"));+ assertEquals(+ Literals.booleanLiteral(false),+ HiveColumnDefaultValueConverter.toGravitino(Types.BooleanType.get(), " FALSE "));+ assertEquals(+ Literals.integerLiteral(-7),+ HiveColumnDefaultValueConverter.toGravitino(Types.IntegerType.get(), "-7"));+ assertEquals(+ Literals.timestampLiteral(LocalDateTime.of(2024, 1, 2, 3, 4, 5, 123_000_000)),+ HiveColumnDefaultValueConverter.toGravitino(+ Types.TimestampType.withoutTimeZone(), "'2024-01-02 03:04:05.123'"));+ // A quoted NULL is the string "NULL", not the NULL literal+ assertEquals(+ Literals.stringLiteral("NULL"),+ HiveColumnDefaultValueConverter.toGravitino(Types.StringType.get(), "'NULL'"));+ assertEquals(+ Literals.decimalLiteral(Decimal.of("1.50", 10, 2)),+ HiveColumnDefaultValueConverter.toGravitino(Types.DecimalType.of(10, 2), "1.5"));+ assertEquals(+ Literals.stringLiteral("it's"),+ HiveColumnDefaultValueConverter.toGravitino(Types.StringType.get(), "'it\\'s'"));+ assertEquals(+ Literals.stringLiteral("it's"),+ HiveColumnDefaultValueConverter.toGravitino(Types.StringType.get(), "'it''s'"));+ assertEquals(+ Literals.varcharLiteral(10, "abc"),+ HiveColumnDefaultValueConverter.toGravitino(Types.VarCharType.of(10), "'abc'"));+ assertEquals(+ Literals.dateLiteral(LocalDate.of(2024, 1, 2)),+ HiveColumnDefaultValueConverter.toGravitino(Types.DateType.get(), "'2024-01-02'"));+ assertEquals(+ Literals.timestampLiteral(LocalDateTime.of(2024, 1, 2, 3, 4, 5)),+ HiveColumnDefaultValueConverter.toGravitino(+ Types.TimestampType.withoutTimeZone(), "'2024-01-02 03:04:05'"));+ assertEquals(+ Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMP,+ HiveColumnDefaultValueConverter.toGravitino(+ Types.TimestampType.withoutTimeZone(), "CURRENT_TIMESTAMP()"));+ // Values that cannot be parsed for the column type are kept verbatim+ Expression unparsed =+ HiveColumnDefaultValueConverter.toGravitino(Types.IntegerType.get(), "abc");+ assertEquals(UnparsedExpression.of("abc"), unparsed);+ assertEquals(+ UnparsedExpression.of("'x'"),+ HiveColumnDefaultValueConverter.toGravitino(Types.BinaryType.get(), "'x'"));+ // Unquoted text on a string column and non true/false text on a boolean column are+ // expressions, not literals+ assertEquals(+ UnparsedExpression.of("CAST('x' AS STRING)"),+ HiveColumnDefaultValueConverter.toGravitino(Types.StringType.get(), "CAST('x' AS STRING)"));+ assertEquals(+ UnparsedExpression.of("CURRENT_USER"),+ HiveColumnDefaultValueConverter.toGravitino(Types.StringType.get(), "CURRENT_USER"));+ assertEquals(+ UnparsedExpression.of("CAST(1 AS BOOLEAN)"),+ HiveColumnDefaultValueConverter.toGravitino(Types.BooleanType.get(), "CAST(1 AS BOOLEAN)"));+ }++ @Test+ public void testRoundTrip() {+ assertRoundTrip(Types.StringType.get(), Literals.NULL);+ assertRoundTrip(Types.IntegerType.get(), Literals.integerLiteral(7));+ assertRoundTrip(Types.StringType.get(), Literals.stringLiteral("a'b\\c"));+ assertRoundTrip(Types.DateType.get(), Literals.dateLiteral(LocalDate.of(2024, 1, 2)));+ assertRoundTrip(+ Types.TimestampType.withoutTimeZone(), Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMP);+ assertRoundTrip(Types.StringType.get(), UnparsedExpression.of("CAST('x' AS STRING)"));+ }++ private void assertRoundTrip(Type type, Expression value) {+ String hive = HiveColumnDefaultValueConverter.fromGravitino(value);+ assertEquals(value, HiveColumnDefaultValueConverter.toGravitino(type, hive));+ }+}diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveTableConverter.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveTableConverter.javaindex a811bd835b..952b9674d9 100644--- a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveTableConverter.java+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/converter/TestHiveTableConverter.java@@ -21,8 +21,12 @@ package org.apache.gravitino.hive.converter;import static org.apache.gravitino.catalog.hive.HiveConstants.TABLE_TYPE;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import com.google.common.collect.ImmutableMap;+import com.google.common.collect.ImmutableSet;import java.time.Instant;import java.util.Arrays;import java.util.HashMap;@@ -31,6 +35,7 @@ import java.util.Map;import org.apache.gravitino.hive.HiveTable;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.literals.Literals;import org.apache.gravitino.rel.types.Types;import org.apache.hadoop.hive.metastore.TableType;import org.apache.hadoop.hive.metastore.api.FieldSchema;@@ -230,4 +235,31 @@ public class TestHiveTableConverter {assertEquals(0, hiveTable.columns().length);assertEquals("SELECT `1`", hiveTable.viewOriginalText());}++ @Test+ public void testGetColumnsWithConstraints() {+ Table table = new Table();+ StorageDescriptor sd = new StorageDescriptor();+ sd.setCols(+ Arrays.asList(+ new FieldSchema("id", "int", null),+ new FieldSchema("name", "string", null),+ new FieldSchema("age", "int", null)));+ table.setSd(sd);+ table.setPartitionKeys(Arrays.asList(new FieldSchema("dt", "string", null)));++ Column[] columns =+ HiveTableConverter.getColumns(+ table, ImmutableSet.of("id", "dt"), ImmutableMap.of("name", "'n/a'", "age", "18"));++ assertEquals(4, columns.length);+ assertFalse(columns[0].nullable());+ assertEquals(Column.DEFAULT_VALUE_NOT_SET, columns[0].defaultValue());+ assertTrue(columns[1].nullable());+ assertEquals(Literals.stringLiteral("n/a"), columns[1].defaultValue());+ assertTrue(columns[2].nullable());+ assertEquals(Literals.integerLiteral(18), columns[2].defaultValue());+ assertFalse(columns[3].nullable());+ assertEquals(Column.DEFAULT_VALUE_NOT_SET, columns[3].defaultValue());+ }}diff --git a/catalogs/hive-metastore2-libs/build.gradle.kts b/catalogs/hive-metastore2-libs/build.gradle.ktsindex d2a01d348f..0c151bef26 100644--- a/catalogs/hive-metastore2-libs/build.gradle.kts+++ b/catalogs/hive-metastore2-libs/build.gradle.kts@@ -29,6 +29,10 @@ plugins {// Guava and Logback are excluded because they are provided by the Gravitino runtime classpath.dependencies {+ // Only needed to compile HiveShimV2 against the shared HiveShim base class; compileOnly keeps+ // hive-metastore-common's own classes out of the shaded runtime jar produced by copyDepends.+ compileOnly(project(":catalogs:hive-metastore-common"))+// Force upgrades for outdated transitive dependencies pulled by Hive Metastoreconstraints {implementation(libs.thrift)diff --git a/catalogs/hive-metastore2-libs/src/main/java/org/apache/gravitino/hive/client/hive2/HiveShimV2.java b/catalogs/hive-metastore2-libs/src/main/java/org/apache/gravitino/hive/client/hive2/HiveShimV2.javanew file mode 100644index 0000000000..f205881b4c--- /dev/null+++ b/catalogs/hive-metastore2-libs/src/main/java/org/apache/gravitino/hive/client/hive2/HiveShimV2.java@@ -0,0 +1,34 @@+/*+ * 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.hive2;++import java.util.Properties;+import org.apache.gravitino.hive.client.HiveClientClassLoader;+import org.apache.gravitino.hive.client.HiveShim;++/**+ * Hive 2.x metastore shim. Hive 2.x has no multi-catalog support and no column constraints, so this+ * class adds nothing on top of {@link HiveShim}'s baseline behavior.+ */+public class HiveShimV2 extends HiveShim {++ public HiveShimV2(Properties properties) {+ super(HiveClientClassLoader.HiveVersion.HIVE2, properties);+ }+}diff --git a/catalogs/hive-metastore3-libs/build.gradle.kts b/catalogs/hive-metastore3-libs/build.gradle.ktsindex 1c30bba7b4..6e7f9c79af 100644--- a/catalogs/hive-metastore3-libs/build.gradle.kts+++ b/catalogs/hive-metastore3-libs/build.gradle.kts@@ -29,6 +29,15 @@ plugins {// Guava and Logback are excluded because they are provided by the Gravitino runtime classpath.dependencies {+ // Only needed to compile HiveShimV3 against the shared HiveShim base class, Gravitino's own+ // Column/HiveTable types (HiveTable extends core's BaseTable) and RandomNameUtils; compileOnly+ // keeps these classes out of the shaded runtime jar produced by copyDepends.+ compileOnly(project(":catalogs:hive-metastore-common"))+ compileOnly(project(":api"))+ compileOnly(project(":common"))+ compileOnly(project(":core"))+ compileOnly(libs.slf4j.api)+// Force upgrades for outdated transitive dependencies pulled by Hive Metastoreconstraints {implementation(libs.thrift)@@ -81,6 +90,22 @@ dependencies {exclude(group = "org.openjdk.jol")exclude(group = "org.slf4j")}++ // compileOnly is not inherited by the test compile classpath, so the same set of Gravitino+ // modules used to compile HiveShimV3 needs to be redeclared for the test sources.+ testImplementation(project(":catalogs:hive-metastore-common"))+ testImplementation(project(":catalogs:catalog-common"))+ testImplementation(project(":api"))+ testImplementation(project(":common"))+ testImplementation(project(":core"))+ testImplementation(libs.slf4j.api)+ testImplementation(libs.junit.jupiter.api)+ testImplementation(libs.mockito.core)+ testRuntimeOnly(libs.junit.jupiter.engine)+}++tasks.withType<Test>().configureEach {+ useJUnitPlatform()}tasks {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.javanew file mode 100644index 0000000000..dfc76ca5aa--- /dev/null+++ b/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java@@ -0,0 +1,589 @@+/*+ * 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.hive3;++import static org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion.HIVE3;+import static org.apache.gravitino.hive.client.Util.updateConfigurationFromProperties;++import java.util.ArrayList;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Properties;+import java.util.Set;+import org.apache.commons.lang3.StringUtils;+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;+import org.apache.gravitino.hive.client.HiveExceptionConverter.ExceptionTarget;+import org.apache.gravitino.hive.client.HiveShim;+import org.apache.gravitino.hive.converter.HiveColumnDefaultValueConverter;+import org.apache.gravitino.hive.converter.HiveDatabaseConverter;+import org.apache.gravitino.hive.converter.HiveTableConverter;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.utils.RandomNameUtils;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.hive.metastore.IMetaStoreClient;+import org.apache.hadoop.hive.metastore.RetryingMetaStoreClient;+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.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.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Hive 3.x metastore shim. Hive 3.x supports multiple metastore catalogs and NOT NULL / DEFAULT+ * column constraints, so every operation below is catalog-aware and column constraints are kept in+ * sync with the metastore.+ */+public class HiveShimV3 extends HiveShim {++ private static final Logger LOG = LoggerFactory.getLogger(HiveShimV3.class);++ // Keeps generated constraint names well within the metastore's 400 character limit+ private static final int MAX_CONSTRAINT_PREFIX = 128;+ // Constraints are recorded for metadata only: enabled and not validated against existing data.+ // rely_cstr is deliberately false: Gravitino never validates existing data against newly added+ // constraints, so telling the query optimizer to rely on them could produce incorrect results.+ private static final boolean CONSTRAINT_ENABLE = true;+ private static final boolean CONSTRAINT_VALIDATE = false;+ private static final boolean CONSTRAINT_RELY = false;++ public HiveShimV3(Properties properties) {+ super(HIVE3, properties);+ }++ @Override+ public IMetaStoreClient createMetaStoreClient(Properties properties) {+ try {+ Configuration conf = new Configuration();+ updateConfigurationFromProperties(properties, conf);+ return RetryingMetaStoreClient.getProxy(conf, false);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(+ e, ExceptionTarget.other("MetaStoreClient"));+ }+ }++ @Override+ public void createDatabase(HiveSchema database) {+ Database db = HiveDatabaseConverter.toHiveDb(database);+ db.setCatalogName(database.catalogName());+ invoke(ExceptionTarget.schema(database.name()), () -> client.createDatabase(db));+ }++ @Override+ public List<String> getAllDatabases(String catalogName) {+ return invoke(ExceptionTarget.catalog(catalogName), () -> client.getAllDatabases(catalogName));+ }++ @Override+ public HiveSchema getDatabase(String catalogName, String databaseName) {+ Database db =+ invoke(+ ExceptionTarget.schema(databaseName),+ () -> client.getDatabase(catalogName, databaseName));+ return HiveDatabaseConverter.fromHiveDB(db);+ }++ @Override+ public void alterDatabase(String catalogName, String databaseName, HiveSchema database) {+ Database db = HiveDatabaseConverter.toHiveDb(database);+ db.setCatalogName(catalogName);+ invoke(+ ExceptionTarget.schema(databaseName),+ () -> client.alterDatabase(catalogName, databaseName, db));+ }++ @Override+ public void dropDatabase(String catalogName, String databaseName, boolean cascade) {+ invoke(+ ExceptionTarget.schema(databaseName),+ () -> client.dropDatabase(catalogName, databaseName, true, false, cascade));+ }++ @Override+ public List<String> getAllTables(String catalogName, String databaseName) {+ return invoke(+ ExceptionTarget.schema(databaseName), () -> client.getAllTables(catalogName, databaseName));+ }++ @Override+ public List<String> listTablesByType(+ String catalogName, String databaseName, String tablePattern, String tableType) {+ TableType hiveTableType = TableType.valueOf(tableType);+ return invoke(+ ExceptionTarget.schema(databaseName),+ () -> client.getTables(catalogName, databaseName, tablePattern, hiveTableType));+ }++ @Override+ public List<String> listTableNamesByFilter(+ String catalogName, String databaseName, String filter, short pageSize) {+ return invoke(+ ExceptionTarget.schema(databaseName),+ () -> client.listTableNamesByFilter(catalogName, databaseName, filter, pageSize));+ }++ @Override+ public HiveTable getTable(String catalogName, String databaseName, String tableName) {+ Table tb =+ invoke(+ ExceptionTarget.table(tableName),+ () -> client.getTable(catalogName, databaseName, tableName));+ if (TableType.VIRTUAL_VIEW.name().equalsIgnoreCase(tb.getTableType())) {+ return HiveTableConverter.fromHiveTable(tb);+ }+ ColumnConstraints constraints = loadColumnConstraints(catalogName, databaseName, tableName);+ return HiveTableConverter.fromHiveTable(+ tb, notNullColumns(constraints), defaultValues(constraints));+ }++ @Override+ public void alterTable(+ String catalogName,+ String databaseName,+ String tableName,+ HiveTable alteredHiveTable,+ boolean skipStatsUpdate) {+ Table tb = HiveTableConverter.toHiveTable(alteredHiveTable);+ tb.setCatName(catalogName);+ if (skipStatsUpdate) {+ // Property-only and comment-only alters cannot change columns, so the constraints stay as+ // they are. Instruct the metastore not to recompute statistics for this alter, so it does+ // not access the table's storage location.+ invoke(+ ExceptionTarget.table(tableName),+ () ->+ client.alter_table(+ catalogName, databaseName, tableName, tb, doNotUpdateStatsContext()));+ return;+ }++ // The Thrift Table passed to alter_table carries no constraint information, so constraints+ // are rewritten around it: the existing ones are dropped first (while their columns and the+ // old table name still exist) and the desired set is added after the alter (once new columns+ // and names are in place). The desired set is built before the first metastore write so that+ // an unconvertible default value leaves the table untouched.+ ColumnConstraints existing = loadColumnConstraints(catalogName, databaseName, tableName);+ ColumnConstraints desired =+ buildColumnConstraints(+ catalogName,+ alteredHiveTable.databaseName(),+ alteredHiveTable.name(),+ alteredHiveTable.columns(),+ existing);+ try {+ dropColumnConstraints(catalogName, databaseName, tableName, existing);+ invoke(+ ExceptionTarget.table(tableName),+ () -> client.alter_table(catalogName, databaseName, tableName, tb));+ } catch (RuntimeException e) {+ // The table is unchanged, so any constraints dropped before the failure can be put back.+ restoreColumnConstraints(catalogName, databaseName, tableName, existing, e);+ throw e;+ }+ try {+ addColumnConstraints(desired);+ } catch (RuntimeException e) {+ String message =+ String.format(+ "Table %s.%s was altered, but its existing column constraints %s were dropped and "+ + "the desired column constraints %s could not be fully created; inspect the "+ + "metastore and re-apply any missing NOT NULL and DEFAULT constraints manually",+ alteredHiveTable.databaseName(),+ alteredHiveTable.name(),+ existing.names,+ desired.names);+ LOG.error(message, e);+ throw new RuntimeException(message, e);+ }+ }++ @Override+ public void dropTable(+ String catalogName,+ String databaseName,+ String tableName,+ boolean deleteData,+ boolean ifPurge) {+ invoke(+ ExceptionTarget.table(tableName),+ () -> client.dropTable(catalogName, databaseName, tableName, deleteData, ifPurge));+ }++ @Override+ public void createTable(HiveTable hiveTable) {+ String catalogName = hiveTable.catalogName();+ Table tb = HiveTableConverter.toHiveTable(hiveTable);+ tb.setCatName(catalogName);+ ColumnConstraints constraints =+ buildColumnConstraints(+ catalogName, hiveTable.databaseName(), hiveTable.name(), hiveTable.columns());+ if (constraints.isEmpty()) {+ invoke(ExceptionTarget.table(hiveTable.name()), () -> client.createTable(tb));+ return;+ }+ invoke(+ ExceptionTarget.table(hiveTable.name()),+ () ->+ client.createTableWithConstraints(+ tb,+ Collections.emptyList(),+ Collections.emptyList(),+ Collections.emptyList(),+ constraints.notNulls,+ constraints.defaults,+ Collections.emptyList()));+ }++ @Override+ public List<String> listPartitionNames(HiveTable table, short pageSize) {+ String catalogName = table.catalogName();+ String databaseName = table.databaseName();+ return invoke(+ ExceptionTarget.table(table.name()),+ () -> client.listPartitionNames(catalogName, databaseName, table.name(), (int) pageSize));+ }++ @Override+ public List<HivePartition> listPartitions(HiveTable table, short pageSize) {+ String catalogName = table.catalogName();+ String databaseName = table.databaseName();+ List<Partition> partitions =+ invoke(+ ExceptionTarget.table(table.name()),+ () -> client.listPartitions(catalogName, databaseName, table.name(), (int) pageSize));+ return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();+ }++ @Override+ public List<HivePartition> listPartitions(+ HiveTable table, List<String> filterPartitionValueList, short pageSize) {+ String catalogName = table.catalogName();+ String databaseName = table.databaseName();+ List<Partition> partitions =+ invoke(+ ExceptionTarget.table(table.name()),+ () ->+ client.listPartitions(+ catalogName,+ databaseName,+ table.name(),+ filterPartitionValueList,+ (int) pageSize));+ return partitions.stream().map(p -> HiveTableConverter.fromHivePartition(table, p)).toList();+ }++ @Override+ public HivePartition getPartition(HiveTable table, String partitionName) {+ String catalogName = table.catalogName();+ String databaseName = table.databaseName();+ List<String> partitionValues = HivePartition.extractPartitionValues(partitionName);+ Partition partition =+ invoke(+ ExceptionTarget.partition(partitionName),+ () -> client.getPartition(catalogName, databaseName, table.name(), partitionValues));+ return HiveTableConverter.fromHivePartition(table, partition);+ }++ @Override+ public HivePartition addPartition(HiveTable table, HivePartition partition) {+ String catalogName = table.catalogName();+ String databaseName = table.databaseName();+ Partition hivePartition = HiveTableConverter.toHivePartition(databaseName, table, partition);+ hivePartition.setCatName(catalogName);+ Partition addedPartition =+ invoke(+ ExceptionTarget.partition(partition.name()), () -> client.add_partition(hivePartition));+ return HiveTableConverter.fromHivePartition(table, addedPartition);+ }++ @Override+ public void dropPartition(+ String catalogName,+ String databaseName,+ String tableName,+ String partitionName,+ boolean deleteData) {+ List<String> partitionValues = HivePartition.extractPartitionValues(partitionName);+ invoke(+ ExceptionTarget.partition(partitionName),+ () ->+ client.dropPartition(+ catalogName, databaseName, tableName, partitionValues, deleteData));+ }++ @Override+ public List<HiveTable> getTableObjectsByName(+ String catalogName, String databaseName, List<String> allTables) {+ List<Table> tables =+ invoke(+ ExceptionTarget.schema(databaseName),+ () -> client.getTableObjectsByName(catalogName, databaseName, allTables));+ // 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();+ }++ @Override+ public List<String> getCatalogs() {+ return invoke(ExceptionTarget.other(""), client::getCatalogs);+ }++ @Override+ public void createCatalog(String catalogName, String location, String description) {+ Catalog catalog = new Catalog(catalogName, location);+ if (StringUtils.isNotBlank(description)) {+ catalog.setDescription(description);+ }+ invoke(ExceptionTarget.catalog(catalogName), () -> client.createCatalog(catalog));+ }++ /** NOT NULL and DEFAULT constraints of a table, as Hive metastore constraint objects. */+ private static class ColumnConstraints {+ final List<SQLNotNullConstraint> notNulls = new ArrayList<>();+ final List<SQLDefaultConstraint> defaults = new ArrayList<>();+ // constraint names of both kinds+ final Set<String> names = new HashSet<>();++ boolean isEmpty() {+ return notNulls.isEmpty() && defaults.isEmpty();+ }+ }++ private ColumnConstraints loadColumnConstraints(+ String catalogName, String databaseName, String tableName) {+ ExceptionTarget target = ExceptionTarget.table(tableName);+ ColumnConstraints constraints = new ColumnConstraints();+ List<SQLNotNullConstraint> notNulls =+ invoke(+ target,+ () ->+ client.getNotNullConstraints(+ new NotNullConstraintsRequest(catalogName, databaseName, tableName)));+ for (SQLNotNullConstraint constraint : notNulls) {+ constraints.notNulls.add(constraint);+ constraints.names.add(constraint.getNn_name());+ }+ List<SQLDefaultConstraint> defaults =+ invoke(+ target,+ () ->+ client.getDefaultConstraints(+ new DefaultConstraintsRequest(catalogName, databaseName, tableName)));+ for (SQLDefaultConstraint constraint : defaults) {+ constraints.defaults.add(constraint);+ constraints.names.add(constraint.getDc_name());+ }+ return constraints;+ }++ private Set<String> notNullColumns(ColumnConstraints constraints) {+ Set<String> columns = new HashSet<>();+ for (SQLNotNullConstraint constraint : constraints.notNulls) {+ columns.add(constraint.getColumn_name());+ }+ return columns;+ }++ private Map<String, String> defaultValues(ColumnConstraints constraints) {+ Map<String, String> values = new HashMap<>();+ for (SQLDefaultConstraint constraint : constraints.defaults) {+ values.put(constraint.getColumn_name(), constraint.getDefault_value());+ }+ return values;+ }++ private void dropColumnConstraints(+ String catalogName, String databaseName, String tableName, ColumnConstraints constraints) {+ for (SQLNotNullConstraint constraint : constraints.notNulls) {+ invoke(+ ExceptionTarget.table(tableName),+ () ->+ client.dropConstraint(catalogName, databaseName, tableName, constraint.getNn_name()));+ }+ for (SQLDefaultConstraint constraint : constraints.defaults) {+ invoke(+ ExceptionTarget.table(tableName),+ () ->+ client.dropConstraint(catalogName, databaseName, tableName, constraint.getDc_name()));+ }+ }++ private void addColumnConstraints(ColumnConstraints constraints) {+ if (!constraints.notNulls.isEmpty()) {+ invoke(ExceptionTarget.other(""), () -> client.addNotNullConstraint(constraints.notNulls));+ }+ if (!constraints.defaults.isEmpty()) {+ invoke(ExceptionTarget.other(""), () -> client.addDefaultConstraint(constraints.defaults));+ }+ }++ private void restoreColumnConstraints(+ String catalogName,+ String databaseName,+ String tableName,+ ColumnConstraints constraints,+ Exception cause) {+ if (constraints.isEmpty()) {+ return;+ }+ try {+ ColumnConstraints current = loadColumnConstraints(catalogName, databaseName, tableName);+ ColumnConstraints missing = new ColumnConstraints();+ for (SQLNotNullConstraint constraint : constraints.notNulls) {+ if (!current.names.contains(constraint.getNn_name())) {+ missing.notNulls.add(constraint);+ missing.names.add(constraint.getNn_name());+ }+ }+ for (SQLDefaultConstraint constraint : constraints.defaults) {+ if (!current.names.contains(constraint.getDc_name())) {+ missing.defaults.add(constraint);+ missing.names.add(constraint.getDc_name());+ }+ }+ addColumnConstraints(missing);+ } catch (RuntimeException restoreFailure) {+ cause.addSuppressed(restoreFailure);+ LOG.error(+ "Failed to restore column constraints {} of table {}.{} after a failed alter; "+ + "the NOT NULL and DEFAULT constraints must be re-applied manually",+ constraints.names,+ databaseName,+ tableName,+ restoreFailure);+ }+ }++ private ColumnConstraints buildColumnConstraints(+ String catalogName, String databaseName, String tableName, Column[] columns) {+ return buildColumnConstraints(+ catalogName, databaseName, tableName, columns, new ColumnConstraints());+ }++ private ColumnConstraints buildColumnConstraints(+ String catalogName,+ String databaseName,+ String tableName,+ Column[] columns,+ ColumnConstraints existing) {+ ColumnConstraints constraints = new ColumnConstraints();+ Map<String, SQLNotNullConstraint> existingNotNulls = new HashMap<>();+ for (SQLNotNullConstraint constraint : existing.notNulls) {+ existingNotNulls.put(constraint.getColumn_name(), constraint);+ }+ Map<String, SQLDefaultConstraint> existingDefaults = new HashMap<>();+ for (SQLDefaultConstraint constraint : existing.defaults) {+ existingDefaults.put(constraint.getColumn_name(), constraint);+ }+ for (Column column : columns) {+ if (!column.nullable()) {+ SQLNotNullConstraint previous = existingNotNulls.get(column.name());+ String name =+ previous == null+ ? constraintName(tableName, column.name(), "nn")+ : previous.getNn_name();+ constraints.notNulls.add(+ new SQLNotNullConstraint(+ catalogName,+ databaseName,+ tableName,+ column.name(),+ name,+ previous == null ? CONSTRAINT_ENABLE : previous.isEnable_cstr(),+ previous == null ? CONSTRAINT_VALIDATE : previous.isValidate_cstr(),+ previous == null ? CONSTRAINT_RELY : previous.isRely_cstr()));+ constraints.names.add(name);+ }+ String defaultValue = HiveColumnDefaultValueConverter.fromGravitino(column.defaultValue());+ if (defaultValue != null) {+ SQLDefaultConstraint previous = existingDefaults.get(column.name());+ String name =+ previous == null+ ? constraintName(tableName, column.name(), "dv")+ : previous.getDc_name();+ constraints.defaults.add(+ new SQLDefaultConstraint(+ catalogName,+ databaseName,+ tableName,+ column.name(),+ defaultValue,+ name,+ previous == null ? CONSTRAINT_ENABLE : previous.isEnable_cstr(),+ previous == null ? CONSTRAINT_VALIDATE : previous.isValidate_cstr(),+ previous == null ? CONSTRAINT_RELY : previous.isRely_cstr()));+ constraints.names.add(name);+ }+ }+ return constraints;+ }++ private static String constraintName(String tableName, String columnName, String suffix) {+ // Constraint names are unique across the whole metastore and the prefix does not include the+ // database name, so a random suffix keeps same-named tables in different databases apart.+ // The prefix is bounded so the name fits the metastore's constraint name column.+ String prefix = tableName + "_" + columnName;+ if (prefix.length() > MAX_CONSTRAINT_PREFIX) {+ prefix = prefix.substring(0, MAX_CONSTRAINT_PREFIX);+ }+ return RandomNameUtils.genRandomName(prefix + "_" + suffix);+ }++ /** A metastore call, deferred so exceptions can be converted uniformly by {@link #invoke}. */+ @FunctionalInterface+ private interface MetastoreCall<T> {+ T call() throws Exception;+ }++ /**+ * A void metastore call, deferred so exceptions can be converted uniformly by {@link #invoke}.+ */+ @FunctionalInterface+ private interface VoidMetastoreCall {+ void call() throws Exception;+ }++ private <T> T invoke(ExceptionTarget target, MetastoreCall<T> call) {+ try {+ return call.call();+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, target);+ }+ }++ private void invoke(ExceptionTarget target, VoidMetastoreCall call) {+ try {+ call.call();+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, target);+ }+ }+}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.javanew file mode 100644index 0000000000..b7ac7e0e14--- /dev/null+++ b/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java@@ -0,0 +1,357 @@+/*+ * 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.hive3;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.inOrder;+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.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Properties;+import org.apache.gravitino.catalog.hive.HiveConstants;+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.expressions.literals.Literals;+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.MetaException;+import org.apache.hadoop.hive.metastore.api.NotNullConstraintsRequest;+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.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;+import org.mockito.InOrder;++/**+ * Unit tests for {@link HiveShimV3}, using a mocked {@link IMetaStoreClient} to verify NOT NULL /+ * DEFAULT constraint construction and the {@code alterTable} drop/recreate sequence, following the+ * same mocking style as {@code TestHiveShimAlterTable} for the base {@link+ * org.apache.gravitino.hive.client.HiveShim}.+ */+class TestHiveShimV3 {++ private static final String CATALOG = "hive";+ private static final String DB = "db";+ private static final String TABLE = "tbl";++ /**+ * A {@link HiveShimV3} that uses a mocked metastore client instead of connecting to a real Hive+ * Metastore. The mock is created inside {@link #createMetaStoreClient(Properties)} because that+ * method is invoked from the {@code HiveShim} superclass constructor, before any subclass field+ * is initialized.+ */+ private static class MockHiveShimV3 extends HiveShimV3 {+ MockHiveShimV3() {+ super(new Properties());+ }++ @Override+ public IMetaStoreClient createMetaStoreClient(Properties properties) {+ return mock(IMetaStoreClient.class);+ }++ IMetaStoreClient metaStoreClient() {+ return client;+ }+ }++ private HiveTable testTable(Column... columns) {+ Map<String, String> properties = new HashMap<>();+ properties.put(HiveConstants.LOCATION, "hdfs://ns/warehouse/db.db/tbl");+ return HiveTable.builder()+ .withName(TABLE)+ .withColumns(columns)+ .withProperties(properties)+ .withAuditInfo(+ AuditInfo.builder().withCreator("tester").withCreateTime(Instant.now()).build())+ .withCatalogName(CATALOG)+ .withDatabaseName(DB)+ .build();+ }++ @Test+ void testCreateTableBuildsNotNullAndDefaultConstraints() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ Column notNullColumn =+ Column.of("id", Types.IntegerType.get(), null, /* nullable */ false, false, null);+ Column defaultValueColumn =+ Column.of("name", Types.StringType.get(), null, true, false, Literals.stringLiteral("abc"));+ HiveTable table = testTable(notNullColumn, defaultValueColumn);++ shim.createTable(table);++ ArgumentCaptor<List<SQLNotNullConstraint>> notNullCaptor = ArgumentCaptor.forClass(List.class);+ ArgumentCaptor<List<SQLDefaultConstraint>> defaultCaptor = ArgumentCaptor.forClass(List.class);+ verify(client)+ .createTableWithConstraints(+ any(Table.class),+ eq(Collections.emptyList()),+ eq(Collections.emptyList()),+ eq(Collections.emptyList()),+ notNullCaptor.capture(),+ defaultCaptor.capture(),+ eq(Collections.emptyList()));++ List<SQLNotNullConstraint> notNulls = notNullCaptor.getValue();+ assertEquals(1, notNulls.size());+ SQLNotNullConstraint notNull = notNulls.get(0);+ assertEquals("id", notNull.getColumn_name());+ assertTrue(notNull.getNn_name().startsWith(TABLE + "_id_nn"));+ assertTrue(notNull.isEnable_cstr());+ assertFalse(notNull.isValidate_cstr());+ assertFalse(notNull.isRely_cstr());++ List<SQLDefaultConstraint> defaults = defaultCaptor.getValue();+ assertEquals(1, defaults.size());+ SQLDefaultConstraint defaultConstraint = defaults.get(0);+ assertEquals("name", defaultConstraint.getColumn_name());+ assertEquals("'abc'", defaultConstraint.getDefault_value());+ assertTrue(defaultConstraint.getDc_name().startsWith(TABLE + "_name_dv"));+ assertTrue(defaultConstraint.isEnable_cstr());+ assertFalse(defaultConstraint.isValidate_cstr());+ assertFalse(defaultConstraint.isRely_cstr());+ }++ @Test+ void testCreateTableWithoutConstraintsSkipsConstraintsCall() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ Column plainColumn = Column.of("id", Types.IntegerType.get(), null, true, false, null);+ shim.createTable(testTable(plainColumn));++ verify(client).createTable(any(Table.class));+ verify(client, never())+ .createTableWithConstraints(any(), any(), any(), any(), any(), any(), any());+ }++ @Test+ void testAlterTablePreservesExistingConstraintMetadata() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ SQLNotNullConstraint existingNotNull =+ new SQLNotNullConstraint(CATALOG, DB, TABLE, "id", "external_not_null", false, true, true);+ SQLDefaultConstraint existingDefault =+ new SQLDefaultConstraint(+ CATALOG, DB, TABLE, "name", "'abc'", "external_default", false, true, true);+ when(client.getNotNullConstraints(new NotNullConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingNotNull));+ when(client.getDefaultConstraints(new DefaultConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingDefault));++ Column notNullColumn =+ Column.of("id", Types.IntegerType.get(), "updated comment", false, false, null);+ Column defaultValueColumn =+ Column.of("name", Types.StringType.get(), null, true, false, Literals.stringLiteral("abc"));+ HiveTable alteredTable = testTable(notNullColumn, defaultValueColumn);++ shim.alterTable(CATALOG, DB, TABLE, alteredTable, false);++ ArgumentCaptor<List<SQLNotNullConstraint>> notNullCaptor = ArgumentCaptor.forClass(List.class);+ ArgumentCaptor<List<SQLDefaultConstraint>> defaultCaptor = ArgumentCaptor.forClass(List.class);+ InOrder calls = inOrder(client);+ calls.verify(client).dropConstraint(CATALOG, DB, TABLE, "external_not_null");+ calls.verify(client).dropConstraint(CATALOG, DB, TABLE, "external_default");+ calls.verify(client).alter_table(eq(CATALOG), eq(DB), eq(TABLE), any(Table.class));+ calls.verify(client).addNotNullConstraint(notNullCaptor.capture());+ calls.verify(client).addDefaultConstraint(defaultCaptor.capture());++ SQLNotNullConstraint recreatedNotNull = notNullCaptor.getValue().get(0);+ assertEquals("external_not_null", recreatedNotNull.getNn_name());+ assertFalse(recreatedNotNull.isEnable_cstr());+ assertTrue(recreatedNotNull.isValidate_cstr());+ assertTrue(recreatedNotNull.isRely_cstr());++ SQLDefaultConstraint recreatedDefault = defaultCaptor.getValue().get(0);+ assertEquals("external_default", recreatedDefault.getDc_name());+ assertFalse(recreatedDefault.isEnable_cstr());+ assertTrue(recreatedDefault.isValidate_cstr());+ assertTrue(recreatedDefault.isRely_cstr());+ }++ @Test+ void testAlterTableRestoresConstraintsWhenAlterFails() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ SQLNotNullConstraint existingNotNull =+ new SQLNotNullConstraint(CATALOG, DB, TABLE, "id", "tbl_id_nn_old", true, false, false);+ when(client.getNotNullConstraints(new NotNullConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingNotNull), List.of());+ when(client.getDefaultConstraints(new DefaultConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(), List.of());+ doThrow(new MetaException("boom"))+ .when(client)+ .alter_table(anyString(), anyString(), anyString(), any(Table.class));++ Column notNullColumn = Column.of("id", Types.IntegerType.get(), null, false, false, null);+ HiveTable alteredTable = testTable(notNullColumn);++ assertThrows(+ RuntimeException.class, () -> shim.alterTable(CATALOG, DB, TABLE, alteredTable, false));++ // The alter failed, so the previously dropped constraints must be put back.+ verify(client).addNotNullConstraint(List.of(existingNotNull));+ }++ @Test+ void testAlterTableFailurePropagatesWhenConstraintsCannotBeRestored() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ SQLNotNullConstraint existingNotNull =+ new SQLNotNullConstraint(CATALOG, DB, TABLE, "id", "tbl_id_nn_old", true, false, false);+ when(client.getNotNullConstraints(new NotNullConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingNotNull), List.of());+ when(client.getDefaultConstraints(new DefaultConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(), List.of());+ doThrow(new MetaException("boom"))+ .when(client)+ .alter_table(anyString(), anyString(), anyString(), any(Table.class));+ doThrow(new MetaException("restore also fails")).when(client).addNotNullConstraint(any());++ Column notNullColumn = Column.of("id", Types.IntegerType.get(), null, false, false, null);+ HiveTable alteredTable = testTable(notNullColumn);++ // The original alter failure must still be the one that is (eventually) surfaced, even though+ // restoring the dropped constraints also failed.+ RuntimeException thrown =+ assertThrows(+ RuntimeException.class, () -> shim.alterTable(CATALOG, DB, TABLE, alteredTable, false));+ assertTrue(thrown.getMessage() == null || !thrown.getMessage().contains("restore"));+ }++ @Test+ void testAlterTableRestoresEarlierConstraintWhenLaterDropFails() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ SQLNotNullConstraint existingNotNull =+ new SQLNotNullConstraint(CATALOG, DB, TABLE, "id", "existing_not_null", true, false, false);+ SQLDefaultConstraint existingDefault =+ new SQLDefaultConstraint(+ CATALOG, DB, TABLE, "name", "'abc'", "existing_default", true, false, false);+ when(client.getNotNullConstraints(new NotNullConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingNotNull), List.of());+ when(client.getDefaultConstraints(new DefaultConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingDefault), List.of(existingDefault));+ doThrow(new MetaException("second drop failed"))+ .when(client)+ .dropConstraint(CATALOG, DB, TABLE, "existing_default");++ Column notNullColumn = Column.of("id", Types.IntegerType.get(), null, false, false, null);+ Column defaultValueColumn =+ Column.of("name", Types.StringType.get(), null, true, false, Literals.stringLiteral("abc"));++ assertThrows(+ RuntimeException.class,+ () ->+ shim.alterTable(+ CATALOG, DB, TABLE, testTable(notNullColumn, defaultValueColumn), false));++ verify(client).addNotNullConstraint(List.of(existingNotNull));+ verify(client, never()).addDefaultConstraint(any());+ verify(client, never()).alter_table(anyString(), anyString(), anyString(), any(Table.class));+ }++ @Test+ void testAlterTableRethrowsWithClearMessageWhenConstraintReAddFails() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ SQLDefaultConstraint existingDefault =+ new SQLDefaultConstraint(+ CATALOG, DB, TABLE, "old_column", "'old'", "existing_default", true, false, false);+ when(client.getNotNullConstraints(new NotNullConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of());+ when(client.getDefaultConstraints(new DefaultConstraintsRequest(CATALOG, DB, TABLE)))+ .thenReturn(List.of(existingDefault));+ doThrow(new MetaException("add failed")).when(client).addNotNullConstraint(any());++ Column notNullColumn = Column.of("id", Types.IntegerType.get(), null, false, false, null);+ HiveTable alteredTable = testTable(notNullColumn);++ RuntimeException thrown =+ assertThrows(+ RuntimeException.class, () -> shim.alterTable(CATALOG, DB, TABLE, alteredTable, false));++ // alter_table itself succeeded (no stub failure), so the table was altered but constraints+ // could not be fully created; the surfaced message distinguishes the old and desired sets.+ verify(client).alter_table(eq(CATALOG), eq(DB), eq(TABLE), any(Table.class));+ assertTrue(thrown.getMessage().contains("existing_default"));+ assertTrue(thrown.getMessage().contains("tbl_id_nn"));+ assertTrue(thrown.getMessage().contains("could not be fully created"));+ }++ @Test+ void testGetViewDoesNotLoadConstraints() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ Column plainColumn = Column.of("id", Types.IntegerType.get(), null, true, false, null);+ Table hiveView = HiveTableConverter.toHiveTable(testTable(plainColumn));+ hiveView.setCatName(CATALOG);+ hiveView.setTableType(TableType.VIRTUAL_VIEW.name());+ when(client.getTable(CATALOG, DB, TABLE)).thenReturn(hiveView);++ shim.getTable(CATALOG, DB, TABLE);++ verify(client, never()).getNotNullConstraints(any());+ verify(client, never()).getDefaultConstraints(any());+ }++ @Test+ void testGetTableObjectsByNameDoesNotLoadConstraints() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();++ Column plainColumn = Column.of("id", Types.IntegerType.get(), null, true, false, null);+ Table hiveTable = HiveTableConverter.toHiveTable(testTable(plainColumn));+ hiveTable.setCatName(CATALOG);+ when(client.getTableObjectsByName(CATALOG, DB, List.of(TABLE))).thenReturn(List.of(hiveTable));++ shim.getTableObjectsByName(CATALOG, DB, List.of(TABLE));++ verify(client, never()).getNotNullConstraints(any());+ verify(client, never()).getDefaultConstraints(any());+ }+}diff --git a/docs/apache-hive-catalog.md b/docs/apache-hive-catalog.mdindex 3d6770ecdf..73b0952e7a 100644--- a/docs/apache-hive-catalog.md+++ b/docs/apache-hive-catalog.md@@ -110,7 +110,7 @@ see [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#schema-operat### Table Capabilities- The Hive catalog supports creating, updating, and deleting tables in the HMS.-- Doesn't support column default value.+- Column `NOT NULL` and `DEFAULT` constraints are supported only when the connected HMS is Hive 3.x; on Hive 2.x they are rejected.### Table Partitioning@@ -222,12 +222,14 @@ As Gravitino has a separate interface for updating the comment of a table, the H##### Alter column-| Hive Alter Operation | Gravitino Table Update Request |-|--------------------------|-----------------------------------|-| `Change Column Name` | `Rename a column` |-| `Change Column Type` | `Update the type of a column` |-| `Change Column Position` | `Update the position of a column` |-| `Change Column Comment` | `Update the column comment` |+| Hive Alter Operation | Gravitino Table Update Request |+|-----------------------------|--------------------------------------------------------|+| `Change Column Name` | `Rename a column` |+| `Change Column Type` | `Update the type of a column` |+| `Change Column Position` | `Update the position of a column` |+| `Change Column Comment` | `Update the column comment` |+| `Change Column Nullability` | `Update the nullability of a column` (Hive 3.x only) |+| `Change Column Default` | `Update the default value of a column` (Hive 3.x only) |##### Alter partitiondiff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.javaindex a48738a8a6..3808e7506e 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.java@@ -552,8 +552,8 @@ public abstract class FlinkHiveCatalogIT extends FlinkCommonIT {String key = "test key";String value = "test value";- // 1. The NOT NULL constraint for column is only supported since Hive 3.0,- // but the current Gravitino Hive catalog only supports Hive 2.x.+ // 1. The NOT NULL constraint for column is only supported since Hive 3.0, and the test+ // environment runs a Hive 2.x metastore.// 2. Hive doesn't support Time and Timestamp with timezone type.// 3. Flink SQL only support to create Interval Month and Second(3).doWithSchema(