Skip to content

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

[#131] feat(catalog) Hive catalog supports alterTable operation (#132)

mchades42fb899c5352
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java
index e171701710..705b887486 100644
--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java
@@ -4,12 +4,14 @@
*/
package com.datastrato.graviton.catalog.hive;
+import static com.datastrato.graviton.catalog.hive.HiveTable.HMS_TABLE_COMMENT;
import static com.datastrato.graviton.catalog.hive.HiveTable.SUPPORT_TABLE_TYPES;
import static org.apache.hadoop.hive.metastore.TableType.EXTERNAL_TABLE;
import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
import com.datastrato.graviton.catalog.CatalogOperations;
+import com.datastrato.graviton.catalog.hive.converter.ToHiveType;
import com.datastrato.graviton.exceptions.NoSuchNamespaceException;
import com.datastrato.graviton.exceptions.NoSuchSchemaException;
import com.datastrato.graviton.exceptions.NoSuchTableException;
@@ -19,6 +21,7 @@ import com.datastrato.graviton.exceptions.TableAlreadyExistsException;
import com.datastrato.graviton.meta.AuditInfo;
import com.datastrato.graviton.meta.CatalogEntity;
import com.datastrato.graviton.meta.rel.BaseSchema;
+import com.datastrato.graviton.meta.rel.BaseTable;
import com.datastrato.graviton.rel.Column;
import com.datastrato.graviton.rel.SchemaChange;
import com.datastrato.graviton.rel.SupportsSchemas;
@@ -38,8 +41,10 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.UnknownDBException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.thrift.TException;
@@ -538,9 +543,207 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
* @throws IllegalArgumentException This exception will not be thrown in this method.
*/
@Override
- public Table alterTable(NameIdentifier ident, TableChange... changes)
+ public Table alterTable(NameIdentifier tableIdent, TableChange... changes)
throws NoSuchTableException, IllegalArgumentException {
- throw new UnsupportedOperationException("Not support alter Hive table yet");
+ Preconditions.checkArgument(
+ !tableIdent.name().isEmpty(), "Cannot create table with empty name");
+
+ NameIdentifier schemaIdent = NameIdentifier.of(tableIdent.namespace().levels());
+ Preconditions.checkArgument(
+ isValidNamespace(schemaIdent.namespace()),
+ String.format(
+ "Cannot support invalid namespace in Hive Metastore: %s", schemaIdent.namespace()));
+
+ try {
+ // TODO(@Minghuang): require a table lock to avoid race condition
+ HiveTable table = (HiveTable) loadTable(tableIdent);
+ org.apache.hadoop.hive.metastore.api.Table alteredHiveTable = table.toInnerTable();
+
+ for (TableChange change : changes) {
+ // Table change
+ if (change instanceof TableChange.RenameTable) {
+ doRenameTable(alteredHiveTable, (TableChange.RenameTable) change);
+
+ } else if (change instanceof TableChange.UpdateComment) {
+ doUpdateComment(alteredHiveTable, (TableChange.UpdateComment) change);
+
+ } else if (change instanceof TableChange.SetProperty) {
+ doSetProperty(alteredHiveTable, (TableChange.SetProperty) change);
+
+ } else if (change instanceof TableChange.RemoveProperty) {
+ doRemoveProperty(alteredHiveTable, (TableChange.RemoveProperty) change);
+
+ } else if (change instanceof TableChange.ColumnChange) {
+ // Column change
+ StorageDescriptor sd = alteredHiveTable.getSd();
+ List<FieldSchema> cols = sd.getCols();
+
+ if (change instanceof TableChange.AddColumn) {
+ doAddColumn(cols, (TableChange.AddColumn) change);
+
+ } else if (change instanceof TableChange.DeleteColumn) {
+ doDeleteColumn(cols, (TableChange.DeleteColumn) change);
+
+ } else if (change instanceof TableChange.RenameColumn) {
+ doRenameColumn(cols, (TableChange.RenameColumn) change);
+
+ } else if (change instanceof TableChange.UpdateColumnComment) {
+ doUpdateColumnComment(cols, (TableChange.UpdateColumnComment) change);
+
+ } else if (change instanceof TableChange.UpdateColumnPosition) {
+ doUpdateColumnPosition(cols, (TableChange.UpdateColumnPosition) change);
+
+ } else if (change instanceof TableChange.UpdateColumnType) {
+ doUpdateColumnType(cols, (TableChange.UpdateColumnType) change);
+
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported column change type: " + change.getClass().getSimpleName());
+ }
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported table change type: " + change.getClass().getSimpleName());
+ }
+ }
+
+ clientPool.run(
+ c -> {
+ c.alter_table(schemaIdent.name(), tableIdent.name(), alteredHiveTable);
+ return null;
+ });
+
+ // TODO(@Minghuang). We should also update the customized HiveTable entity fields into our own
+ // if necessary
+ HiveTable.Builder builder = new HiveTable.Builder();
+ builder =
+ builder
+ .withId((Long) table.fields().get(BaseTable.ID))
+ .withSchemaId((Long) table.fields().get(BaseTable.SCHEMA_ID))
+ .withName(alteredHiveTable.getTableName())
+ .withNameSpace(tableIdent.namespace())
+ .withAuditInfo(
+ /* TODO(@Minghuang): Fetch audit info from underlying storage */
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .build());
+ HiveTable alteredTable = HiveTable.fromInnerTable(alteredHiveTable, builder);
+ LOG.info("Altered Hive table {} in Hive Metastore", tableIdent.name());
+
+ return alteredTable;
+
+ } catch (NoSuchObjectException e) {
+ throw new NoSuchTableException(
+ String.format("Hive table does not exist: %s in Hive Metastore", tableIdent.name()), e);
+ } catch (TException | InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private int columnPosition(List<FieldSchema> columns, TableChange.ColumnPosition position) {
+ if (position == null) {
+ // add to the end by default
+ return columns.size();
+ } else if (position instanceof TableChange.After) {
+ String afterColumn = ((TableChange.After) position).getColumn();
+ return indexOfColumn(columns, afterColumn) + 1;
+ }
+ return 0;
+ }
+
+ /**
+ * Returns the index of a column in the given list of FieldSchema objects, based on the field
+ * name.
+ *
+ * @param columns The list of Hive columns.
+ * @param fieldName The name of the field to be searched.
+ * @return The index of the column if found, otherwise -1.
+ */
+ private int indexOfColumn(List<FieldSchema> columns, String fieldName) {
+ return columns.stream()
+ .map(FieldSchema::getName)
+ .collect(Collectors.toList())
+ .indexOf(fieldName);
+ }
+
+ private void doRenameTable(
+ org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.RenameTable change) {
+ hiveTable.setTableName(change.getNewName());
+ }
+
+ private void doUpdateComment(
+ org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.UpdateComment change) {
+ Map<String, String> parameters = hiveTable.getParameters();
+ parameters.put(HMS_TABLE_COMMENT, change.getNewComment());
+ }
+
+ private void doSetProperty(
+ org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.SetProperty change) {
+ Map<String, String> parameters = hiveTable.getParameters();
+ parameters.put(change.getProperty(), change.getValue());
+ }
+
+ private void doRemoveProperty(
+ org.apache.hadoop.hive.metastore.api.Table hiveTable, TableChange.RemoveProperty change) {
+ Map<String, String> parameters = hiveTable.getParameters();
+ parameters.remove(change.getProperty());
+ }
+
+ void doAddColumn(List<FieldSchema> cols, TableChange.AddColumn change) {
+ cols.add(
+ columnPosition(cols, change.getPosition()),
+ new FieldSchema(
+ change.fieldNames()[0],
+ change.getDataType().accept(ToHiveType.INSTANCE).getQualifiedName(),
+ change.getComment()));
+ }
+
+ private void doDeleteColumn(List<FieldSchema> cols, TableChange.DeleteColumn change) {
+ String columnName = change.fieldNames()[0];
+ if (!cols.removeIf(c -> c.getName().equals(columnName)) && !change.getIfExists()) {
+ throw new IllegalArgumentException("DeleteColumn does not exist: " + columnName);
+ }
+ }
+
+ private void doRenameColumn(List<FieldSchema> cols, TableChange.RenameColumn change) {
+ String columnName = change.fieldNames()[0];
+ if (indexOfColumn(cols, columnName) == -1) {
+ throw new IllegalArgumentException("RenameColumn does not exist: " + columnName);
+ }
+
+ String newName = change.getNewName();
+ if (indexOfColumn(cols, newName) != -1) {
+ throw new IllegalArgumentException("Column already exists: " + newName);
+ }
+ cols.get(indexOfColumn(cols, columnName)).setName(newName);
+ }
+
+ private void doUpdateColumnComment(
+ List<FieldSchema> cols, TableChange.UpdateColumnComment change) {
+ cols.get(indexOfColumn(cols, change.fieldNames()[0])).setComment(change.getNewComment());
+ }
+
+ private void doUpdateColumnPosition(
+ List<FieldSchema> cols, TableChange.UpdateColumnPosition change) {
+ String columnName = change.fieldNames()[0];
+ int sourceIndex = indexOfColumn(cols, columnName);
+ if (sourceIndex == -1) {
+ throw new IllegalArgumentException("UpdateColumnPosition does not exist: " + columnName);
+ }
+
+ // update column position: remove then add to given position
+ FieldSchema hiveColumn = cols.remove(sourceIndex);
+ cols.add(columnPosition(cols, change.getPosition()), hiveColumn);
+ }
+
+ private void doUpdateColumnType(List<FieldSchema> cols, TableChange.UpdateColumnType change) {
+ String columnName = change.fieldNames()[0];
+ int indexOfColumn = indexOfColumn(cols, columnName);
+ if (indexOfColumn == -1) {
+ throw new IllegalArgumentException("UpdateColumnType does not exist: " + columnName);
+ }
+ cols.get(indexOfColumn)
+ .setType(change.getNewDataType().accept(ToHiveType.INSTANCE).getQualifiedName());
}
/**
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java
index f0441118e8..e3768c4d12 100644
--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java
@@ -11,6 +11,7 @@ import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.catalog.hive.converter.FromHiveType;
import com.datastrato.graviton.catalog.hive.converter.ToHiveType;
import com.datastrato.graviton.meta.rel.BaseTable;
+import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.Set;
@@ -43,6 +44,10 @@ public class HiveTable extends BaseTable {
private TableType tableType;
+ private String location;
+
+ private int createTime;
+
private HiveTable() {}
/**
@@ -68,6 +73,11 @@ public class HiveTable extends BaseTable {
.withComment(f.getComment())
.build())
.toArray(HiveColumn[]::new))
+ .withOutputFormat(table.getSd().getOutputFormat())
+ .withInputFormat(table.getSd().getInputFormat())
+ .withSerLib(table.getSd().getSerdeInfo().getSerializationLib())
+ .withLocation(table.getSd().getLocation())
+ .withCreateTime(table.getCreateTime())
.build();
}
@@ -84,6 +94,9 @@ public class HiveTable extends BaseTable {
hiveTable.setOwner(auditInfo.creator());
hiveTable.setSd(buildStorageDescriptor());
hiveTable.setTableType(String.valueOf(tableType));
+ hiveTable.setParameters(properties);
+ hiveTable.setCreateTime(createTime);
+ hiveTable.setPartitionKeys(Lists.newArrayList() /* TODO(Minghuang): Add partition support */);
return hiveTable;
}
@@ -99,6 +112,7 @@ public class HiveTable extends BaseTable {
c.dataType().accept(ToHiveType.INSTANCE).getQualifiedName(),
c.comment()))
.collect(Collectors.toList()));
+ sd.setLocation(location);
sd.setInputFormat(inputFormat);
sd.setOutputFormat(outputFormat);
sd.setSerdeInfo(buildSerDeInfo());
@@ -131,6 +145,10 @@ public class HiveTable extends BaseTable {
private TableType tableType;
+ private String location;
+
+ private int createTime;
+
/**
* Sets the input format for the HiveTable.
*
@@ -169,6 +187,16 @@ public class HiveTable extends BaseTable {
return this;
}
+ public Builder withLocation(String location) {
+ this.location = location;
+ return this;
+ }
+
+ public Builder withCreateTime(int createTime) {
+ this.createTime = createTime;
+ return this;
+ }
+
/**
* Internal method to build a HiveTable instance using the provided values.
*
@@ -188,6 +216,8 @@ public class HiveTable extends BaseTable {
hiveTable.inputFormat = inputFormat;
hiveTable.outputFormat = outputFormat;
hiveTable.serLib = serLib;
+ hiveTable.location = location;
+ hiveTable.createTime = createTime;
hiveTable.tableType = tableType == null ? MANAGED_TABLE : tableType;
// HMS put table comment in parameters
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveTableTest.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveTableTest.java
index cb7659b118..bf7e178e3a 100644
--- a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveTableTest.java
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveTableTest.java
@@ -12,6 +12,7 @@ import com.datastrato.graviton.meta.AuditInfo;
import com.datastrato.graviton.meta.CatalogEntity;
import com.datastrato.graviton.rel.Column;
import com.datastrato.graviton.rel.Table;
+import com.datastrato.graviton.rel.TableChange;
import com.google.common.collect.Maps;
import io.substrait.type.TypeCreator;
import java.time.Instant;
@@ -179,4 +180,98 @@ public class HiveTableTest extends MiniHiveMetastoreService {
Assertions.assertTrue(
exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));
}
+
+ @Test
+ public void testAlterHiveTable() {
+ // create a table with random name
+ NameIdentifier tableIdentifier =
+ NameIdentifier.of(META_LAKE_NAME, hiveCatalog.name(), hiveSchema.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ HiveColumn col1 =
+ new HiveColumn.Builder()
+ .withName("col_1")
+ .withType(TypeCreator.NULLABLE.I8)
+ .withComment(HIVE_COMMENT)
+ .build();
+ HiveColumn col2 =
+ new HiveColumn.Builder()
+ .withName("col_2")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(HIVE_COMMENT)
+ .build();
+ Column[] columns = new Column[] {col1, col2};
+
+ hiveCatalog.asTableCatalog().createTable(tableIdentifier, columns, HIVE_COMMENT, properties);
+ Assertions.assertTrue(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));
+
+ // test alter
+ hiveCatalog
+ .asTableCatalog()
+ .alterTable(
+ tableIdentifier,
+ TableChange.rename("test_hive_table_new"),
+ TableChange.updateComment(HIVE_COMMENT + "_new"),
+ TableChange.removeProperty("key1"),
+ TableChange.setProperty("key2", "val2_new"),
+ // columns current format: [col_1:I8:comment, col_2:DATE:comment]
+ TableChange.addColumn(new String[] {"col_3"}, TypeCreator.NULLABLE.STRING),
+ // columns current format: [col_1:I8:comment, col_2:DATE:comment, col_3:STRING:null]
+ TableChange.renameColumn(new String[] {"col_2"}, "col_2_new"),
+ // columns current format: [col_1:I8:comment, col_2_new:DATE:comment, col_3:STRING:null]
+ TableChange.updateColumnComment(new String[] {"col_1"}, HIVE_COMMENT + "_new"),
+ // columns current format: [col_1:I8:comment_new, col_2_new:DATE:comment,
+ // col_3:STRING:null]
+ TableChange.updateColumnType(new String[] {"col_1"}, TypeCreator.NULLABLE.I32),
+ // columns current format: [col_1:I32:comment_new, col_2_new:DATE:comment,
+ // col_3:STRING:null]
+ TableChange.updateColumnPosition(
+ new String[] {"col_2_new"}, TableChange.ColumnPosition.first())
+ // columns current: [col_2_new:DATE:comment, col_1:I32:comment_new, col_3:STRING:null]
+ );
+ Table alteredTable =
+ hiveCatalog
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of(tableIdentifier.namespace(), "test_hive_table_new"));
+
+ Assertions.assertEquals(HIVE_COMMENT + "_new", alteredTable.comment());
+ Assertions.assertFalse(alteredTable.properties().containsKey("key1"));
+ Assertions.assertEquals(alteredTable.properties().get("key2"), "val2_new");
+
+ Column[] expected =
+ new Column[] {
+ new HiveColumn.Builder()
+ .withName("col_2_new")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(HIVE_COMMENT)
+ .build(),
+ new HiveColumn.Builder()
+ .withName("col_1")
+ .withType(TypeCreator.NULLABLE.I32)
+ .withComment(HIVE_COMMENT + "_new")
+ .build(),
+ new HiveColumn.Builder()
+ .withName("col_3")
+ .withType(TypeCreator.NULLABLE.STRING)
+ .withComment(null)
+ .build()
+ };
+ Assertions.assertArrayEquals(expected, alteredTable.columns());
+
+ // test delete column change
+ hiveCatalog
+ .asTableCatalog()
+ .alterTable(
+ NameIdentifier.of(tableIdentifier.namespace(), "test_hive_table_new"),
+ TableChange.deleteColumn(new String[] {"col_1"}, false));
+ alteredTable =
+ hiveCatalog
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of(tableIdentifier.namespace(), "test_hive_table_new"));
+ expected =
+ Arrays.stream(expected).filter(c -> !"col_1".equals(c.name())).toArray(Column[]::new);
+ Assertions.assertArrayEquals(expected, alteredTable.columns());
+ }
}