World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#9504] feat(flink): support generic table for Gravitino flink connector (#9689)
FANNG7f2cbfc921f1
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 b25ea4bbcc..f0a8debac2 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@@ -36,6 +36,8 @@ import static org.apache.gravitino.catalog.hive.HiveCatalogPropertiesMetadata.PRimport static org.apache.gravitino.catalog.hive.TestHiveCatalog.HIVE_PROPERTIES_METADATA;import static org.apache.gravitino.connector.BaseCatalog.CATALOG_BYPASS_PREFIX;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doNothing;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -49,10 +51,20 @@ import org.apache.gravitino.connector.BaseCatalog;import org.apache.gravitino.connector.PropertyEntry;import org.apache.gravitino.exceptions.ConnectionFailedException;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.rel.Column;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Index;+import org.apache.gravitino.utils.ClientPool;import org.apache.hadoop.hive.conf.HiveConf.ConfVars;import org.apache.thrift.TException;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;class TestHiveCatalogOperations {@Test@@ -148,4 +160,41 @@ class TestHiveCatalogOperations {"Failed to run getAllDatabases in Hive Metastore: mock connection exception",exception.getMessage());}++ @Test+ void testCreateGenericTableWithEmptyColumns() throws Exception {+ HiveCatalogOperations op = new HiveCatalogOperations();+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);++ CachedClientPool clientPool = mock(CachedClientPool.class);+ HiveClient hiveClient = mock(HiveClient.class);+ HiveSchema schema = HiveSchema.builder().withCatalogName("hive").withName("db").build();+ when(hiveClient.getDatabase(anyString(), anyString())).thenReturn(schema);++ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);+ doNothing().when(hiveClient).createTable(hiveTableCaptor.capture());+ when(clientPool.run(any()))+ .thenAnswer(+ invocation -> {+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);+ return action.run(hiveClient);+ });+ op.clientPool = clientPool;++ Map<String, String> properties = Maps.newHashMap();+ properties.put("is_generic", "true");++ op.createTable(+ NameIdentifier.of("db", "tbl"),+ new Column[0],+ "comment",+ properties,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]);++ HiveTable createdTable = hiveTableCaptor.getValue();+ Assertions.assertEquals(0, createdTable.columns().length);+ }}diff --git a/docs/flink-connector/flink-catalog-hive.md b/docs/flink-connector/flink-catalog-hive.mdindex 057cd4d0d0..612aed5e06 100644--- a/docs/flink-connector/flink-catalog-hive.md+++ b/docs/flink-connector/flink-catalog-hive.md@@ -23,6 +23,30 @@ Supports most DDL and DML operations in Flink SQL, except such operations:- `DELETE` clause- `CALL` clause+## Generic table support++Flink generic tables are non-Hive tables. Their schema and partition keys are stored in table+properties in Hive metastore. Gravitino Flink connector follows the Flink Hive catalog behavior:++- If `connector=hive`, the table is treated as a Hive table and stored with a normal Hive schema.+- If the connector is missing or not `hive`, the table is treated as a generic table. Gravitino+ stores an empty Hive schema and serializes schema and partition keys into `flink.*` properties.+ It also uses the `is_generic` flag when needed for compatibility.++When loading or altering a table, Gravitino Flink connector detects generic tables by the+`is_generic`, `flink.connector`, and `flink.connector.type` properties. Generic tables are+reconstructed from the serialized `flink.*` properties. Hive tables continue to use the native+Hive schema.++:::note+You must set `connector=hive` explicitly when creating a raw Hive table. Otherwise, the table is+created as a generic table by default in HiveCatalog. Starting from Apache Flink 1.18,+ManagedTable-related APIs are deprecated, so avoid relying on managed table behavior. Prefer+Hive-compatible tables (use Hive dialect or set `connector=hive`) or external generic tables (set+an explicit `connector`). For details, see the Flink documentation on Hive generic tables:+https://nightlies.apache.org/flink/flink-docs-stable/docs/connectors/table/hive/hive_catalog/#generic-tables+:::+## Requirement* Hive metastore 2.x@@ -30,7 +54,6 @@ Supports most DDL and DML operations in Flink SQL, except such operations:## SQL example-```sql// Suppose hive_a is the Hive catalog name managed by Gravitino@@ -45,13 +68,28 @@ SET 'execution.runtime-mode' = 'batch';SET 'sql-client.execution.result-mode' = 'tableau';-- [INFO] Execute statement succeed.-// Create table+// Create a raw hive table, please make sure setting 'connector'='hive'.CREATE TABLE IF NOT EXISTS employees (id INT,name STRING,dt INT)-PARTITIONED BY (dt);+PARTITIONED BY (dt) WITH (+ 'connector'='hive'+);++// Create a generic jdbc table+CREATE TABLE IF NOT EXISTS jdbc_table (+ id INT,+ name STRING+) WITH (+ 'connector'='jdbc',+ 'url'='jdbc:postgresql://127.0.0.1:5432/postgres',+ 'table-name'='jdbc_table',+ 'username'='xx',+ 'password'='xx',+ 'driver'='org.postgresql.Driver'+);DESC EXTENDED employees;@@ -76,4 +114,4 @@ The validated catalog properties are listed below. Any other properties with the:::cautionYou can set other hadoop properties (with the prefix `hadoop.`, `dfs.`, `fs.`, `hive.`) in Gravitino Catalog properties. If so, it will overridethe configuration from the `hive-conf-dir` and `hadoop-conf-dir`.-:::\ No newline at end of file+:::diff --git a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/catalog/BaseCatalog.java b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/catalog/BaseCatalog.javaindex d5eeaef726..e2f412ec67 100644--- a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/catalog/BaseCatalog.java+++ b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/catalog/BaseCatalog.java@@ -293,10 +293,9 @@ public abstract class BaseCatalog extends AbstractCatalog {schemaAndTablePropertiesConverter.toGravitinoTableProperties(table.getOptions());Transform[] partitions =partitionConverter.toGravitinoPartitions(((CatalogTable) table).getPartitionKeys());+ Index[] indices = getGrivatinoIndices(resolvedTable);try {-- Index[] indices = getGrivatinoIndices(resolvedTable);catalog().asTableCatalog().createTable(diff --git a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/FlinkGenericTableUtil.java b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/FlinkGenericTableUtil.javanew file mode 100644index 0000000000..d7447968ae--- /dev/null+++ b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/FlinkGenericTableUtil.java@@ -0,0 +1,123 @@+/*+ * 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.flink.connector.hive;++import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+import java.util.stream.Collectors;+import org.apache.flink.table.catalog.CatalogPropertiesUtil;+import org.apache.flink.table.catalog.CatalogTable;+import org.apache.flink.table.catalog.ResolvedCatalogTable;+import org.apache.flink.table.factories.FactoryUtil;+import org.apache.gravitino.rel.Table;++final class FlinkGenericTableUtil {+ public static final String CONNECTOR = FactoryUtil.CONNECTOR.key();+ private static final String CONNECTOR_TYPE = "connector.type";+ private static final String MANAGED_TABLE_IDENTIFIER = "default";++ private FlinkGenericTableUtil() {}++ static boolean isGenericTableWhenCreate(Map<String, String> options) {+ if (options == null) {+ return true;+ }+ String connector = options.get(CONNECTOR);+ if (connector == null) {+ return true;+ }+ return !"hive".equalsIgnoreCase(connector);+ }++ static boolean isGenericTableWhenLoad(Map<String, String> properties) {+ // If a table doesn't have properties, it is a raw hive table.+ if (properties == null) {+ return false;+ }+ if (properties.containsKey(CatalogPropertiesUtil.IS_GENERIC)) {+ return Boolean.parseBoolean(properties.get(CatalogPropertiesUtil.IS_GENERIC));+ }+ String connector = getConnectorFromProperties(properties);+ if (connector == null) {+ return false;+ }+ return !"hive".equalsIgnoreCase(connector);+ }++ static Map<String, String> toGravitinoGenericTableProperties(ResolvedCatalogTable resolvedTable) {+ Map<String, String> properties = CatalogPropertiesUtil.serializeCatalogTable(resolvedTable);+ if (!properties.containsKey(CONNECTOR)) {+ properties.put(CONNECTOR, MANAGED_TABLE_IDENTIFIER);+ }+ Map<String, String> masked = maskFlinkProperties(properties);+ masked.put(CatalogPropertiesUtil.IS_GENERIC, "true");+ return masked;+ }++ static CatalogTable toFlinkGenericTable(Table table) {+ Map<String, String> flinkProperties = unmaskFlinkProperties(table.properties());+ CatalogTable catalogTable = CatalogPropertiesUtil.deserializeCatalogTable(flinkProperties);+ if (catalogTable.getUnresolvedSchema().getColumns().isEmpty()) {+ catalogTable =+ CatalogPropertiesUtil.deserializeCatalogTable(flinkProperties, "generic.table.schema");+ }+ Map<String, String> options = new HashMap<>(catalogTable.getOptions());+ if (MANAGED_TABLE_IDENTIFIER.equalsIgnoreCase(options.get(CONNECTOR))) {+ options.remove(CONNECTOR);+ }+ return CatalogTable.of(+ catalogTable.getUnresolvedSchema(),+ catalogTable.getComment(),+ catalogTable.getPartitionKeys(),+ options);+ }++ private static String getConnectorFromProperties(Map<String, String> properties) {+ String connector = properties.get(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + CONNECTOR);+ if (connector == null) {+ connector = properties.get(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + CONNECTOR_TYPE);+ }+ return connector;+ }++ private static Map<String, String> maskFlinkProperties(Map<String, String> properties) {+ if (properties == null) {+ return Collections.emptyMap();+ }+ return properties.entrySet().stream()+ .filter(e -> e.getKey() != null && e.getValue() != null)+ .collect(+ Collectors.toMap(+ e -> CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + e.getKey(),+ Map.Entry::getValue));+ }++ private static Map<String, String> unmaskFlinkProperties(Map<String, String> properties) {+ if (properties == null) {+ return Collections.emptyMap();+ }+ return properties.entrySet().stream()+ .filter(e -> e.getKey().startsWith(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX))+ .collect(+ Collectors.toMap(+ e -> e.getKey().substring(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX.length()),+ Map.Entry::getValue));+ }+}diff --git a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/GravitinoHiveCatalog.java b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/GravitinoHiveCatalog.javaindex 07411b10d4..d54a82811f 100644--- a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/GravitinoHiveCatalog.java+++ b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/GravitinoHiveCatalog.java@@ -18,15 +18,40 @@*/package org.apache.gravitino.flink.connector.hive;+import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;import java.util.Map;+import java.util.Objects;import java.util.Optional;import javax.annotation.Nullable;import org.apache.flink.table.catalog.AbstractCatalog;+import org.apache.flink.table.catalog.CatalogBaseTable;+import org.apache.flink.table.catalog.CatalogPropertiesUtil;+import org.apache.flink.table.catalog.ObjectPath;+import org.apache.flink.table.catalog.ResolvedCatalogBaseTable;+import org.apache.flink.table.catalog.ResolvedCatalogTable;+import org.apache.flink.table.catalog.exceptions.CatalogException;+import org.apache.flink.table.catalog.exceptions.DatabaseNotExistException;+import org.apache.flink.table.catalog.exceptions.TableAlreadyExistException;+import org.apache.flink.table.catalog.exceptions.TableNotExistException;import org.apache.flink.table.catalog.hive.HiveCatalog;import org.apache.flink.table.factories.Factory;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.exceptions.TableAlreadyExistsException;import org.apache.gravitino.flink.connector.PartitionConverter;import org.apache.gravitino.flink.connector.SchemaAndTablePropertiesConverter;import org.apache.gravitino.flink.connector.catalog.BaseCatalog;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Index;import org.apache.hadoop.hive.conf.HiveConf;/**@@ -67,4 +92,164 @@ public class GravitinoHiveCatalog extends BaseCatalog {protected AbstractCatalog realCatalog() {return hiveCatalog;}++ @Override+ public void createTable(ObjectPath tablePath, CatalogBaseTable table, boolean ignoreIfExists)+ throws TableAlreadyExistException, DatabaseNotExistException, CatalogException {+ Preconditions.checkArgument(+ table instanceof ResolvedCatalogBaseTable, "table should be resolved");++ if (!FlinkGenericTableUtil.isGenericTableWhenCreate(table.getOptions())) {+ super.createTable(tablePath, table, ignoreIfExists);+ return;+ }++ if (!(table instanceof ResolvedCatalogTable)) {+ throw new CatalogException("Generic table must be a resolved catalog table");+ }+ ResolvedCatalogTable resolvedTable = (ResolvedCatalogTable) table;++ NameIdentifier identifier =+ NameIdentifier.of(tablePath.getDatabaseName(), tablePath.getObjectName());+ Map<String, String> properties =+ FlinkGenericTableUtil.toGravitinoGenericTableProperties(resolvedTable);++ try {+ catalog()+ .asTableCatalog()+ .createTable(+ identifier,+ new Column[0],+ table.getComment(),+ properties,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]);+ } catch (NoSuchSchemaException e) {+ throw new DatabaseNotExistException(catalogName(), tablePath.getDatabaseName(), e);+ } catch (TableAlreadyExistsException e) {+ if (!ignoreIfExists) {+ throw new TableAlreadyExistException(catalogName(), tablePath, e);+ }+ } catch (Exception e) {+ throw new CatalogException(e);+ }+ }++ @Override+ public CatalogBaseTable getTable(ObjectPath tablePath)+ throws TableNotExistException, CatalogException {+ try {+ Table table =+ catalog()+ .asTableCatalog()+ .loadTable(NameIdentifier.of(tablePath.getDatabaseName(), tablePath.getObjectName()));+ if (FlinkGenericTableUtil.isGenericTableWhenLoad(table.properties())) {+ return FlinkGenericTableUtil.toFlinkGenericTable(table);+ }+ return super.toFlinkTable(table, tablePath);+ } catch (NoSuchTableException e) {+ throw new TableNotExistException(catalogName(), tablePath, e);+ } catch (Exception e) {+ throw new CatalogException(e);+ }+ }++ @Override+ public void alterTable(ObjectPath tablePath, CatalogBaseTable newTable, boolean ignoreIfNotExists)+ throws TableNotExistException, CatalogException {+ Table table = loadGravitinoTable(tablePath, ignoreIfNotExists);+ if (table == null) {+ return;+ }+ if (!FlinkGenericTableUtil.isGenericTableWhenLoad(table.properties())) {+ super.alterTable(tablePath, newTable, ignoreIfNotExists);+ return;+ }+ if (!(newTable instanceof ResolvedCatalogTable)) {+ throw new CatalogException("Generic table must be a resolved catalog table");+ }+ // For generic tables, we re-serialize the entire table schema and partition keys into+ // flink.* properties, so the individual tableChanges are not needed. The newTable+ // parameter contains the final state after applying all changes.+ applyGenericTableAlter(tablePath, table, (ResolvedCatalogTable) newTable);+ }++ @Override+ public void alterTable(+ ObjectPath tablePath,+ CatalogBaseTable newTable,+ java.util.List<org.apache.flink.table.catalog.TableChange> tableChanges,+ boolean ignoreIfNotExists)+ throws TableNotExistException, CatalogException {+ Table table = loadGravitinoTable(tablePath, ignoreIfNotExists);+ if (table == null) {+ return;+ }+ if (!FlinkGenericTableUtil.isGenericTableWhenLoad(table.properties())) {+ super.alterTable(tablePath, newTable, tableChanges, ignoreIfNotExists);+ return;+ }+ if (!(newTable instanceof ResolvedCatalogTable)) {+ throw new CatalogException("Generic table must be a resolved catalog table");+ }+ applyGenericTableAlter(tablePath, table, (ResolvedCatalogTable) newTable);+ }++ private Table loadGravitinoTable(ObjectPath tablePath, boolean ignoreIfNotExists)+ throws TableNotExistException, CatalogException {+ try {+ return catalog()+ .asTableCatalog()+ .loadTable(NameIdentifier.of(tablePath.getDatabaseName(), tablePath.getObjectName()));+ } catch (NoSuchTableException e) {+ if (!ignoreIfNotExists) {+ throw new TableNotExistException(catalogName(), tablePath, e);+ }+ return null;+ } catch (Exception e) {+ throw new CatalogException(e);+ }+ }++ private void applyGenericTableAlter(+ ObjectPath tablePath, Table existingTable, ResolvedCatalogTable newTable)+ throws TableNotExistException, CatalogException {+ NameIdentifier identifier =+ NameIdentifier.of(tablePath.getDatabaseName(), tablePath.getObjectName());+ Map<String, String> updatedProperties =+ FlinkGenericTableUtil.toGravitinoGenericTableProperties(newTable);+ Map<String, String> currentProperties =+ existingTable.properties() == null ? Collections.emptyMap() : existingTable.properties();++ List<TableChange> changes = new ArrayList<>();+ if (!Objects.equals(existingTable.comment(), newTable.getComment())) {+ changes.add(TableChange.updateComment(newTable.getComment()));+ }++ currentProperties.keySet().stream()+ .filter(+ key ->+ (key.startsWith(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX)+ || CatalogPropertiesUtil.IS_GENERIC.equals(key))+ && !updatedProperties.containsKey(key))+ .forEach(key -> changes.add(TableChange.removeProperty(key)));++ updatedProperties.forEach(+ (key, value) -> {+ String currentValue = currentProperties.get(key);+ if (!value.equals(currentValue)) {+ changes.add(TableChange.setProperty(key, value));+ }+ });++ try {+ catalog().asTableCatalog().alterTable(identifier, changes.toArray(new TableChange[0]));+ } catch (NoSuchTableException e) {+ throw new TableNotExistException(catalogName(), tablePath, e);+ } catch (Exception e) {+ throw new CatalogException(e);+ }+ }}diff --git a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/HiveSchemaAndTablePropertiesConverter.java b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/HiveSchemaAndTablePropertiesConverter.javaindex ca82a24622..9b8e5a39bb 100644--- a/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/HiveSchemaAndTablePropertiesConverter.java+++ b/flink-connector/flink/src/main/java/org/apache/gravitino/flink/connector/hive/HiveSchemaAndTablePropertiesConverter.java@@ -24,6 +24,7 @@ import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors;import javax.annotation.Nullable;+import org.apache.flink.table.catalog.CatalogPropertiesUtil;import org.apache.flink.table.catalog.ObjectPath;import org.apache.flink.table.catalog.hive.util.Constants;import org.apache.gravitino.catalog.hive.HiveConstants;@@ -108,6 +109,18 @@ public class HiveSchemaAndTablePropertiesConverter implements SchemaAndTablePropif (formatRaw != null) {properties.put(HiveConstants.FORMAT, formatRaw);}++ String connector = properties.get(FlinkGenericTableUtil.CONNECTOR);++ // remove connector from properties to keep compatibility with Flink's behavior+ if (connector != null) {+ Preconditions.checkArgument(+ "hive".equalsIgnoreCase(connector),+ "The connector type must be hive, but get %s",+ connector);+ properties.remove(FlinkGenericTableUtil.CONNECTOR);+ }+ properties.put(CatalogPropertiesUtil.IS_GENERIC, "false");return properties;}diff --git a/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/hive/TestFlinkGenericTableUtil.java b/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/hive/TestFlinkGenericTableUtil.javanew file mode 100644index 0000000000..2a78f8beb3--- /dev/null+++ b/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/hive/TestFlinkGenericTableUtil.java@@ -0,0 +1,139 @@+/*+ * 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.flink.connector.hive;++import com.google.common.collect.ImmutableMap;+import java.util.Collections;+import java.util.Map;+import org.apache.flink.table.api.DataTypes;+import org.apache.flink.table.api.Schema;+import org.apache.flink.table.catalog.CatalogPropertiesUtil;+import org.apache.flink.table.catalog.CatalogTable;+import org.apache.flink.table.catalog.Column;+import org.apache.flink.table.catalog.ResolvedCatalogTable;+import org.apache.flink.table.catalog.ResolvedSchema;+import org.apache.flink.table.factories.ManagedTableFactory;+import org.apache.gravitino.rel.Table;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++class TestFlinkGenericTableUtil {++ @Test+ void testGenericTableWhenCreate() {+ Assertions.assertTrue(FlinkGenericTableUtil.isGenericTableWhenCreate(null));+ Assertions.assertTrue(FlinkGenericTableUtil.isGenericTableWhenCreate(Collections.emptyMap()));+ Assertions.assertFalse(+ FlinkGenericTableUtil.isGenericTableWhenCreate(ImmutableMap.of("connector", "hive")));+ Assertions.assertTrue(+ FlinkGenericTableUtil.isGenericTableWhenCreate(ImmutableMap.of("connector", "kafka")));+ }++ @Test+ void testGenericTableWhenLoad() {+ Assertions.assertFalse(FlinkGenericTableUtil.isGenericTableWhenLoad(null));+ Assertions.assertTrue(+ FlinkGenericTableUtil.isGenericTableWhenLoad(ImmutableMap.of("is_generic", "true")));+ Assertions.assertTrue(+ FlinkGenericTableUtil.isGenericTableWhenLoad(+ ImmutableMap.of("is_generic", "true", "flink.connector", "hive")));+ Assertions.assertFalse(+ FlinkGenericTableUtil.isGenericTableWhenLoad(ImmutableMap.of("is_generic", "false")));+ Assertions.assertFalse(+ FlinkGenericTableUtil.isGenericTableWhenLoad(+ ImmutableMap.of("is_generic", "false", "flink.connector", "kafka")));+ Assertions.assertTrue(+ FlinkGenericTableUtil.isGenericTableWhenLoad(ImmutableMap.of("flink.connector", "kafka")));+ Assertions.assertTrue(+ FlinkGenericTableUtil.isGenericTableWhenLoad(+ ImmutableMap.of("flink.connector.type", "jdbc")));+ Assertions.assertFalse(FlinkGenericTableUtil.isGenericTableWhenLoad(Collections.emptyMap()));+ }++ @Test+ void testGenericTablePropertiesSerializationAddsIsGeneric() {+ ResolvedCatalogTable resolvedTable = createResolvedTable(Collections.emptyMap());++ Map<String, String> properties =+ FlinkGenericTableUtil.toGravitinoGenericTableProperties(resolvedTable);++ Assertions.assertEquals("true", properties.get(CatalogPropertiesUtil.IS_GENERIC));+ Assertions.assertTrue(+ properties.containsKey(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + "schema.0.name"));+ }++ @Test+ @SuppressWarnings("deprecation")+ void testGenericTablePropertiesAddsDefaultConnector() {+ ResolvedCatalogTable resolvedTable = createResolvedTable(Collections.emptyMap());++ Map<String, String> properties =+ FlinkGenericTableUtil.toGravitinoGenericTableProperties(resolvedTable);++ Assertions.assertEquals(+ ManagedTableFactory.DEFAULT_IDENTIFIER,+ properties.get(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + "connector"));+ }++ @Test+ void testToFlinkGenericTableRemoveDefaultConnector() {+ ResolvedCatalogTable resolvedTable = createResolvedTable(ImmutableMap.of("custom", "value"));+ Map<String, String> properties =+ FlinkGenericTableUtil.toGravitinoGenericTableProperties(resolvedTable);+ Assertions.assertEquals("default", properties.get("flink.connector"));++ CatalogTable catalogTable =+ FlinkGenericTableUtil.toFlinkGenericTable(+ new Table() {+ @Override+ public String name() {+ return "tbl";+ }++ @Override+ public org.apache.gravitino.rel.Column[] columns() {+ return new org.apache.gravitino.rel.Column[0];+ }++ @Override+ public Map<String, String> properties() {+ return properties;+ }++ @Override+ public org.apache.gravitino.Audit auditInfo() {+ return null;+ }+ });++ Assertions.assertFalse(catalogTable.getOptions().containsKey("connector"));+ Assertions.assertEquals("value", catalogTable.getOptions().get("custom"));+ }++ private static ResolvedCatalogTable createResolvedTable(Map<String, String> options) {+ Schema schema = Schema.newBuilder().column("id", DataTypes.INT()).build();+ CatalogTable table = CatalogTable.of(schema, "comment", Collections.emptyList(), options);+ ResolvedSchema resolvedSchema =+ new ResolvedSchema(+ Collections.singletonList(Column.physical("id", DataTypes.INT())),+ Collections.emptyList(),+ null);+ return new ResolvedCatalogTable(table, resolvedSchema);+ }+}diff --git a/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.java b/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.javaindex 17d8695cb7..ab196f6f2e 100644--- a/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.java+++ b/flink-connector/flink/src/test/java/org/apache/gravitino/flink/connector/integration/test/hive/FlinkHiveCatalogIT.java@@ -27,18 +27,24 @@ import com.google.common.collect.Lists;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.security.PrivilegedAction;+import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.SQLException;+import java.sql.Statement;import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.stream.Collectors;import org.apache.flink.configuration.Configuration;+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;import org.apache.flink.table.api.DataTypes;import org.apache.flink.table.api.EnvironmentSettings;import org.apache.flink.table.api.ResultKind;import org.apache.flink.table.api.TableEnvironment;import org.apache.flink.table.api.TableResult;import org.apache.flink.table.api.ValidationException;+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;import org.apache.flink.table.api.internal.TableEnvironmentImpl;import org.apache.flink.table.catalog.Catalog;import org.apache.flink.table.catalog.CatalogBaseTable;@@ -59,6 +65,9 @@ import org.apache.gravitino.flink.connector.hive.GravitinoHiveCatalog;import org.apache.gravitino.flink.connector.hive.GravitinoHiveCatalogFactoryOptions;import org.apache.gravitino.flink.connector.integration.test.FlinkCommonIT;import org.apache.gravitino.flink.connector.integration.test.utils.TestUtils;+import org.apache.gravitino.flink.connector.store.GravitinoCatalogStoreFactoryOptions;+import org.apache.gravitino.integration.test.container.ContainerSuite;+import org.apache.gravitino.integration.test.util.TestDatabaseName;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.expressions.transforms.Transform;@@ -80,15 +89,32 @@ import org.junit.jupiter.api.Test;public class FlinkHiveCatalogIT extends FlinkCommonIT {private static final String DEFAULT_HIVE_CATALOG = "test_flink_hive_schema_catalog";private static final String FLINK_USER_NAME = "gravitino";+ private static final String MYSQL_DATABASE = TestDatabaseName.FLINK_HIVE_CATALOG_IT.name();private static org.apache.gravitino.Catalog hiveCatalog;private static String hiveConfDir;+ private String mysqlUrl;+ private String mysqlUsername;+ private String mysqlPassword;+ private String mysqlDriver;+ private ContainerSuite containerSuite;+@Overrideprotected boolean supportsPrimaryKey() {return false;}+ @Override+ protected boolean supportColumnOperation() {+ return false;+ }++ @Override+ protected boolean supportTablePropertiesOperation() {+ return false;+ }+@BeforeAllvoid hiveStartUp() {initHiveConfDir();@@ -101,6 +127,27 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {metalake.dropCatalog(DEFAULT_HIVE_CATALOG, true);}+ @Override+ protected void initCatalogEnv() throws Exception {+ containerSuite = ContainerSuite.getInstance();+ containerSuite.startMySQLContainer(TestDatabaseName.FLINK_HIVE_CATALOG_IT);+ mysqlUrl =+ containerSuite.getMySQLContainer().getJdbcUrl(TestDatabaseName.FLINK_HIVE_CATALOG_IT);+ mysqlUsername = containerSuite.getMySQLContainer().getUsername();+ mysqlPassword = containerSuite.getMySQLContainer().getPassword();+ mysqlDriver =+ containerSuite+ .getMySQLContainer()+ .getDriverClassName(TestDatabaseName.FLINK_HIVE_CATALOG_IT);+ }++ @Override+ protected void stopCatalogEnv() throws Exception {+ if (containerSuite != null) {+ containerSuite.close();+ }+ }+protected void initDefaultHiveCatalog() {Preconditions.checkArgument(metalake != null, "metalake should not be null");hiveCatalog =@@ -316,6 +363,42 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {Assertions.assertFalse(metalake.catalogExists(catalogName));}+ @Test+ public void testStreamExecutionEnvironmentLoadsGravitinoCatalogStoreConfiguration() {+ String catalogName = "gravitino_hive_stream_env";+ if (metalake.catalogExists(catalogName)) {+ metalake.dropCatalog(catalogName, true);+ }++ metalake.createCatalog(+ catalogName,+ org.apache.gravitino.Catalog.Type.RELATIONAL,+ getProvider(),+ null,+ ImmutableMap.of(HiveConstants.METASTORE_URIS, hiveMetastoreUri));++ try {+ Configuration configuration = new Configuration();+ configuration.setString(+ "table.catalog-store.kind", GravitinoCatalogStoreFactoryOptions.GRAVITINO);+ configuration.setString(+ "table.catalog-store.gravitino.gravitino.metalake", GRAVITINO_METALAKE);+ configuration.setString("table.catalog-store.gravitino.gravitino.uri", gravitinoUri);++ StreamExecutionEnvironment env =+ StreamExecutionEnvironment.getExecutionEnvironment(configuration);+ EnvironmentSettings settings =+ EnvironmentSettings.newInstance().withConfiguration(configuration).build();+ StreamTableEnvironment streamTableEnv = StreamTableEnvironment.create(env, settings);++ Assertions.assertTrue(+ Arrays.asList(streamTableEnv.listCatalogs()).contains(catalogName),+ "StreamTableEnvironment should load Gravitino catalog store configs");+ } finally {+ metalake.dropCatalog(catalogName, true);+ }+ }+@Testpublic void testGetCatalogFromGravitino() {// list catalogs.@@ -362,7 +445,7 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {}@Test- public void testHivePartitionTable() {+ public void testRawHivePartitionTable() {String databaseName = "test_create_hive_partition_table_db";String tableName = "test_create_hive_partition_table";String comment = "test comment";@@ -381,7 +464,8 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {+ " COMMENT '%s' "+ " PARTITIONED BY (string_type, double_type)"+ " WITH ("- + "'%s' = '%s')",+ + "'%s' = '%s',"+ + "'connector'='hive')",tableName, comment, key, value);TestUtils.assertTableResult(result, ResultKind.SUCCESS);@@ -443,7 +527,7 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {}@Test- public void testCreateHiveTable() {+ public void testCreateRawHiveTable() {String databaseName = "test_create_hive_table_db";String tableName = "test_create_hive_table";String comment = "test comment";@@ -479,7 +563,8 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {+ " map_type MAP<INT, STRING> COMMENT 'map_type',"+ " struct_type ROW<k1 INT, k2 String>)"+ " COMMENT '%s' WITH ("- + "'%s' = '%s')",+ + "'%s' = '%s',"+ + "'connector'='hive')",tableName, comment, key, value);TestUtils.assertTableResult(result, ResultKind.SUCCESS);@@ -536,7 +621,7 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {catalog -> {TestUtils.assertTableResult(sql(- "CREATE TABLE %s (id STRING) WITH ('%s'='%s')",+ "CREATE TABLE %s (id STRING) WITH ('%s'='%s', 'connector'='hive')",tableName, Constants.SERDE_LIB_CLASS_NAME, customSerde),ResultKind.SUCCESS);TestUtils.assertTableResult(@@ -570,7 +655,7 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {catalog -> {TestUtils.assertTableResult(sql(- "CREATE TABLE %s (id INT) WITH ('%s'='%s', '%s'='%s')",+ "CREATE TABLE %s (id INT) WITH ('%s'='%s', '%s'='%s', 'connector'='hive')",tableName,Constants.SERDE_LIB_CLASS_NAME,customSerde,@@ -610,7 +695,8 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {Assertions.assertTrue(flinkCatalog.isPresent());HiveConf hiveConf = ((GravitinoHiveCatalog) flinkCatalog.get()).getHiveConf();TestUtils.assertTableResult(- sql("CREATE TABLE %s (id INT)", tableName), ResultKind.SUCCESS);+ sql("CREATE TABLE %s (id INT) WITH ('connector'='hive')", tableName),+ ResultKind.SUCCESS);TestUtils.assertTableResult(sql("INSERT INTO %s VALUES (1)", tableName),ResultKind.SUCCESS_WITH_CONTENT,@@ -782,6 +868,519 @@ public class FlinkHiveCatalogIT extends FlinkCommonIT {true);}+ @Test+ public void testGravitinoCreateRawHiveTableReadableByNativeHiveCatalog() {+ String databaseName = "test_native_read_raw_hive_db";+ String tableName = "raw_hive_table";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING) WITH ('connector'='hive')", tableName),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s ADD age INT", tableName), ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("INSERT INTO %s VALUES (1, 'a', 10)", tableName),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ withNativeHiveEnv(+ databaseName, env -> assertSingleRow(env, tableName, Row.of(1, "a", 10)));+ },+ true);+ }++ @Test+ public void testGravitinoCreateGenericJdbcTableReadableByNativeHiveCatalog() {+ String databaseName = "test_native_read_jdbc_db";+ String tableName = "generic_jdbc_table";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ createJdbcTable(tableName);+ try {+ TestUtils.assertTableResult(+ sql(+ "CREATE TABLE %s (id INT, name STRING) WITH ("+ + "'connector'='jdbc',"+ + "'url'='%s',"+ + "'table-name'='%s',"+ + "'username'='%s',"+ + "'password'='%s',"+ + "'driver'='%s')",+ tableName, mysqlUrl, tableName, mysqlUsername, mysqlPassword, mysqlDriver),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s ADD age INT", tableName), ResultKind.SUCCESS);+ alterJdbcTableAddColumn(tableName);+ TestUtils.assertTableResult(+ sql("INSERT INTO %s VALUES (1, 'a', 10)", tableName),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ withNativeHiveEnv(+ databaseName, env -> assertSingleRow(env, tableName, Row.of(1, "a", 10)));+ } finally {+ dropJdbcTable(tableName);+ }+ },+ true);+ }++ @Test+ public void testGravitinoCreatePaimonTableReadableByNativePaimonCatalog() {+ String databaseName = "test_native_read_paimon_db";+ String tableName = "paimon_table";+ String tablePath = paimonTablePath(databaseName, tableName);+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql(+ "CREATE TABLE %s (id INT, name STRING) WITH ("+ + "'connector'='paimon',"+ + "'path'='%s')",+ tableName, tablePath),+ ResultKind.SUCCESS);+ withNativePaimonEnv(+ databaseName,+ env -> {+ TestUtils.assertTableResult(+ env.executeSql(+ String.format("CREATE TABLE %s (id INT, name STRING)", tableName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ env.executeSql(String.format("ALTER TABLE %s ADD age INT", tableName)),+ ResultKind.SUCCESS);+ });+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s ADD age INT", tableName), ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("INSERT INTO %s VALUES (1, 'a', 10)", tableName),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ withNativePaimonEnv(+ databaseName, env -> assertSingleRow(env, tableName, Row.of(1, "a", 10)));+ },+ true);+ }++ @Test+ public void testNativeCreateRawHiveTableReadableByGravitino() {+ String databaseName = "test_gravitino_read_raw_hive_db";+ String tableName = "raw_hive_table";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ withNativeHiveEnv(+ databaseName,+ env -> {+ TestUtils.assertTableResult(+ env.executeSql(+ String.format(+ "CREATE TABLE %s (id INT, name STRING) WITH ('connector'='hive')",+ tableName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ env.executeSql(String.format("ALTER TABLE %s ADD age INT", tableName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ env.executeSql(String.format("INSERT INTO %s VALUES (1, 'a', 10)", tableName)),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ });+ assertSingleRow(tableEnv, tableName, Row.of(1, "a", 10));+ },+ true);+ }++ @Test+ public void testNativeCreateGenericJdbcTableReadableByGravitino() {+ String databaseName = "test_gravitino_read_jdbc_db";+ String tableName = "generic_jdbc_table";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ createJdbcTable(tableName);+ try {+ withNativeHiveEnv(+ databaseName,+ env -> {+ TestUtils.assertTableResult(+ env.executeSql(+ String.format(+ "CREATE TABLE %s (id INT, name STRING) WITH ("+ + "'connector'='jdbc',"+ + "'url'='%s',"+ + "'table-name'='%s',"+ + "'username'='%s',"+ + "'password'='%s',"+ + "'driver'='%s')",+ tableName,+ mysqlUrl,+ tableName,+ mysqlUsername,+ mysqlPassword,+ mysqlDriver)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ env.executeSql(String.format("ALTER TABLE %s ADD age INT", tableName)),+ ResultKind.SUCCESS);+ alterJdbcTableAddColumn(tableName);+ TestUtils.assertTableResult(+ env.executeSql(+ String.format("INSERT INTO %s VALUES (1, 'a', 10)", tableName)),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ });+ assertSingleRow(tableEnv, tableName, Row.of(1, "a", 10));+ } finally {+ dropJdbcTable(tableName);+ }+ },+ true);+ }++ @Test+ public void testNativeCreatePaimonTableReadableByGravitino() {+ String databaseName = "test_gravitino_read_paimon_db";+ String tableName = "paimon_table";+ String tablePath = paimonTablePath(databaseName, tableName);+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ withNativePaimonEnv(+ databaseName,+ env -> {+ TestUtils.assertTableResult(+ env.executeSql(+ String.format("CREATE TABLE %s (id INT, name STRING)", tableName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ env.executeSql(String.format("ALTER TABLE %s ADD age INT", tableName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ env.executeSql(String.format("INSERT INTO %s VALUES (1, 'a', 10)", tableName)),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ });+ TestUtils.assertTableResult(+ sql(+ "CREATE TABLE %s (id INT, name STRING, age INT) WITH ("+ + "'connector'='paimon',"+ + "'path'='%s')",+ tableName, tablePath),+ ResultKind.SUCCESS);+ assertSingleRow(tableEnv, tableName, Row.of(1, "a", 10));+ },+ true);+ }++ @Test+ @Override+ public void testCreateSimpleTable() {+ String databaseName = "test_create_no_partition_table_db";+ String tableName = "test_create_no_partition_table";+ String comment = "test comment";++ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TableResult result =+ sql(+ "CREATE TABLE %s "+ + "(string_type STRING COMMENT 'string_type', "+ + " double_type DOUBLE COMMENT 'double_type')"+ + " COMMENT '%s' WITH ('connector'='hive')",+ tableName, comment);+ TestUtils.assertTableResult(result, ResultKind.SUCCESS);++ Optional<Catalog> flinkCatalog = tableEnv.getCatalog(currentCatalog().name());+ Assertions.assertTrue(flinkCatalog.isPresent());+ try {+ CatalogBaseTable table =+ flinkCatalog.get().getTable(new ObjectPath(databaseName, tableName));+ Assertions.assertNotNull(table);+ Assertions.assertEquals(comment, table.getComment());++ CatalogTable catalogTable = (CatalogTable) table;+ Assertions.assertFalse(catalogTable.isPartitioned());+ } catch (TableNotExistException e) {+ Assertions.fail(e);+ }++ assertFlinkTableColumns(databaseName, tableName, "string_type", "double_type");++ TestUtils.assertTableResult(+ sql("INSERT INTO %s VALUES ('A', 1.0), ('B', 2.0)", tableName),+ ResultKind.SUCCESS_WITH_CONTENT,+ Row.of(-1L));+ TableResult selectResult = sql("SELECT * FROM %s ORDER BY string_type", tableName);+ Assertions.assertEquals(ResultKind.SUCCESS_WITH_CONTENT, selectResult.getResultKind());+ List<Row> actualRows = Lists.newArrayList(selectResult.collect());+ Assertions.assertEquals(2, actualRows.size());+ Assertions.assertTrue(hasRow(actualRows, "A", 1.0));+ Assertions.assertTrue(hasRow(actualRows, "B", 2.0));+ },+ true,+ supportDropCascade());+ }++ @Test+ public void testAlterRawHiveTableAddColumn() {+ String databaseName = "test_alter_raw_hive_table_db";+ String tableName = "test_alter_raw_hive_table";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING) WITH ('connector'='hive')", tableName),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s ADD age INT", tableName), ResultKind.SUCCESS);+ Column[] columns =+ catalog+ .asTableCatalog()+ .loadTable(NameIdentifier.of(databaseName, tableName))+ .columns();+ Assertions.assertEquals(3, columns.length);+ },+ true);+ }++ @Test+ public void testAlterRawHiveTableRenameColumn() {+ String databaseName = "test_alter_raw_hive_table_rename_db";+ String tableName = "test_alter_raw_hive_table_rename";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING) WITH ('connector'='hive')", tableName),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s RENAME id TO id_new", tableName), ResultKind.SUCCESS);+ Column[] columns =+ catalog+ .asTableCatalog()+ .loadTable(NameIdentifier.of(databaseName, tableName))+ .columns();+ Column[] expected =+ new Column[] {+ Column.of("id_new", Types.IntegerType.get(), null),+ Column.of("name", Types.StringType.get(), null)+ };+ assertColumns(expected, columns);+ },+ true);+ }++ @Test+ public void testAlterRawHiveTableDropColumn() {+ String databaseName = "test_alter_raw_hive_table_drop_db";+ String tableName = "test_alter_raw_hive_table_drop";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING) WITH ('connector'='hive')", tableName),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s DROP name", tableName), ResultKind.SUCCESS);+ Column[] columns =+ catalog+ .asTableCatalog()+ .loadTable(NameIdentifier.of(databaseName, tableName))+ .columns();+ Column[] expected = new Column[] {Column.of("id", Types.IntegerType.get(), null)};+ assertColumns(expected, columns);+ },+ true);+ }++ @Test+ public void testAlterGenericTableAddColumn() {+ String databaseName = "test_alter_generic_table_db";+ String tableName = "test_alter_generic_table";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING)", tableName), ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s ADD age INT", tableName), ResultKind.SUCCESS);+ assertFlinkTableColumns(databaseName, tableName, "id", "name", "age");+ },+ true);+ }++ @Test+ public void testAlterGenericTableRenameColumn() {+ String databaseName = "test_alter_generic_table_rename_db";+ String tableName = "test_alter_generic_table_rename";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING)", tableName), ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s RENAME id TO id_new", tableName), ResultKind.SUCCESS);+ assertFlinkTableColumns(databaseName, tableName, "id_new", "name");+ },+ true);+ }++ @Test+ public void testAlterGenericTableDropColumn() {+ String databaseName = "test_alter_generic_table_drop_db";+ String tableName = "test_alter_generic_table_drop";+ doWithSchema(+ currentCatalog(),+ databaseName,+ catalog -> {+ TestUtils.assertTableResult(+ sql("CREATE TABLE %s (id INT, name STRING)", tableName), ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ sql("ALTER TABLE %s DROP name", tableName), ResultKind.SUCCESS);+ assertFlinkTableColumns(databaseName, tableName, "id");+ },+ true);+ }++ private void assertFlinkTableColumns(+ String databaseName, String tableName, String... expectedColumnNames) {+ Optional<Catalog> flinkCatalog = tableEnv.getCatalog(currentCatalog().name());+ Assertions.assertTrue(flinkCatalog.isPresent());+ ObjectPath tablePath = new ObjectPath(databaseName, tableName);+ try {+ CatalogTable table = (CatalogTable) flinkCatalog.get().getTable(tablePath);+ List<String> actual =+ table.getUnresolvedSchema().getColumns().stream()+ .map(column -> column.getName())+ .collect(Collectors.toList());+ Assertions.assertEquals(Arrays.asList(expectedColumnNames), actual);+ } catch (TableNotExistException e) {+ Assertions.fail(e);+ }+ }++ private boolean hasRow(List<Row> rows, String name, double value) {+ return rows.stream()+ .anyMatch(+ row ->+ row.toString().contains("[" + name + ",")+ && row.toString().contains(String.valueOf(value)));+ }++ private void withNativeHiveEnv(+ String databaseName, java.util.function.Consumer<TableEnvironment> action) {+ EnvironmentSettings settings = EnvironmentSettings.newInstance().inBatchMode().build();+ TableEnvironment nativeEnv = TableEnvironment.create(settings);+ try {+ TestUtils.assertTableResult(+ nativeEnv.executeSql(+ String.format(+ "CREATE CATALOG native_hive WITH ('type'='hive', 'hive-conf-dir'='%s')",+ hiveConfDir)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ nativeEnv.executeSql("USE CATALOG native_hive"), ResultKind.SUCCESS);+ if (databaseName != null) {+ TestUtils.assertTableResult(+ nativeEnv.executeSql(String.format("CREATE DATABASE IF NOT EXISTS %s", databaseName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ nativeEnv.executeSql("USE " + databaseName), ResultKind.SUCCESS);+ }+ action.accept(nativeEnv);+ } finally {+ ((TableEnvironmentImpl) nativeEnv).getCatalogManager().close();+ }+ }++ private void withNativePaimonEnv(+ String databaseName, java.util.function.Consumer<TableEnvironment> action) {+ EnvironmentSettings settings = EnvironmentSettings.newInstance().inBatchMode().build();+ TableEnvironment nativeEnv = TableEnvironment.create(settings);+ try {+ TestUtils.assertTableResult(+ nativeEnv.executeSql(+ String.format(+ "CREATE CATALOG native_paimon WITH ('type'='paimon', 'warehouse'='%s')",+ warehouse)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ nativeEnv.executeSql("USE CATALOG native_paimon"), ResultKind.SUCCESS);+ if (databaseName != null) {+ TestUtils.assertTableResult(+ nativeEnv.executeSql(String.format("CREATE DATABASE IF NOT EXISTS %s", databaseName)),+ ResultKind.SUCCESS);+ TestUtils.assertTableResult(+ nativeEnv.executeSql("USE " + databaseName), ResultKind.SUCCESS);+ }+ action.accept(nativeEnv);+ } finally {+ ((TableEnvironmentImpl) nativeEnv).getCatalogManager().close();+ }+ }++ private void assertSingleRow(TableEnvironment env, String tableName, Row expectedRow) {+ TableResult result = env.executeSql("SELECT * FROM " + tableName);+ List<Row> rows = Lists.newArrayList(result.collect());+ Assertions.assertEquals(1, rows.size());+ Assertions.assertEquals(expectedRow, rows.get(0));+ }++ private void createJdbcTable(String tableName) {+ try (Connection connection =+ DriverManager.getConnection(mysqlUrl, mysqlUsername, mysqlPassword);+ Statement statement = connection.createStatement()) {+ statement.execute(String.format("CREATE DATABASE IF NOT EXISTS %s", MYSQL_DATABASE));+ statement.execute(String.format("DROP TABLE IF EXISTS %s.%s", MYSQL_DATABASE, tableName));+ statement.execute(+ String.format(+ "CREATE TABLE %s.%s (id INT, name VARCHAR(32))", MYSQL_DATABASE, tableName));+ } catch (SQLException e) {+ throw new RuntimeException("Failed to create JDBC table " + tableName, e);+ }+ }++ private void alterJdbcTableAddColumn(String tableName) {+ try (Connection connection =+ DriverManager.getConnection(mysqlUrl, mysqlUsername, mysqlPassword);+ Statement statement = connection.createStatement()) {+ statement.execute(+ String.format("ALTER TABLE %s.%s ADD COLUMN age INT", MYSQL_DATABASE, tableName));+ } catch (SQLException e) {+ throw new RuntimeException("Failed to alter JDBC table " + tableName, e);+ }+ }++ private String paimonTablePath(String databaseName, String tableName) {+ return String.format("%s/%s.db/%s", warehouse, databaseName, tableName);+ }++ private void dropJdbcTable(String tableName) {+ try (Connection connection =+ DriverManager.getConnection(mysqlUrl, mysqlUsername, mysqlPassword);+ Statement statement = connection.createStatement()) {+ statement.execute(String.format("DROP TABLE IF EXISTS %s.%s", MYSQL_DATABASE, tableName));+ } catch (SQLException e) {+ throw new RuntimeException("Failed to drop JDBC table " + tableName, e);+ }+ }+@Overrideprotected Map<String, String> getCreateSchemaProps(String schemaName) {return ImmutableMap.of("location", warehouse + "/" + schemaName);diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.javaindex 8f0de42219..515e79c007 100644--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.java+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/TestDatabaseName.java@@ -124,4 +124,5 @@ public enum TestDatabaseName {return this.name().toLowerCase();}},+ FLINK_HIVE_CATALOG_IT,}