Skip to content

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

[#61] feat(catalog): Maintain the tables in the Hive Using HiveCatalog (#111)

mchadesf0670bd67b98
diff --git a/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java b/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java
index a7c26f5483..3127add350 100644
--- a/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java
+++ b/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java
@@ -51,7 +51,7 @@ public interface SupportsSchemas {
* Check if a schema exists.
*
* <p>If an entity such as a table, view exists, its parent namespaces must also exist. For
- * example, if table a.b.t exists, this method invoked as schemaExists(a) must return true.
+ * example, if table a.b.t exists, this method invoked as schemaExists(a.b) must return true.
*
* @param ident The name identifier of the schema.
* @return True if the schema exists, false otherwise.
diff --git a/catalog-hive/build.gradle.kts b/catalog-hive/build.gradle.kts
index e86f273a51..aa4181d13a 100644
--- a/catalog-hive/build.gradle.kts
+++ b/catalog-hive/build.gradle.kts
@@ -64,6 +64,12 @@ dependencies {
exclude("*")
}
+ implementation(libs.substrait.java.core) {
+ exclude("org.slf4j")
+ exclude("com.fasterxml.jackson.core")
+ exclude("com.fasterxml.jackson.datatype")
+ }
+
implementation(libs.slf4j.api)
implementation(libs.guava)
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java
index adec939ede..15572c58d1 100644
--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java
@@ -7,6 +7,7 @@ package com.datastrato.graviton.catalog.hive;
import com.datastrato.graviton.catalog.BaseCatalog;
import com.datastrato.graviton.catalog.CatalogOperations;
import com.datastrato.graviton.rel.SupportsSchemas;
+import com.datastrato.graviton.rel.TableCatalog;
import java.util.Map;
public class HiveCatalog extends BaseCatalog<HiveCatalog> {
@@ -27,4 +28,9 @@ public class HiveCatalog extends BaseCatalog<HiveCatalog> {
public SupportsSchemas asSchemas() {
return (HiveCatalogOperations) ops();
}
+
+ @Override
+ public TableCatalog asTableCatalog() {
+ return (HiveCatalogOperations) ops();
+ }
}
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 72b202abdd..16cd1f7285 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,24 +4,38 @@
*/
package com.datastrato.graviton.catalog.hive;
+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.exceptions.NoSuchNamespaceException;
import com.datastrato.graviton.exceptions.NoSuchSchemaException;
+import com.datastrato.graviton.exceptions.NoSuchTableException;
import com.datastrato.graviton.exceptions.NonEmptySchemaException;
import com.datastrato.graviton.exceptions.SchemaAlreadyExistsException;
+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.rel.Column;
import com.datastrato.graviton.rel.SchemaChange;
import com.datastrato.graviton.rel.SupportsSchemas;
+import com.datastrato.graviton.rel.Table;
+import com.datastrato.graviton.rel.TableCatalog;
+import com.datastrato.graviton.rel.TableChange;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Instant;
+import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.hadoop.conf.Configuration;
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.InvalidOperationException;
@@ -32,7 +46,7 @@ import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas {
+public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas, TableCatalog {
public static final Logger LOG = LoggerFactory.getLogger(HiveCatalogOperations.class);
@@ -149,7 +163,7 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
public HiveSchema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {
Preconditions.checkArgument(
!ident.name().isEmpty(),
- String.format("Cannot create schema with invalid name: %s", ident.name()));
+ String.format("Cannot load schema with invalid name: %s", ident.name()));
Preconditions.checkArgument(
isValidNamespace(ident.namespace()),
String.format("Cannot support invalid namespace in Hive Metastore: %s", ident.namespace()));
@@ -258,7 +272,7 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
HiveSchema hiveSchema = HiveSchema.fromInnerDB(alteredDatabase, builder);
LOG.info("Altered Hive schema (database) {} in Hive Metastore", ident.name());
- // todo(xun): hive dose not support renaming database name directly,
+ // todo(xun): hive does not support renaming database name directly,
// perhaps we can use namespace to mapping the database names indirectly
return hiveSchema;
@@ -310,6 +324,191 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
}
}
+ @Override
+ public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
+ NameIdentifier schemaIdent = NameIdentifier.of(namespace.levels());
+ if (!schemaExists(schemaIdent)) {
+ throw new NoSuchSchemaException("Schema (database) does not exist " + namespace);
+ }
+
+ try {
+ List<NameIdentifier> tables = Lists.newArrayList();
+
+ for (TableType tableType : SUPPORT_TABLE_TYPES) {
+ tables.addAll(
+ clientPool.run(
+ c ->
+ c.getTables(schemaIdent.name(), "*", tableType).stream()
+ .map(tb -> NameIdentifier.of(namespace, tb))
+ .collect(Collectors.toList())));
+ }
+
+ return tables.toArray(new NameIdentifier[0]);
+ } catch (TException e) {
+ throw new RuntimeException(
+ "Failed to list all tables under under namespace : " + namespace + " in Hive Metastore",
+ e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Table loadTable(NameIdentifier tableIdent) throws NoSuchTableException {
+ Preconditions.checkArgument(!tableIdent.name().isEmpty(), "Cannot load 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()));
+
+ HiveSchema schema = loadSchema(schemaIdent);
+ try {
+ org.apache.hadoop.hive.metastore.api.Table hiveTable =
+ clientPool.run(c -> c.getTable(schemaIdent.name(), tableIdent.name()));
+ HiveTable.Builder builder = new HiveTable.Builder();
+
+ // TODO: We should also fetch the customized HiveTable entity fields from our own
+ // underlying storage, like id, auditInfo, etc.
+
+ builder =
+ builder
+ .withId(1L /* TODO: Fetch id from underlying storage */)
+ .withSchemaId((Long) schema.fields().get(BaseSchema.ID))
+ .withName(tableIdent.name())
+ .withNameSpace(tableIdent.namespace())
+ .withAuditInfo(
+ /* TODO: Fetch audit info from underlying storage */
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .build());
+ HiveTable table = HiveTable.fromInnerTable(hiveTable, builder);
+
+ LOG.info("Loaded Hive table {} from Hive Metastore ", tableIdent.name());
+
+ return table;
+ } catch (TException e) {
+ throw new NoSuchTableException(
+ String.format("Hive table does not exist: %s in Hive Metastore", tableIdent.name()), e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Table createTable(
+ NameIdentifier tableIdent, Column[] columns, String comment, Map<String, String> properties)
+ throws NoSuchSchemaException, TableAlreadyExistsException {
+ 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 {
+ HiveSchema schema = loadSchema(schemaIdent);
+
+ HiveTable table =
+ new HiveTable.Builder()
+ .withId(1L /* TODO: Use ID generator*/)
+ .withSchemaId((Long) schema.fields().get(BaseSchema.ID))
+ .withName(tableIdent.name())
+ .withNameSpace(tableIdent.namespace())
+ .withColumns(columns)
+ .withComment(comment)
+ .withProperties(properties)
+ .withAuditInfo(
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
+ clientPool.run(
+ c -> {
+ c.createTable(table.toInnerTable());
+ return null;
+ });
+
+ // TODO. We should also store the customized HiveTable entity fields into our own
+ // underlying storage, like id, auditInfo, etc.
+
+ LOG.info("Created Hive table {} in Hive Metastore", tableIdent.name());
+
+ return table;
+
+ } catch (AlreadyExistsException e) {
+ throw new TableAlreadyExistsException("Table already exists: " + tableIdent.name(), e);
+ } catch (TException e) {
+ throw new RuntimeException(
+ "Failed to create Hive table " + tableIdent.name() + " in Hive Metastore", e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Table alterTable(NameIdentifier ident, TableChange... changes)
+ throws NoSuchTableException, IllegalArgumentException {
+ throw new UnsupportedOperationException("Not support alter Hive table yet");
+ }
+
+ @Override
+ public boolean dropTable(NameIdentifier tableIdent) {
+ return dropHiveTable(tableIdent, false, false);
+ }
+
+ @Override
+ public boolean purgeTable(NameIdentifier tableIdent) throws UnsupportedOperationException {
+ HiveTable table = (HiveTable) loadTable(tableIdent);
+ if (EXTERNAL_TABLE == table.getTableType()) {
+ throw new UnsupportedOperationException("Cannot purge Hive table with type EXTERNAL_TABLE");
+ }
+ return dropHiveTable(tableIdent, true, true);
+ }
+
+ private boolean dropHiveTable(NameIdentifier tableIdent, boolean deleteData, boolean ifPurge) {
+ Preconditions.checkArgument(!tableIdent.name().isEmpty(), "Cannot drop 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 {
+ clientPool.run(
+ c -> {
+ c.dropTable(schemaIdent.name(), tableIdent.name(), deleteData, false, ifPurge);
+ return null;
+ });
+
+ // TODO. we should also delete the Hive table from our own underlying storage
+
+ LOG.info("Dropped Hive table {}", tableIdent.name());
+ return true;
+
+ } catch (NoSuchObjectException e) {
+ LOG.warn("Hive table {} does not exist in Hive Metastore", tableIdent.name());
+ return false;
+ } catch (TException e) {
+ throw new RuntimeException(
+ "Failed to drop Hive table " + tableIdent.name() + " in Hive Metastore", e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Valid namespace of Hive schema
+ *
+ * @param namespace of Hive scheme
+ * @return true if catalog name equals current
+ */
public boolean isValidNamespace(Namespace namespace) {
return namespace.levels().length == 2 && namespace.level(1).equals(entity.name());
}
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.java
new file mode 100644
index 0000000000..0f89acaa0c
--- /dev/null
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.hive;
+
+import com.datastrato.graviton.meta.rel.BaseColumn;
+
+public class HiveColumn extends BaseColumn {
+
+ private HiveColumn() {}
+
+ public static class Builder extends BaseColumnBuilder<Builder, HiveColumn> {
+
+ @Override
+ protected HiveColumn internalBuild() {
+ HiveColumn hiveColumn = new HiveColumn();
+
+ hiveColumn.name = name;
+ hiveColumn.comment = comment;
+ hiveColumn.dataType = dataType;
+ return hiveColumn;
+ }
+ }
+}
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
new file mode 100644
index 0000000000..4ef64f1fce
--- /dev/null
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.hive;
+
+import static org.apache.hadoop.hive.metastore.TableType.EXTERNAL_TABLE;
+import static org.apache.hadoop.hive.metastore.TableType.MANAGED_TABLE;
+
+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.Sets;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.stream.Collectors;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.SerDeInfo;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.metastore.api.Table;
+
+/** A Hive Table entity */
+@ToString
+@Getter
+public class HiveTable extends BaseTable {
+
+ public static final Set<TableType> SUPPORT_TABLE_TYPES =
+ Sets.newHashSet(MANAGED_TABLE, EXTERNAL_TABLE);
+ public static final String HMS_TABLE_COMMENT = "comment";
+
+ private String inputFormat;
+
+ private String outputFormat;
+
+ private String serLib;
+
+ private TableType tableType;
+
+ private HiveTable() {}
+
+ public static HiveTable fromInnerTable(Table table, Builder builder) {
+
+ return builder
+ .withComment(table.getParameters().get(HMS_TABLE_COMMENT))
+ .withProperties(table.getParameters())
+ .withTableType(TableType.valueOf(table.getTableType()))
+ .withColumns(
+ table.getSd().getCols().stream()
+ .map(
+ f ->
+ new HiveColumn.Builder()
+ .withName(f.getName())
+ .withType(FromHiveType.convert(f.getType()))
+ .withComment(f.getComment())
+ .build())
+ .toArray(HiveColumn[]::new))
+ .build();
+ }
+
+ public Table toInnerTable() {
+ Table hiveTable = new Table();
+
+ hiveTable.setTableName(name);
+ hiveTable.setDbName(schemaIdentifier().name());
+ hiveTable.setOwner(auditInfo.creator());
+ hiveTable.setSd(buildStorageDescriptor());
+ hiveTable.setTableType(String.valueOf(tableType));
+
+ return hiveTable;
+ }
+
+ private StorageDescriptor buildStorageDescriptor() {
+ StorageDescriptor sd = new StorageDescriptor();
+ sd.setCols(
+ Arrays.stream(columns)
+ .map(
+ c ->
+ new FieldSchema(
+ c.name(),
+ c.dataType().accept(ToHiveType.INSTANCE).getQualifiedName(),
+ c.comment()))
+ .collect(Collectors.toList()));
+ sd.setInputFormat(inputFormat);
+ sd.setOutputFormat(outputFormat);
+ sd.setSerdeInfo(buildSerDeInfo());
+ return sd;
+ }
+
+ private SerDeInfo buildSerDeInfo() {
+ SerDeInfo serDeInfo = new SerDeInfo();
+ serDeInfo.setName(name);
+ serDeInfo.setSerializationLib(serLib);
+ return serDeInfo;
+ }
+
+ public NameIdentifier schemaIdentifier() {
+ return NameIdentifier.of(nameIdentifier().namespace().levels());
+ }
+
+ public static class Builder extends BaseTableBuilder<Builder, HiveTable> {
+ private String inputFormat;
+
+ private String outputFormat;
+
+ private String serLib;
+
+ private TableType tableType;
+
+ public Builder withInputFormat(String inputFormat) {
+ this.inputFormat = inputFormat;
+ return this;
+ }
+
+ public Builder withOutputFormat(String outputFormat) {
+ this.outputFormat = outputFormat;
+ return this;
+ }
+
+ public Builder withSerLib(String serLib) {
+ this.serLib = serLib;
+ return this;
+ }
+
+ public Builder withTableType(TableType tableType) {
+ this.tableType = tableType;
+ return this;
+ }
+
+ @Override
+ protected HiveTable internalBuild() {
+ HiveTable hiveTable = new HiveTable();
+ hiveTable.id = id;
+ hiveTable.schemaId = schemaId;
+ hiveTable.namespace = namespace;
+ hiveTable.name = name;
+ hiveTable.comment = comment;
+ hiveTable.properties = properties;
+ hiveTable.auditInfo = auditInfo;
+ hiveTable.columns = columns;
+ hiveTable.inputFormat = inputFormat;
+ hiveTable.outputFormat = outputFormat;
+ hiveTable.serLib = serLib;
+ hiveTable.tableType = tableType == null ? MANAGED_TABLE : tableType;
+
+ // HMS put table comment in parameters
+ hiveTable.properties.put(HMS_TABLE_COMMENT, comment);
+
+ return hiveTable;
+ }
+ }
+}
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/converter/FromHiveType.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/converter/FromHiveType.java
new file mode 100644
index 0000000000..f93c2ea54c
--- /dev/null
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/converter/FromHiveType.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.hive.converter;
+
+import static org.apache.hadoop.hive.serde.serdeConstants.BIGINT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.BOOLEAN_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.CHAR_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.DATE_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.DECIMAL_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.DOUBLE_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.FLOAT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.INT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.SMALLINT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.STRING_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.TIMESTAMP_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.TINYINT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.VARCHAR_TYPE_NAME;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils.getTypeInfoFromTypeString;
+
+import io.substrait.type.Type;
+import io.substrait.type.TypeCreator;
+import java.util.stream.Collectors;
+import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.UnionTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo;
+
+public class FromHiveType {
+ public static Type convert(String hiveType) throws IllegalArgumentException {
+ TypeInfo hiveTypeInfo = getTypeInfoFromTypeString(hiveType);
+ return toSubstraitType(hiveTypeInfo);
+ }
+
+ private static Type toSubstraitType(TypeInfo hiveTypeInfo) throws IllegalArgumentException {
+ switch (hiveTypeInfo.getCategory()) {
+ case PRIMITIVE:
+ switch (hiveTypeInfo.getTypeName()) {
+ case BOOLEAN_TYPE_NAME:
+ return TypeCreator.NULLABLE.BOOLEAN;
+ case TINYINT_TYPE_NAME:
+ return TypeCreator.NULLABLE.I8;
+ case SMALLINT_TYPE_NAME:
+ return TypeCreator.NULLABLE.I16;
+ case INT_TYPE_NAME:
+ return TypeCreator.NULLABLE.I32;
+ case BIGINT_TYPE_NAME:
+ return TypeCreator.NULLABLE.I64;
+ case FLOAT_TYPE_NAME:
+ return TypeCreator.NULLABLE.FP32;
+ case DOUBLE_TYPE_NAME:
+ return TypeCreator.NULLABLE.FP64;
+ case STRING_TYPE_NAME:
+ return TypeCreator.NULLABLE.STRING;
+ case DATE_TYPE_NAME:
+ return TypeCreator.NULLABLE.DATE;
+ case TIMESTAMP_TYPE_NAME:
+ return TypeCreator.NULLABLE.TIMESTAMP;
+ case DECIMAL_TYPE_NAME:
+ DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) hiveTypeInfo;
+ return TypeCreator.NULLABLE.decimal(
+ decimalTypeInfo.precision(), decimalTypeInfo.getScale());
+ case CHAR_TYPE_NAME:
+ return TypeCreator.NULLABLE.fixedChar(((CharTypeInfo) hiveTypeInfo).getLength());
+ case VARCHAR_TYPE_NAME:
+ return TypeCreator.NULLABLE.varChar(((VarcharTypeInfo) hiveTypeInfo).getLength());
+ default:
+ throw new IllegalArgumentException(
+ "Unknown Hive type: " + hiveTypeInfo.getQualifiedName());
+ }
+ case LIST:
+ return TypeCreator.NULLABLE.list(
+ toSubstraitType(((ListTypeInfo) hiveTypeInfo).getListElementTypeInfo()));
+ case MAP:
+ MapTypeInfo mapTypeInfo = (MapTypeInfo) hiveTypeInfo;
+ return TypeCreator.NULLABLE.map(
+ toSubstraitType(mapTypeInfo.getMapKeyTypeInfo()),
+ toSubstraitType(mapTypeInfo.getMapKeyTypeInfo()));
+ case STRUCT:
+ return TypeCreator.NULLABLE.struct(
+ ((StructTypeInfo) hiveTypeInfo)
+ .getAllStructFieldTypeInfos().stream()
+ .map(FromHiveType::toSubstraitType)
+ .collect(Collectors.toList()));
+ case UNION:
+ return TypeCreator.NULLABLE.struct(
+ ((UnionTypeInfo) hiveTypeInfo)
+ .getAllUnionObjectTypeInfos().stream()
+ .map(FromHiveType::toSubstraitType)
+ .collect(Collectors.toList()));
+ default:
+ throw new IllegalArgumentException(
+ "Unknown category of Hive type: " + hiveTypeInfo.getCategory());
+ }
+ }
+}
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/converter/ToHiveType.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/converter/ToHiveType.java
new file mode 100644
index 0000000000..6e97ae0a14
--- /dev/null
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/converter/ToHiveType.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.hive.converter;
+
+import static org.apache.hadoop.hive.serde.serdeConstants.BIGINT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.BINARY_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.BOOLEAN_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.DATE_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.DOUBLE_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.FLOAT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.INTERVAL_DAY_TIME_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.INTERVAL_YEAR_MONTH_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.INT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.SMALLINT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.STRING_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.TIMESTAMP_TYPE_NAME;
+import static org.apache.hadoop.hive.serde.serdeConstants.TINYINT_TYPE_NAME;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getCharTypeInfo;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getDecimalTypeInfo;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getListTypeInfo;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getMapTypeInfo;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getPrimitiveTypeInfo;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getStructTypeInfo;
+import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getVarcharTypeInfo;
+
+import io.substrait.function.ParameterizedTypeVisitor;
+import io.substrait.type.Type;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+
+public class ToHiveType
+ extends ParameterizedTypeVisitor.ParameterizedTypeThrowsVisitor<TypeInfo, RuntimeException> {
+
+ public static ToHiveType INSTANCE = new ToHiveType();
+
+ private ToHiveType() {
+ super("Only support type literals and parameterized types.");
+ }
+
+ @Override
+ public TypeInfo visit(Type.Bool type) throws RuntimeException {
+ return getPrimitiveTypeInfo(BOOLEAN_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.I8 type) throws RuntimeException {
+ return getPrimitiveTypeInfo(TINYINT_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.I16 type) throws RuntimeException {
+ return getPrimitiveTypeInfo(SMALLINT_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.I32 type) throws RuntimeException {
+ return getPrimitiveTypeInfo(INT_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.I64 type) throws RuntimeException {
+ return getPrimitiveTypeInfo(BIGINT_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.FP32 type) throws RuntimeException {
+ return getPrimitiveTypeInfo(FLOAT_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.FP64 type) throws RuntimeException {
+ return getPrimitiveTypeInfo(DOUBLE_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.Str type) throws RuntimeException {
+ return getPrimitiveTypeInfo(STRING_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.VarChar type) throws RuntimeException {
+ return getVarcharTypeInfo(type.length());
+ }
+
+ @Override
+ public TypeInfo visit(Type.FixedChar type) throws RuntimeException {
+ return getCharTypeInfo(type.length());
+ }
+
+ @Override
+ public TypeInfo visit(Type.Date type) throws RuntimeException {
+ return getPrimitiveTypeInfo(DATE_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.Timestamp type) throws RuntimeException {
+ return getPrimitiveTypeInfo(TIMESTAMP_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.Decimal type) throws RuntimeException {
+ return getDecimalTypeInfo(type.precision(), type.scale());
+ }
+
+ @Override
+ public TypeInfo visit(Type.Binary type) throws RuntimeException {
+ return getPrimitiveTypeInfo(BINARY_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.IntervalYear type) throws RuntimeException {
+ return getPrimitiveTypeInfo(INTERVAL_YEAR_MONTH_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.IntervalDay type) throws RuntimeException {
+ return getPrimitiveTypeInfo(INTERVAL_DAY_TIME_TYPE_NAME);
+ }
+
+ @Override
+ public TypeInfo visit(Type.ListType type) throws RuntimeException {
+ return getListTypeInfo(type.elementType().accept(INSTANCE));
+ }
+
+ @Override
+ public TypeInfo visit(Type.Map type) throws RuntimeException {
+ return getMapTypeInfo(type.key().accept(INSTANCE), type.value().accept(INSTANCE));
+ }
+
+ @Override
+ public TypeInfo visit(Type.Struct type) throws RuntimeException {
+ List<TypeInfo> typeInfos =
+ type.fields().stream().map(t -> t.accept(INSTANCE)).collect(Collectors.toList());
+ List<String> names =
+ IntStream.range(0, typeInfos.size()).mapToObj(String::valueOf).collect(Collectors.toList());
+ // TODO: Actually, Hive's Struct type should correspond to Substrait's NamedStruct type.
+ // However, NamedStruct is a Pseudo-type, not an implementation of io.substrait.type.Type.
+ // I haven't figured out a good way to resolve this yet. For now, I'm using an index instead of
+ // name as a temporary workaround.
+ return getStructTypeInfo(names, typeInfos);
+ }
+}
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java
index e4c15deea3..4c2ca83df6 100644
--- a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java
@@ -15,7 +15,6 @@ import com.google.common.collect.Maps;
import java.time.Instant;
import java.util.Arrays;
import java.util.Map;
-import java.util.UUID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -126,8 +125,4 @@ public class HiveSchemaTest extends MiniHiveMetastoreService {
hiveCatalog.asSchemas().dropSchema(ident, true);
Assertions.assertFalse(hiveCatalog.asSchemas().schemaExists(ident));
}
-
- private static String genRandomName() {
- return UUID.randomUUID().toString().replace("-", "");
- }
}
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
new file mode 100644
index 0000000000..cb7659b118
--- /dev/null
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveTableTest.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.hive;
+
+import com.datastrato.graviton.NameIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;
+import com.datastrato.graviton.exceptions.TableAlreadyExistsException;
+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.google.common.collect.Maps;
+import io.substrait.type.TypeCreator;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class HiveTableTest extends MiniHiveMetastoreService {
+
+ private static final String META_LAKE_NAME = "metalake";
+
+ private static final String HIVE_CATALOG_NAME = "test_catalog";
+ private static final String HIVE_SCHEMA_NAME = "test_schema";
+ private static final String HIVE_COMMENT = "test_comment";
+ private static HiveCatalog hiveCatalog;
+ private static HiveSchema hiveSchema;
+
+ @BeforeAll
+ private static void setup() {
+ initHiveCatalog();
+ initHiveSchema();
+ }
+
+ @AfterEach
+ private void resetSchema() {
+ hiveCatalog.asSchemas().dropSchema(hiveSchema.nameIdentifier(), true);
+ initHiveSchema();
+ }
+
+ private static void initHiveSchema() {
+ NameIdentifier schemaIdent =
+ NameIdentifier.of(META_LAKE_NAME, hiveCatalog.name(), HIVE_SCHEMA_NAME);
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ hiveSchema =
+ (HiveSchema) hiveCatalog.asSchemas().createSchema(schemaIdent, HIVE_COMMENT, properties);
+ }
+
+ private static void initHiveCatalog() {
+ AuditInfo auditInfo =
+ new AuditInfo.Builder().withCreator("testHiveUser").withCreateTime(Instant.now()).build();
+
+ CatalogEntity entity =
+ new CatalogEntity.Builder()
+ .withId(1L)
+ .withName(HIVE_CATALOG_NAME)
+ .withNamespace(Namespace.of(META_LAKE_NAME))
+ .withType(HiveCatalog.Type.RELATIONAL)
+ .withMetalakeId(1L)
+ .withAuditInfo(auditInfo)
+ .build();
+
+ Map<String, String> conf = Maps.newHashMap();
+ metastore.hiveConf().forEach(e -> conf.put(e.getKey(), e.getValue()));
+ hiveCatalog = new HiveCatalog().withCatalogConf(conf).withCatalogEntity(entity);
+ }
+
+ @Test
+ public void testCreateHiveTable() {
+ Long tableId = 1L;
+ String hiveTableName = "test_hive_table";
+ NameIdentifier tableIdentifier =
+ NameIdentifier.of(META_LAKE_NAME, hiveCatalog.name(), hiveSchema.name(), hiveTableName);
+ 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};
+
+ Table table =
+ hiveCatalog
+ .asTableCatalog()
+ .createTable(tableIdentifier, columns, HIVE_COMMENT, properties);
+ Assertions.assertEquals(tableIdentifier.name(), table.name());
+ Assertions.assertEquals(HIVE_COMMENT, table.comment());
+ Assertions.assertArrayEquals(columns, table.columns());
+
+ Assertions.assertTrue(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));
+ NameIdentifier[] tableIdents =
+ hiveCatalog.asTableCatalog().listTables(tableIdentifier.namespace());
+ Assertions.assertTrue(Arrays.asList(tableIdents).contains(tableIdentifier));
+
+ // Test exception
+ Throwable exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ hiveCatalog
+ .asTableCatalog()
+ .createTable(hiveSchema.nameIdentifier(), columns, HIVE_COMMENT, properties));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));
+
+ exception =
+ Assertions.assertThrows(
+ TableAlreadyExistsException.class,
+ () ->
+ hiveCatalog
+ .asTableCatalog()
+ .createTable(tableIdentifier, columns, HIVE_COMMENT, properties));
+ Assertions.assertTrue(exception.getMessage().contains("Table already exists"));
+ }
+
+ @Test
+ public void testDropHiveTable() {
+ Long tableId = 1L;
+ 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));
+ hiveCatalog.asTableCatalog().dropTable(tableIdentifier);
+ Assertions.assertFalse(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));
+ }
+
+ @Test
+ public void testListTableException() {
+ Throwable exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> hiveCatalog.asTableCatalog().listTables(hiveSchema.nameIdentifier().namespace()));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));
+
+ NameIdentifier ident = NameIdentifier.of("metalake", hiveCatalog.name(), "not_exist_db");
+ exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> hiveCatalog.asTableCatalog().listTables(ident.namespace()));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));
+ }
+}
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/MiniHiveMetastoreService.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/MiniHiveMetastoreService.java
index d9bac3588f..4cc5780810 100644
--- a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/MiniHiveMetastoreService.java
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/MiniHiveMetastoreService.java
@@ -21,6 +21,7 @@ package com.datastrato.graviton.catalog.hive.miniHMS;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
+import java.util.UUID;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.Database;
@@ -71,4 +72,8 @@ public abstract class MiniHiveMetastoreService {
metastore.stop();
MiniHiveMetastoreService.metastore = null;
}
+
+ protected static String genRandomName() {
+ return UUID.randomUUID().toString().replace("-", "");
+ }
}
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/ScriptRunner.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/ScriptRunner.java
index 0836596ce5..eb22030cac 100644
--- a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/ScriptRunner.java
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/miniHMS/ScriptRunner.java
@@ -135,15 +135,15 @@ public class ScriptRunner {
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
- for (int i = 0; i < cols; i++) {
+ for (int i = 1; i <= cols; i++) {
String name = md.getColumnLabel(i);
- print(name + "\t");
+ print(name + "\t|");
}
println("");
while (rs.next()) {
- for (int i = 0; i < cols; i++) {
+ for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
- print(value + "\t");
+ print(value + "\t|");
}
println("");
}
@@ -181,7 +181,7 @@ public class ScriptRunner {
private void print(Object obj) {
if (logWriter != null) {
- System.out.print(obj);
+ logWriter.print(obj);
}
}
diff --git a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseColumn.java b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseColumn.java
new file mode 100644
index 0000000000..057f538163
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseColumn.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.meta.rel;
+
+import com.datastrato.graviton.Entity;
+import com.datastrato.graviton.Field;
+import com.datastrato.graviton.rel.Column;
+import com.google.common.collect.Maps;
+import io.substrait.type.Type;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+
+@EqualsAndHashCode
+@ToString
+public abstract class BaseColumn implements Column, Entity {
+ public static final Field NAME = Field.required("name", String.class, "The name of the column");
+ public static final Field COMMENT =
+ Field.optional("comment", String.class, "The comment of the column");
+ public static final Field TYPE = Field.required("dataType", Type.class, "The type of the column");
+
+ protected String name;
+
+ @Nullable protected String comment;
+
+ protected Type dataType;
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public Type dataType() {
+ return dataType;
+ }
+
+ @Nullable
+ @Override
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public Map<Field, Object> fields() {
+ Map<Field, Object> fields = Maps.newHashMap();
+ fields.put(NAME, name);
+ fields.put(COMMENT, comment);
+ fields.put(TYPE, dataType);
+
+ return fields;
+ }
+
+ interface Builder<SELF extends BaseColumn.Builder<SELF, T>, T extends BaseColumn> {
+ SELF withName(String name);
+
+ SELF withComment(String comment);
+
+ SELF withType(Type dataType);
+
+ T build();
+ }
+
+ public abstract static class BaseColumnBuilder<
+ SELF extends BaseColumn.Builder<SELF, T>, T extends BaseColumn>
+ implements BaseColumn.Builder<SELF, T> {
+ protected String name;
+ protected String comment;
+ protected Type dataType;
+
+ @Override
+ public SELF withName(String name) {
+ this.name = name;
+ return self();
+ }
+
+ @Override
+ public SELF withComment(String comment) {
+ this.comment = comment;
+ return self();
+ }
+
+ @Override
+ public SELF withType(Type dataType) {
+ this.dataType = dataType;
+ return self();
+ }
+
+ @Override
+ public T build() {
+ T t = internalBuild();
+ t.validate();
+ return t;
+ }
+
+ private SELF self() {
+ return (SELF) this;
+ }
+
+ protected abstract T internalBuild();
+ }
+}
diff --git a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java
new file mode 100644
index 0000000000..ee7302312d
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.meta.rel;
+
+import com.datastrato.graviton.Audit;
+import com.datastrato.graviton.Entity;
+import com.datastrato.graviton.Field;
+import com.datastrato.graviton.HasIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.rel.Column;
+import com.datastrato.graviton.rel.Table;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+
+@EqualsAndHashCode
+@ToString
+public abstract class BaseTable implements Table, Entity, HasIdentifier {
+
+ public static final Field ID =
+ Field.required("id", Long.class, "The unique identifier of the table");
+ public static final Field SCHEMA_ID =
+ Field.required("schema_id", Long.class, "The unique identifier of the schema");
+ public static final Field NAME = Field.required("name", String.class, "The name of the table");
+ public static final Field COMMENT =
+ Field.optional("comment", String.class, "The comment of the table");
+ public static final Field PROPERTIES =
+ Field.optional("properties", Map.class, "The properties of the table");
+ public static final Field AUDIT_INFO =
+ Field.required("audit_info", AuditInfo.class, "The audit info of the table");
+ public static final Field COLUMNS =
+ Field.required("columns", Column[].class, "The columns of the table");
+
+ protected Long id;
+
+ protected Long schemaId;
+
+ protected String name;
+
+ @Nullable protected String comment;
+
+ @Nullable protected Map<String, String> properties;
+
+ protected AuditInfo auditInfo;
+
+ protected Column[] columns;
+
+ protected Namespace namespace;
+
+ @Override
+ public Map<Field, Object> fields() {
+ Map<Field, Object> fields = Maps.newHashMap();
+ fields.put(ID, id);
+ fields.put(SCHEMA_ID, schemaId);
+ fields.put(NAME, name);
+ fields.put(COMMENT, comment);
+ fields.put(PROPERTIES, properties);
+ fields.put(AUDIT_INFO, auditInfo);
+ fields.put(COLUMNS, columns);
+
+ return fields;
+ }
+
+ @Override
+ public Audit auditInfo() {
+ return auditInfo;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public Column[] columns() {
+ return columns;
+ }
+
+ @Nullable
+ @Override
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return properties;
+ }
+
+ @Override
+ public Namespace namespace() {
+ return namespace;
+ }
+
+ interface Builder<SELF extends Builder<SELF, T>, T extends BaseTable> {
+ SELF withId(Long id);
+
+ SELF withSchemaId(Long schemaId);
+
+ SELF withNameSpace(Namespace namespace);
+
+ SELF withName(String name);
+
+ SELF withColumns(Column[] columns);
+
+ SELF withComment(String comment);
+
+ SELF withProperties(Map<String, String> properties);
+
+ SELF withAuditInfo(AuditInfo auditInfo);
+
+ T build();
+ }
+
+ public abstract static class BaseTableBuilder<SELF extends Builder<SELF, T>, T extends BaseTable>
+ implements Builder<SELF, T> {
+ protected Long id;
+ protected Long schemaId;
+ protected String name;
+ protected Namespace namespace;
+ protected String comment;
+ protected Map<String, String> properties;
+ protected AuditInfo auditInfo;
+ protected Column[] columns;
+
+ @Override
+ public SELF withId(Long id) {
+ this.id = id;
+ return self();
+ }
+
+ @Override
+ public SELF withSchemaId(Long schemaId) {
+ this.schemaId = schemaId;
+ return self();
+ }
+
+ @Override
+ public SELF withNameSpace(Namespace namespace) {
+ this.namespace = namespace;
+ return self();
+ }
+
+ @Override
+ public SELF withName(String name) {
+ this.name = name;
+ return self();
+ }
+
+ @Override
+ public SELF withComment(String comment) {
+ this.comment = comment;
+ return self();
+ }
+
+ @Override
+ public SELF withColumns(Column[] columns) {
+ this.columns = columns;
+ return self();
+ }
+
+ @Override
+ public SELF withProperties(Map<String, String> properties) {
+ this.properties = properties;
+ return self();
+ }
+
+ @Override
+ public SELF withAuditInfo(AuditInfo auditInfo) {
+ this.auditInfo = auditInfo;
+ return self();
+ }
+
+ @Override
+ public T build() {
+ T t = internalBuild();
+ t.validate();
+ return t;
+ }
+
+ private SELF self() {
+ return (SELF) this;
+ }
+
+ protected abstract T internalBuild();
+ }
+}