World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#318] refactor(core, catalog-*): Refactor the catalog operations to guarantee SSOT (#403)
Jerry Shaoc16ab1777785
diff --git a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.javaindex 59125ef3e8..de9c5cfff8 100644--- a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java+++ b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java@@ -4,21 +4,14 @@*/package com.datastrato.graviton.catalog.hive;-import static com.datastrato.graviton.Entity.EntityType.SCHEMA;-import static com.datastrato.graviton.Entity.EntityType.TABLE;import static com.datastrato.graviton.catalog.hive.HiveTable.HMS_TABLE_COMMENT;import static com.datastrato.graviton.catalog.hive.HiveTable.SUPPORT_TABLE_TYPES;-import com.datastrato.graviton.EntityAlreadyExistsException;-import com.datastrato.graviton.EntityStore;-import com.datastrato.graviton.GravitonEnv;import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;-import com.datastrato.graviton.StringIdentifier;import com.datastrato.graviton.catalog.CatalogOperations;import com.datastrato.graviton.catalog.hive.converter.ToHiveType;import com.datastrato.graviton.exceptions.NoSuchCatalogException;-import com.datastrato.graviton.exceptions.NoSuchEntityException;import com.datastrato.graviton.exceptions.NoSuchSchemaException;import com.datastrato.graviton.exceptions.NoSuchTableException;import com.datastrato.graviton.exceptions.NonEmptySchemaException;@@ -26,8 +19,6 @@ 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.meta.rel.BaseTable;import com.datastrato.graviton.rel.Column;import com.datastrato.graviton.rel.Distribution;import com.datastrato.graviton.rel.SchemaChange;@@ -40,7 +31,6 @@ import com.datastrato.graviton.rel.transforms.Transform;import com.datastrato.graviton.rel.transforms.Transforms;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.Arrays;@@ -116,10 +106,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas*/@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {- if (!isValidNamespace(namespace)) {- throw new NoSuchCatalogException("Namespace is invalid " + namespace);- }-try {NameIdentifier[] schemas =clientPool.run(@@ -154,46 +140,27 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas@Overridepublic HiveSchema createSchema(NameIdentifier ident, String comment, Map<String, String> metadata)throws NoSuchCatalogException, SchemaAlreadyExistsException {- Preconditions.checkArgument(- !ident.name().isEmpty(),- String.format("Cannot create schema with invalid name: %s", ident.name()));- Preconditions.checkArgument(- isValidNamespace(ident.namespace()),- String.format("Cannot support invalid namespace in Hive Metastore: %s", ident.namespace()));-try {- EntityStore store = GravitonEnv.getInstance().entityStore();- long uid = GravitonEnv.getInstance().idGenerator().nextId();- StringIdentifier stringId = StringIdentifier.fromId(uid);-HiveSchema hiveSchema =- store.executeInTransaction(- () -> {- HiveSchema createdSchema =- new HiveSchema.Builder()- .withId(uid)- .withName(ident.name())- .withNamespace(ident.namespace())- .withComment(comment)- .withProperties(StringIdentifier.addToProperties(stringId, metadata))- .withAuditInfo(- new AuditInfo.Builder()- .withCreator(currentUser())- .withCreateTime(Instant.now())- .build())- .withConf(hiveConf)- .build();- store.put(createdSchema, false);- clientPool.run(- client -> {- client.createDatabase(createdSchema.toInnerDB());- return null;- });- return createdSchema;- });+ new HiveSchema.Builder()+ .withName(ident.name())+ .withComment(comment)+ .withProperties(metadata)+ .withConf(hiveConf)+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator(currentUser())+ .withCreateTime(Instant.now())+ .build())+ .build();++ clientPool.run(+ client -> {+ client.createDatabase(hiveSchema.toHiveDB());+ return null;+ });LOG.info("Created Hive schema (database) {} in Hive Metastore", ident.name());-return hiveSchema;} catch (AlreadyExistsException e) {@@ -202,20 +169,10 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas"Hive schema (database) '%s' already exists in Hive Metastore", ident.name()),e);- } catch (EntityAlreadyExistsException e) {- throw new SchemaAlreadyExistsException(- String.format(- "Hive schema (database) '%s' already exists in Graviton store", ident.name()),- e);-} catch (TException e) {throw new RuntimeException("Failed to create Hive schema (database) " + ident.name() + " in Hive Metastore", e);- } catch (IOException e) {- throw new RuntimeException(- "Failed to create Hive schema (database) " + ident.name() + " in Graviton store", e);-} catch (Exception e) {throw new RuntimeException(e);}@@ -230,53 +187,25 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas*/@Overridepublic HiveSchema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {- Preconditions.checkArgument(- !ident.name().isEmpty(),- 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()));-try {Database database = clientPool.run(client -> client.getDatabase(ident.name()));- HiveSchema.Builder builder = new HiveSchema.Builder();-- EntityStore store = GravitonEnv.getInstance().entityStore();- BaseSchema baseSchema = store.get(ident, SCHEMA, BaseSchema.class);-- builder = builder.withId(baseSchema.id()).withNamespace(ident.namespace()).withConf(hiveConf);- HiveSchema hiveSchema = HiveSchema.fromInnerDB(database, builder);-- // Merge audit info from Graviton store- hiveSchema.auditInfo().merge(baseSchema.auditInfo(), true /*overwrite*/);+ HiveSchema hiveSchema = HiveSchema.fromHiveDB(database, hiveConf);LOG.info("Loaded Hive schema (database) {} from Hive Metastore ", ident.name());-return hiveSchema;} catch (NoSuchObjectException | UnknownDBException e) {- deleteSchemaFromStore(ident);throw new NoSuchSchemaException(String.format("Hive schema (database) does not exist: %s in Hive Metastore", ident.name()),e);- } catch (NoSuchEntityException e) {- throw new NoSuchSchemaException(- String.format(- "Hive schema (database) does not exist: %s in Graviton store", ident.name()),- e);-} catch (TException e) {throw new RuntimeException("Failed to load Hive schema (database) " + ident.name() + " from Hive Metastore", e);} catch (InterruptedException e) {throw new RuntimeException(e);-- } catch (IOException ioe) {- LOG.error("Failed to load hive schema {}", ident, ioe);- throw new RuntimeException(ioe);}}@@ -291,13 +220,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas@Overridepublic HiveSchema alterSchema(NameIdentifier ident, SchemaChange... changes)throws NoSuchSchemaException {- Preconditions.checkArgument(- !ident.name().isEmpty(),- String.format("Cannot create schema with invalid name: %s", ident.name()));- Preconditions.checkArgument(- isValidNamespace(ident.namespace()),- String.format("Cannot support invalid namespace in Hive Metastore: %s", ident.namespace()));-try {// load the database parametersDatabase database = clientPool.run(client -> client.getDatabase(ident.name()));@@ -324,64 +246,24 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemasDatabase alteredDatabase = database.deepCopy();alteredDatabase.setParameters(metadata);- // update store transactionally- EntityStore store = GravitonEnv.getInstance().entityStore();- HiveSchema alteredHiveSchema =- store.executeInTransaction(- () -> {- BaseSchema oldSchema = store.get(ident, SCHEMA, BaseSchema.class);- HiveSchema.Builder builder = new HiveSchema.Builder();- builder =- builder- .withId(oldSchema.id())- .withNamespace(ident.namespace())- .withConf(hiveConf);- HiveSchema hiveSchema = HiveSchema.fromInnerDB(alteredDatabase, builder);-- AuditInfo newAudit =- new AuditInfo.Builder()- .withCreator(oldSchema.auditInfo().creator())- .withCreateTime(oldSchema.auditInfo().createTime())- .withLastModifier(currentUser())- .withLastModifiedTime(Instant.now())- .build();- hiveSchema.auditInfo().merge(newAudit, true /*overwrite*/);-- // To be on the safe side, here uses delete before put (although hive schema does- // not support rename yet)- store.delete(ident, SCHEMA);- store.put(hiveSchema, false);- clientPool.run(- client -> {- client.alterDatabase(ident.name(), alteredDatabase);- return null;- });- return hiveSchema;- });+ clientPool.run(+ client -> {+ client.alterDatabase(ident.name(), alteredDatabase);+ return null;+ });LOG.info("Altered Hive schema (database) {} in Hive Metastore", ident.name());- // todo(xun): hive does not support renaming database name directly,- // perhaps we can use namespace to mapping the database names indirectly-- return alteredHiveSchema;+ return HiveSchema.fromHiveDB(alteredDatabase, hiveConf);} catch (NoSuchObjectException e) {throw new NoSuchSchemaException(String.format("Hive schema (database) %s does not exist in Hive Metastore", ident.name()),e);- } catch (EntityAlreadyExistsException e) {- throw new NoSuchSchemaException(- "The new Hive schema (database) name already exist in Graviton store", e);-} catch (TException | InterruptedException e) {throw new RuntimeException("Failed to alter Hive schema (database) " + ident.name() + " in Hive metastore", e);- } catch (IOException e) {- throw new RuntimeException(- "Failed to alter Hive schema (database) " + ident.name() + " in Graviton store", e);-} catch (Exception e) {throw new RuntimeException(e);}@@ -397,55 +279,14 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas*/@Overridepublic boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {- if (ident.name().isEmpty()) {- LOG.error("Cannot drop schema with invalid name: {}", ident.name());- return false;- }- if (!isValidNamespace(ident.namespace())) {- LOG.error("Cannot support invalid namespace in Hive Metastore: {}", ident.namespace());- return false;- }-- EntityStore store = GravitonEnv.getInstance().entityStore();- Namespace schemaNamespace =- Namespace.of(ArrayUtils.add(ident.namespace().levels(), ident.name()));- List<BaseTable> tables = Lists.newArrayList();- if (!cascade) {- if (listTables(schemaNamespace).length > 0) {- throw new NonEmptySchemaException(- String.format(- "Hive schema (database) %s is not empty. One or more tables exist in Hive metastore.",- ident.name()));- }-- try {- tables.addAll(store.list(schemaNamespace, BaseTable.class, TABLE));- } catch (IOException e) {- throw new RuntimeException("Failed to list table from Graviton store", e);- }- if (!tables.isEmpty()) {- throw new NonEmptySchemaException(- String.format(- "Hive schema (database) %s is not empty. One or more tables exist in Graviton store.",- ident.name()));- }- }-try {- return store.executeInTransaction(- () -> {- for (BaseTable t : tables) {- store.delete(NameIdentifier.of(schemaNamespace, t.name()), TABLE);- }- boolean dropped = store.delete(ident, SCHEMA, true);- clientPool.run(- client -> {- client.dropDatabase(ident.name(), false, false, cascade);- return null;- });- LOG.info("Dropped Hive schema (database) {}", ident.name());- return dropped;+ clientPool.run(+ client -> {+ client.dropDatabase(ident.name(), false, false, cascade);+ return null;});+ LOG.info("Dropped Hive schema (database) {}", ident.name());+ return true;} catch (InvalidOperationException e) {throw new NonEmptySchemaException(@@ -454,7 +295,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemase);} catch (NoSuchObjectException e) {- deleteSchemaFromStore(ident);LOG.warn("Hive schema (database) {} does not exist in Hive Metastore", ident.name());return false;@@ -462,24 +302,11 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemasthrow new RuntimeException("Failed to drop Hive schema (database) " + ident.name() + " in Hive Metastore", e);- } catch (IOException e) {- throw new RuntimeException(- "Failed to drop Hive schema (database) " + ident.name() + " in Graviton store", e);-} catch (Exception e) {throw new RuntimeException(e);}}- private void deleteSchemaFromStore(NameIdentifier ident) {- EntityStore store = GravitonEnv.getInstance().entityStore();- try {- store.delete(ident, SCHEMA);- } catch (IOException ex) {- LOG.error("Failed to delete hive schema {} from Graviton store", ident, ex);- }- }-/*** Lists all the tables under the specified namespace.*@@ -535,35 +362,16 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas*/@Overridepublic 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()));try {- org.apache.hadoop.hive.metastore.api.Table hiveTable =+ org.apache.hadoop.hive.metastore.api.Table table =clientPool.run(c -> c.getTable(schemaIdent.name(), tableIdent.name()));- HiveTable.Builder builder = new HiveTable.Builder();-- EntityStore store = GravitonEnv.getInstance().entityStore();- BaseTable baseTable = store.get(tableIdent, TABLE, BaseTable.class);-- builder =- builder- .withId(baseTable.id())- .withName(tableIdent.name())- .withNameSpace(tableIdent.namespace());- HiveTable table = HiveTable.fromInnerTable(hiveTable, builder);-- // Merge the audit info from Graviton store.- table.auditInfo().merge(baseTable.auditInfo(), true /* overwrite */);+ HiveTable hiveTable = HiveTable.fromHiveTable(table);LOG.info("Loaded Hive table {} from Hive Metastore ", tableIdent.name());+ return hiveTable;- return table;} catch (NoSuchObjectException e) {throw new NoSuchTableException(String.format("Hive table does not exist: %s in Hive Metastore", tableIdent.name()), e);@@ -571,10 +379,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas} catch (InterruptedException | TException e) {throw new RuntimeException("Failed to load Hive table " + tableIdent.name() + " from Hive metastore", e);-- } catch (IOException e) {- throw new RuntimeException(- "Failed to load Hive table " + tableIdent.name() + " from Graviton store", e);}}@@ -617,14 +421,7 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemasDistribution distribution,SortOrder[] sortOrders)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()));Preconditions.checkArgument(Arrays.stream(partitions).allMatch(p -> p instanceof Transforms.NamedReference),@@ -637,52 +434,36 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemasthrow new NoSuchSchemaException("Hive Schema (database) does not exist " + schemaIdent);}- EntityStore store = GravitonEnv.getInstance().entityStore();- long uid = GravitonEnv.getInstance().idGenerator().nextId();- StringIdentifier stringId = StringIdentifier.fromId(uid);-HiveTable hiveTable =- store.executeInTransaction(- () -> {- HiveTable createdTable =- new HiveTable.Builder()- .withId(uid)- .withName(tableIdent.name())- .withNameSpace(tableIdent.namespace())- .withColumns(columns)- .withComment(comment)- .withProperties(properties)- .withDistribution(distribution)- .withSortOrders(sortOrders)- .withProperties(StringIdentifier.addToProperties(stringId, properties))- .withAuditInfo(- new AuditInfo.Builder()- .withCreator(currentUser())- .withCreateTime(Instant.now())- .build())- .withPartitions(partitions)- .build();- store.put(createdTable, false);- clientPool.run(- c -> {- c.createTable(createdTable.toInnerTable());- return null;- });- return createdTable;- });+ new HiveTable.Builder()+ .withName(tableIdent.name())+ .withSchemaName(schemaIdent.name())+ .withComment(comment)+ .withColumns(columns)+ .withProperties(properties)+ .withDistribution(distribution)+ .withSortOrders(sortOrders)+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator(currentUser())+ .withCreateTime(Instant.now())+ .build())+ .withPartitions(partitions)+ .build();+ clientPool.run(+ c -> {+ c.createTable(hiveTable.toHiveTable());+ return null;+ });LOG.info("Created Hive table {} in Hive Metastore", tableIdent.name());-return hiveTable;- } catch (AlreadyExistsException | EntityAlreadyExistsException e) {+ } catch (AlreadyExistsException e) {throw new TableAlreadyExistsException("Table already exists: " + tableIdent.name(), e);} catch (TException | InterruptedException e) {throw new RuntimeException("Failed to create Hive table " + tableIdent.name() + " in Hive Metastore", e);- } catch (IOException e) {- throw new RuntimeException(- "Failed to create Hive table " + tableIdent.name() + " in Graviton store", e);} catch (Exception e) {throw new RuntimeException(e);}@@ -700,19 +481,12 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas@Overridepublic Table alterTable(NameIdentifier tableIdent, TableChange... changes)throws NoSuchTableException, IllegalArgumentException {- 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 conditionHiveTable table = (HiveTable) loadTable(tableIdent);- org.apache.hadoop.hive.metastore.api.Table alteredHiveTable = table.toInnerTable();+ org.apache.hadoop.hive.metastore.api.Table alteredHiveTable = table.toHiveTable();for (TableChange change : changes) {// Table change@@ -761,41 +535,14 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas}}- EntityStore store = GravitonEnv.getInstance().entityStore();- HiveTable updatedTable =- store.executeInTransaction(- () -> {- HiveTable.Builder builder = new HiveTable.Builder();- builder =- builder- .withId(table.id())- .withName(alteredHiveTable.getTableName())- .withNameSpace(tableIdent.namespace());-- HiveTable alteredTable = HiveTable.fromInnerTable(alteredHiveTable, builder);-- AuditInfo newAudit =- new AuditInfo.Builder()- .withCreator(table.auditInfo().creator())- .withCreateTime(table.auditInfo().createTime())- .withLastModifier(currentUser())- .withLastModifiedTime(Instant.now())- .build();- alteredTable.auditInfo().merge(newAudit, true /* overwrite */);-- store.delete(tableIdent, TABLE);- store.put(alteredTable, false);- clientPool.run(- c -> {- c.alter_table(schemaIdent.name(), tableIdent.name(), alteredHiveTable);- return null;- });- return alteredTable;- });+ clientPool.run(+ c -> {+ c.alter_table(schemaIdent.name(), tableIdent.name(), alteredHiveTable);+ return null;+ });LOG.info("Altered Hive table {} in Hive Metastore", tableIdent.name());-- return updatedTable;+ return HiveTable.fromHiveTable(alteredHiveTable);} catch (NoSuchObjectException e) {throw new NoSuchTableException(@@ -803,9 +550,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas} catch (TException | InterruptedException e) {throw new RuntimeException("Failed to alter Hive table " + tableIdent.name() + " in Hive metastore", e);- } catch (IOException e) {- throw new RuntimeException(- "Failed to alter Hive table " + tableIdent.name() + " in Graviton store", e);} catch (Exception e) {throw new RuntimeException(e);}@@ -937,7 +681,6 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas*/@Overridepublic boolean purgeTable(NameIdentifier tableIdent) throws UnsupportedOperationException {- HiveTable table = (HiveTable) loadTable(tableIdent);// TODO(minghuang): HiveTable support specify `tableType`, then reject purge Hive table with// `tableType` EXTERNAL_TABLEreturn dropHiveTable(tableIdent, true, true);@@ -950,51 +693,29 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas* @return true if the namespace is valid; otherwise, false.*/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 {- EntityStore store = GravitonEnv.getInstance().entityStore();- return store.executeInTransaction(- () -> {- boolean dropped = store.delete(tableIdent, TABLE);- clientPool.run(- c -> {- c.dropTable(schemaIdent.name(), tableIdent.name(), deleteData, false, ifPurge);- return null;- });- LOG.info("Dropped Hive table {}", tableIdent.name());- return dropped;+ clientPool.run(+ c -> {+ c.dropTable(schemaIdent.name(), tableIdent.name(), deleteData, false, ifPurge);+ return null;});++ 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 | InterruptedException e) {throw new RuntimeException("Failed to drop Hive table " + tableIdent.name() + " in Hive Metastore", e);- } catch (IOException e) {- throw new RuntimeException(- "Failed to drop Hive table " + tableIdent.name() + " in Graviton store", e);} catch (Exception e) {throw new RuntimeException(e);}}- /**- * Checks if the given namespace is a valid namespace for the Hive schema.- *- * @param namespace The namespace to validate.- * @return true if the namespace is valid; otherwise, false.- */- public boolean isValidNamespace(Namespace namespace) {- return namespace.levels().length == 2 && namespace.level(1).equals(entity.name());- }-// TODO. We should figure out a better way to get the current user from servlet container.private static String currentUser() {String username = null;diff --git a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.java b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.javaindex f9170e13e8..00852e3e7e 100644--- a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.java+++ b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveColumn.java@@ -4,9 +4,11 @@*/package com.datastrato.graviton.catalog.hive;-import com.datastrato.graviton.meta.rel.BaseColumn;+import com.datastrato.graviton.catalog.rel.BaseColumn;+import lombok.EqualsAndHashCode;/** Represents a column in the Hive Metastore catalog. */+@EqualsAndHashCode(callSuper = true)public class HiveColumn extends BaseColumn {private HiveColumn() {}diff --git a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveSchema.java b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveSchema.javaindex 13eed4f1eb..b9f5c09e4c 100644--- a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveSchema.java+++ b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveSchema.java@@ -4,8 +4,8 @@*/package com.datastrato.graviton.catalog.hive;+import com.datastrato.graviton.catalog.rel.BaseSchema;import com.datastrato.graviton.meta.AuditInfo;-import com.datastrato.graviton.meta.rel.BaseSchema;import com.google.common.base.Preconditions;import com.google.common.collect.Maps;import java.util.Collections;@@ -23,8 +23,6 @@ public class HiveSchema extends BaseSchema {private static final String HMS_DB_OWNER = "hive.metastore.database.owner";private static final String HMS_DB_OWNER_TYPE = "hive.metastore.database.owner-type";- private Database innerDb;-private Configuration conf;private HiveSchema() {}@@ -33,10 +31,10 @@ public class HiveSchema extends BaseSchema {* Creates a new HiveSchema instance from a Database and a Builder.** @param db The Database representing the HiveSchema.- * @param builder The Builder used to construct the HiveSchema.+ * @param hiveConf The HiveConf used to construct the HiveSchema.* @return A new HiveSchema instance.*/- public static HiveSchema fromInnerDB(Database db, Builder builder) {+ public static HiveSchema fromHiveDB(Database db, Configuration hiveConf) {Map<String, String> properties = convertToMetadata(db);// Get audit info from Hive's Database object. Because Hive's database doesn't store create@@ -44,11 +42,12 @@ public class HiveSchema extends BaseSchema {AuditInfo.Builder auditInfoBuilder = new AuditInfo.Builder();Optional.ofNullable(db.getOwnerName()).ifPresent(auditInfoBuilder::withCreator);- return builder+ return new HiveSchema.Builder().withName(db.getName()).withComment(db.getDescription()).withProperties(properties).withAuditInfo(auditInfoBuilder.build())+ .withConf(hiveConf).build();}@@ -81,12 +80,9 @@ public class HiveSchema extends BaseSchema {** @return The converted Database object.*/- public Database toInnerDB() {- if (innerDb != null) {- return innerDb;- }+ public Database toHiveDB() {+ Database innerDb = new Database();- innerDb = new Database();Map<String, String> parameter = Maps.newHashMap();innerDb.setName(name());innerDb.setLocationUri(databaseLocation(name()));@@ -164,9 +160,7 @@ public class HiveSchema extends BaseSchema {@Overrideprotected HiveSchema internalBuild() {HiveSchema hiveSchema = new HiveSchema();- hiveSchema.id = id;hiveSchema.name = name;- hiveSchema.namespace = namespace;hiveSchema.comment = comment;hiveSchema.properties = properties;hiveSchema.auditInfo = auditInfo;diff --git a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.javaindex 0cce51ea82..2391762029 100644--- a/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java+++ b/catalogs/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveTable.java@@ -8,11 +8,10 @@ import static com.datastrato.graviton.rel.transforms.Transforms.identity;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.catalog.rel.BaseTable;import com.datastrato.graviton.meta.AuditInfo;-import com.datastrato.graviton.meta.rel.BaseTable;import com.datastrato.graviton.rel.Column;import com.datastrato.graviton.rel.Distribution;import com.datastrato.graviton.rel.SortOrder;@@ -29,7 +28,6 @@ import java.util.List;import java.util.Optional;import java.util.Set;import java.util.stream.Collectors;-import lombok.Getter;import lombok.ToString;import org.apache.commons.collections.CollectionUtils;import org.apache.commons.lang3.ArrayUtils;@@ -41,7 +39,6 @@ import org.apache.hadoop.hive.metastore.api.Table;/** Represents a Hive Table entity in the Hive Metastore catalog. */@ToString-@Getterpublic class HiveTable extends BaseTable {// A set of supported Hive table types.@@ -53,16 +50,17 @@ public class HiveTable extends BaseTable {private String location;+ private String schemaName;+private HiveTable() {}/*** Creates a new HiveTable instance from a Table and a Builder.** @param table The inner Table representing the HiveTable.- * @param builder The Builder used to construct the HiveTable.* @return A new HiveTable instance.*/- public static HiveTable fromInnerTable(Table table, Builder builder) {+ public static HiveTable fromHiveTable(Table table) {// Get audit info from Hive's Table object. Because Hive's table doesn't store last modifier// and last modified time, we only get creator and create time from Hive's table.AuditInfo.Builder auditInfoBuilder = new AuditInfo.Builder();@@ -96,7 +94,8 @@ public class HiveTable extends BaseTable {.toArray(SortOrder[]::new);}- return builder+ return new HiveTable.Builder()+ .withName(table.getTableName()).withComment(table.getParameters().get(HMS_TABLE_COMMENT)).withProperties(table.getParameters()).withColumns(@@ -117,6 +116,7 @@ public class HiveTable extends BaseTable {table.getPartitionKeys().stream().map(p -> identity(new String[] {p.getName()})).toArray(Transforms.NamedReference[]::new))+ .withSchemaName(table.getDbName()).build();}@@ -125,11 +125,11 @@ public class HiveTable extends BaseTable {** @return The converted Table.*/- public Table toInnerTable() {+ public Table toHiveTable() {Table hiveTable = new Table();hiveTable.setTableName(name);- hiveTable.setDbName(schemaIdentifier().name());+ hiveTable.setDbName(schemaName);hiveTable.setSd(buildStorageDescriptor());hiveTable.setParameters(properties);hiveTable.setPartitionKeys(buildPartitionKeys());@@ -208,15 +208,6 @@ public class HiveTable extends BaseTable {return serDeInfo;}- /**- * Gets the schema identifier for this HiveTable.- *- * @return The schema identifier.- */- public NameIdentifier schemaIdentifier() {- return NameIdentifier.of(nameIdentifier().namespace().levels());- }-/** A builder class for constructing HiveTable instances. */public static class Builder extends BaseTableBuilder<Builder, HiveTable> {@@ -224,11 +215,30 @@ public class HiveTable extends BaseTable {// TODO(minghuang): Support user specify`location` propertyprivate String location;+ private String schemaName;++ /**+ * Sets the location to be used for building the HiveTable.+ *+ * @param location The string location of the HiveTable.+ * @return This Builder instance.+ */public Builder withLocation(String location) {this.location = location;return this;}+ /**+ * Sets the Hive schema (database) name to be used for building the HiveTable.+ *+ * @param schemaName The string schema name of the HiveTable.+ * @return This Builder instance.+ */+ public Builder withSchemaName(String schemaName) {+ this.schemaName = schemaName;+ return this;+ }+/*** Internal method to build a HiveTable instance using the provided values.*@@ -237,8 +247,6 @@ public class HiveTable extends BaseTable {@Overrideprotected HiveTable internalBuild() {HiveTable hiveTable = new HiveTable();- hiveTable.id = id;- hiveTable.namespace = namespace;hiveTable.name = name;hiveTable.comment = comment;hiveTable.properties = properties != null ? Maps.newHashMap(properties) : Maps.newHashMap();@@ -248,6 +256,7 @@ public class HiveTable extends BaseTable {hiveTable.distribution = distribution;hiveTable.sortOrders = sortOrders;hiveTable.partitions = partitions;+ hiveTable.schemaName = schemaName;// HMS put table comment in parametersif (comment != null) {diff --git a/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveSchema.java b/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveSchema.javaindex 75e5af0d3e..ef2614ca4c 100644--- a/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveSchema.java+++ b/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveSchema.java@@ -4,19 +4,8 @@*/package com.datastrato.graviton.catalog.hive;-import static com.datastrato.graviton.Configs.DEFAULT_ENTITY_KV_STORE;-import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;-import static com.datastrato.graviton.Configs.ENTITY_STORE;-import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;-import static com.datastrato.graviton.Entity.EntityType.SCHEMA;--import com.datastrato.graviton.Config;-import com.datastrato.graviton.Configs;-import com.datastrato.graviton.EntityStore;-import com.datastrato.graviton.GravitonEnv;import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;-import com.datastrato.graviton.StringIdentifier;import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;import com.datastrato.graviton.exceptions.SchemaAlreadyExistsException;import com.datastrato.graviton.meta.AuditInfo;@@ -24,47 +13,15 @@ import com.datastrato.graviton.meta.CatalogEntity;import com.datastrato.graviton.rel.Schema;import com.datastrato.graviton.rel.SchemaChange;import com.google.common.collect.Maps;-import java.io.IOException;import java.time.Instant;import java.util.Arrays;import java.util.Map;-import org.apache.commons.io.FileUtils;-import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;-import org.mockito.Mockito;public class TestHiveSchema extends MiniHiveMetastoreService {- private static final String ROCKS_DB_STORE_PATH = "/tmp/graviton/test_hive_schema";-- private static EntityStore store;-- @BeforeAll- private static void setup() {- Config config = Mockito.mock(Config.class);- Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");- Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);- Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");- Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(ROCKS_DB_STORE_PATH);- Mockito.when(config.get(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS))- .thenReturn(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS.getDefaultValue());-- GravitonEnv.getInstance().initialize(config);- store = GravitonEnv.getInstance().entityStore();- }-- @AfterAll- private static void tearDown() {- try {- FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));- } catch (Exception e) {- // Ignore- }- }-- HiveCatalog initHiveCatalog() {+ private HiveCatalog initHiveCatalog() {AuditInfo auditInfo =new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -85,7 +42,7 @@ public class TestHiveSchema extends MiniHiveMetastoreService {}@Test- public void testCreateHiveSchema() throws IOException {+ public void testCreateHiveSchema() {HiveCatalog hiveCatalog = initHiveCatalog();NameIdentifier ident = NameIdentifier.of("metalake", hiveCatalog.name(), genRandomName());@@ -97,37 +54,27 @@ public class TestHiveSchema extends MiniHiveMetastoreService {Schema schema = hiveCatalog.asSchemas().createSchema(ident, comment, properties);Assertions.assertEquals(ident.name(), schema.name());Assertions.assertEquals(comment, schema.comment());- testProperties(properties, schema.properties());+ Assertions.assertEquals(properties, schema.properties());Assertions.assertTrue(hiveCatalog.asSchemas().schemaExists(ident));NameIdentifier[] idents = hiveCatalog.asSchemas().listSchemas(ident.namespace());Assertions.assertTrue(Arrays.asList(idents).contains(ident));- Assertions.assertTrue(store.exists(ident, SCHEMA));Schema loadedSchema = hiveCatalog.asSchemas().loadSchema(ident);- Assertions.assertEquals(schema.auditInfo(), loadedSchema.auditInfo());- testProperties(properties, loadedSchema.properties());-- // Test illegal identifier- NameIdentifier ident1 = NameIdentifier.of("metalake", hiveCatalog.name());- Throwable exception =- Assertions.assertThrows(- IllegalArgumentException.class,- () -> {- hiveCatalog.asSchemas().createSchema(ident1, comment, properties);- });- Assertions.assertTrue(- exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));+ Assertions.assertEquals(schema.auditInfo().creator(), loadedSchema.auditInfo().creator());+ Assertions.assertNull(loadedSchema.auditInfo().createTime());+ Assertions.assertEquals("val1", loadedSchema.properties().get("key1"));+ Assertions.assertEquals("val2", loadedSchema.properties().get("key2"));// Test schema already exists- exception =+ Throwable exception =Assertions.assertThrows(SchemaAlreadyExistsException.class,() -> {hiveCatalog.asSchemas().createSchema(ident, comment, properties);});- Assertions.assertTrue(exception.getMessage().contains("already exists in Graviton store"));+ Assertions.assertTrue(exception.getMessage().contains("already exists in Hive Metastore"));}@Test@@ -144,7 +91,8 @@ public class TestHiveSchema extends MiniHiveMetastoreService {Assertions.assertTrue(hiveCatalog.asSchemas().schemaExists(ident));Map<String, String> properties1 = hiveCatalog.asSchemas().loadSchema(ident).properties();- testProperties(properties, properties1);+ Assertions.assertEquals("val1", properties1.get("key1"));+ Assertions.assertEquals("val2", properties1.get("key2"));hiveCatalog.asSchemas()@@ -159,10 +107,9 @@ public class TestHiveSchema extends MiniHiveMetastoreService {Assertions.assertEquals(createdSchema.auditInfo().creator(), alteredSchema.auditInfo().creator());- Assertions.assertEquals(- createdSchema.auditInfo().createTime(), alteredSchema.auditInfo().createTime());- Assertions.assertNotNull(alteredSchema.auditInfo().lastModifier());- Assertions.assertNotNull(alteredSchema.auditInfo().lastModifiedTime());+ Assertions.assertNull(alteredSchema.auditInfo().createTime());+ Assertions.assertNull(alteredSchema.auditInfo().lastModifier());+ Assertions.assertNull(alteredSchema.auditInfo().lastModifiedTime());hiveCatalog.asSchemas()@@ -177,14 +124,13 @@ public class TestHiveSchema extends MiniHiveMetastoreService {Assertions.assertEquals(createdSchema.auditInfo().creator(), alteredSchema1.auditInfo().creator());- Assertions.assertEquals(- createdSchema.auditInfo().createTime(), alteredSchema1.auditInfo().createTime());- Assertions.assertNotNull(alteredSchema1.auditInfo().lastModifier());- Assertions.assertNotNull(alteredSchema1.auditInfo().lastModifiedTime());+ Assertions.assertNull(alteredSchema1.auditInfo().createTime());+ Assertions.assertNull(alteredSchema1.auditInfo().lastModifier());+ Assertions.assertNull(alteredSchema1.auditInfo().lastModifiedTime());}@Test- public void testDropSchema() throws IOException {+ public void testDropSchema() {HiveCatalog hiveCatalog = initHiveCatalog();NameIdentifier ident = NameIdentifier.of("metalake", hiveCatalog.name(), genRandomName());@@ -197,17 +143,5 @@ public class TestHiveSchema extends MiniHiveMetastoreService {Assertions.assertTrue(hiveCatalog.asSchemas().schemaExists(ident));hiveCatalog.asSchemas().dropSchema(ident, true);Assertions.assertFalse(hiveCatalog.asSchemas().schemaExists(ident));- Assertions.assertFalse(store.exists(ident, SCHEMA));- }-- private void testProperties(Map<String, String> expectedProps, Map<String, String> testProps) {- expectedProps.forEach(- (k, v) -> {- Assertions.assertEquals(v, testProps.get(k));- });-- Assertions.assertTrue(testProps.containsKey(StringIdentifier.ID_KEY));- StringIdentifier StringId = StringIdentifier.fromString(testProps.get(StringIdentifier.ID_KEY));- Assertions.assertEquals(StringId.toString(), testProps.get(StringIdentifier.ID_KEY));}}diff --git a/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveTable.java b/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveTable.javaindex f079525c70..012a58fef2 100644--- a/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveTable.java+++ b/catalogs/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/TestHiveTable.java@@ -4,22 +4,13 @@*/package com.datastrato.graviton.catalog.hive;-import static com.datastrato.graviton.Configs.DEFAULT_ENTITY_KV_STORE;-import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;-import static com.datastrato.graviton.Configs.ENTITY_STORE;-import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;-import static com.datastrato.graviton.Entity.EntityType.TABLE;import static com.datastrato.graviton.rel.transforms.Transforms.day;import static com.datastrato.graviton.rel.transforms.Transforms.identity;-import com.datastrato.graviton.Config;-import com.datastrato.graviton.Configs;-import com.datastrato.graviton.EntityStore;-import com.datastrato.graviton.GravitonEnv;import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;-import com.datastrato.graviton.StringIdentifier;import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;+import com.datastrato.graviton.exceptions.NoSuchSchemaException;import com.datastrato.graviton.exceptions.TableAlreadyExistsException;import com.datastrato.graviton.meta.AuditInfo;import com.datastrato.graviton.meta.CatalogEntity;@@ -39,13 +30,10 @@ import java.io.IOException;import java.time.Instant;import java.util.Arrays;import java.util.Map;-import org.apache.commons.io.FileUtils;-import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;-import org.mockito.Mockito;public class TestHiveTable extends MiniHiveMetastoreService {@@ -54,50 +42,24 @@ public class TestHiveTable extends MiniHiveMetastoreService {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 final String ROCKS_DB_STORE_PATH = "/tmp/graviton/test_hive_table";private static HiveCatalog hiveCatalog;private static HiveSchema hiveSchema;-- private static EntityStore store;+ private static final NameIdentifier schemaIdent =+ NameIdentifier.of(META_LAKE_NAME, HIVE_CATALOG_NAME, HIVE_SCHEMA_NAME);@BeforeAllprivate static void setup() {- mockStore();initHiveCatalog();initHiveSchema();}- @AfterAll- private static void tearDown() {- try {- FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));- } catch (Exception e) {- // Ignore- }- }-@AfterEachprivate void resetSchema() {- hiveCatalog.asSchemas().dropSchema(hiveSchema.nameIdentifier(), true);+ hiveCatalog.asSchemas().dropSchema(schemaIdent, true);initHiveSchema();}- private static void mockStore() {- Config config = Mockito.mock(Config.class);- Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");- Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);- Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");- Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(ROCKS_DB_STORE_PATH);- Mockito.when(config.get(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS))- .thenReturn(Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS.getDefaultValue());-- GravitonEnv.getInstance().initialize(config);- store = GravitonEnv.getInstance().entityStore();- }-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");@@ -181,17 +143,21 @@ public class TestHiveTable extends MiniHiveMetastoreService {sortOrders);Assertions.assertEquals(tableIdentifier.name(), table.name());Assertions.assertEquals(HIVE_COMMENT, table.comment());- testProperties(properties, table.properties());+ Assertions.assertEquals("val1", table.properties().get("key1"));+ Assertions.assertEquals("val2", table.properties().get("key2"));Table loadedTable = hiveCatalog.asTableCatalog().loadTable(tableIdentifier);- Assertions.assertEquals(table.auditInfo(), loadedTable.auditInfo());- testProperties(properties, loadedTable.properties());+ Assertions.assertEquals(table.auditInfo().creator(), loadedTable.auditInfo().creator());+ Assertions.assertNull(loadedTable.auditInfo().lastModifier());+ Assertions.assertNull(loadedTable.auditInfo().lastModifiedTime());++ Assertions.assertEquals("val1", loadedTable.properties().get("key1"));+ Assertions.assertEquals("val2", loadedTable.properties().get("key2"));Assertions.assertTrue(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));NameIdentifier[] tableIdents =hiveCatalog.asTableCatalog().listTables(tableIdentifier.namespace());Assertions.assertTrue(Arrays.asList(tableIdents).contains(tableIdentifier));- Assertions.assertTrue(store.exists(tableIdentifier, TABLE));// Compare sort and orderAssertions.assertEquals(distribution.number(), loadedTable.distribution().number());@@ -208,23 +174,6 @@ public class TestHiveTable extends MiniHiveMetastoreService {// Test exceptionThrowable exception =- Assertions.assertThrows(- IllegalArgumentException.class,- () ->- hiveCatalog- .asTableCatalog()- .createTable(- hiveSchema.nameIdentifier(),- columns,- HIVE_COMMENT,- properties,- new Transform[0],- distribution,- sortOrders));- Assertions.assertTrue(- exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));-- exception =Assertions.assertThrows(TableAlreadyExistsException.class,() ->@@ -242,7 +191,7 @@ public class TestHiveTable extends MiniHiveMetastoreService {}@Test- public void testCreatePartitionedHiveTable() throws IOException {+ public void testCreatePartitionedHiveTable() {NameIdentifier tableIdentifier =NameIdentifier.of(META_LAKE_NAME, hiveCatalog.name(), hiveSchema.name(), genRandomName());Map<String, String> properties = Maps.newHashMap();@@ -271,19 +220,24 @@ public class TestHiveTable extends MiniHiveMetastoreService {.createTable(tableIdentifier, columns, HIVE_COMMENT, properties, partitions);Assertions.assertEquals(tableIdentifier.name(), table.name());Assertions.assertEquals(HIVE_COMMENT, table.comment());- testProperties(properties, table.properties());+ Assertions.assertEquals("val1", table.properties().get("key1"));+ Assertions.assertEquals("val2", table.properties().get("key2"));Assertions.assertArrayEquals(partitions, table.partitioning());Table loadedTable = hiveCatalog.asTableCatalog().loadTable(tableIdentifier);- Assertions.assertEquals(table.auditInfo(), loadedTable.auditInfo());- testProperties(properties, loadedTable.properties());++ Assertions.assertEquals(table.auditInfo().creator(), loadedTable.auditInfo().creator());+ Assertions.assertNull(loadedTable.auditInfo().lastModifier());+ Assertions.assertNull(loadedTable.auditInfo().lastModifiedTime());++ Assertions.assertEquals("val1", loadedTable.properties().get("key1"));+ Assertions.assertEquals("val2", loadedTable.properties().get("key2"));Assertions.assertArrayEquals(partitions, loadedTable.partitioning());Assertions.assertTrue(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));NameIdentifier[] tableIdents =hiveCatalog.asTableCatalog().listTables(tableIdentifier.namespace());Assertions.assertTrue(Arrays.asList(tableIdents).contains(tableIdentifier));- Assertions.assertTrue(store.exists(tableIdentifier, TABLE));// Test exceptionThrowable exception =@@ -334,7 +288,7 @@ public class TestHiveTable extends MiniHiveMetastoreService {}@Test- public void testDropHiveTable() throws IOException {+ public void testDropHiveTable() {NameIdentifier tableIdentifier =NameIdentifier.of(META_LAKE_NAME, hiveCatalog.name(), hiveSchema.name(), genRandomName());Map<String, String> properties = Maps.newHashMap();@@ -369,25 +323,15 @@ public class TestHiveTable extends MiniHiveMetastoreService {Assertions.assertTrue(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));hiveCatalog.asTableCatalog().dropTable(tableIdentifier);Assertions.assertFalse(hiveCatalog.asTableCatalog().tableExists(tableIdentifier));- Assertions.assertFalse(store.exists(tableIdentifier, TABLE));}@Testpublic void testListTableException() {+ Namespace tableNs = Namespace.of("metalake", hiveCatalog.name(), "not_exist_db");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"));+ NoSuchSchemaException.class, () -> hiveCatalog.asTableCatalog().listTables(tableNs));+ Assertions.assertTrue(exception.getMessage().contains("Schema (database) does not exist"));}@Test@@ -462,14 +406,9 @@ public class TestHiveTable extends MiniHiveMetastoreService {Assertions.assertFalse(alteredTable.properties().containsKey("key1"));Assertions.assertEquals(alteredTable.properties().get("key2"), "val2_new");- Assertions.assertFalse(store.exists(tableIdentifier, TABLE));- Assertions.assertTrue(store.exists(((HiveTable) alteredTable).nameIdentifier(), TABLE));-Assertions.assertEquals(createdTable.auditInfo().creator(), alteredTable.auditInfo().creator());- Assertions.assertEquals(- createdTable.auditInfo().createTime(), alteredTable.auditInfo().createTime());- Assertions.assertNotNull(alteredTable.auditInfo().lastModifier());- Assertions.assertNotNull(alteredTable.auditInfo().lastModifiedTime());+ Assertions.assertNull(alteredTable.auditInfo().lastModifier());+ Assertions.assertNull(alteredTable.auditInfo().lastModifiedTime());Assertions.assertNotNull(alteredTable.partitioning());Assertions.assertArrayEquals(createdTable.partitioning(), alteredTable.partitioning());@@ -509,22 +448,9 @@ public class TestHiveTable extends MiniHiveMetastoreService {Assertions.assertEquals(createdTable.auditInfo().creator(), alteredTable1.auditInfo().creator());- Assertions.assertEquals(- createdTable.auditInfo().createTime(), alteredTable1.auditInfo().createTime());- Assertions.assertNotNull(alteredTable1.auditInfo().lastModifier());- Assertions.assertNotNull(alteredTable1.auditInfo().lastModifiedTime());+ Assertions.assertNull(alteredTable1.auditInfo().lastModifier());+ Assertions.assertNull(alteredTable1.auditInfo().lastModifiedTime());Assertions.assertNotNull(alteredTable.partitioning());Assertions.assertArrayEquals(createdTable.partitioning(), alteredTable.partitioning());}-- private void testProperties(Map<String, String> expectedProps, Map<String, String> testProps) {- expectedProps.forEach(- (k, v) -> {- Assertions.assertEquals(v, testProps.get(k));- });-- Assertions.assertTrue(testProps.containsKey(StringIdentifier.ID_KEY));- StringIdentifier StringId = StringIdentifier.fromString(testProps.get(StringIdentifier.ID_KEY));- Assertions.assertEquals(StringId.toString(), testProps.get(StringIdentifier.ID_KEY));- }}diff --git a/core/src/main/java/com/datastrato/graviton/GravitonEnv.java b/core/src/main/java/com/datastrato/graviton/GravitonEnv.javaindex 75024e4d42..0035d15646 100644--- a/core/src/main/java/com/datastrato/graviton/GravitonEnv.java+++ b/core/src/main/java/com/datastrato/graviton/GravitonEnv.java@@ -78,7 +78,8 @@ public class GravitonEnv {// Create and initialize Catalog related modulesthis.catalogManager = new CatalogManager(config, entityStore, idGenerator);- this.catalogOperationDispatcher = new CatalogOperationDispatcher(catalogManager);+ this.catalogOperationDispatcher =+ new CatalogOperationDispatcher(catalogManager, entityStore, idGenerator);this.auxServiceManager = new AuxiliaryServiceManager();this.auxServiceManager.serviceInit(diff --git a/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.java b/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.javaindex 1fc7fdeecc..4dfe727f9d 100644--- a/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.java+++ b/core/src/main/java/com/datastrato/graviton/catalog/CatalogOperationDispatcher.java@@ -4,15 +4,27 @@*/package com.datastrato.graviton.catalog;+import static com.datastrato.graviton.Entity.EntityType.SCHEMA;+import static com.datastrato.graviton.Entity.EntityType.TABLE;++import com.datastrato.graviton.EntityStore;+import com.datastrato.graviton.HasIdentifier;import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.StringIdentifier;+import com.datastrato.graviton.catalog.rel.EntityCombinedSchema;+import com.datastrato.graviton.catalog.rel.EntityCombinedTable;import com.datastrato.graviton.exceptions.IllegalNameIdentifierException;import com.datastrato.graviton.exceptions.NoSuchCatalogException;+import com.datastrato.graviton.exceptions.NoSuchEntityException;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.SchemaEntity;+import com.datastrato.graviton.meta.TableEntity;import com.datastrato.graviton.rel.Column;import com.datastrato.graviton.rel.Distribution;import com.datastrato.graviton.rel.Schema;@@ -23,13 +35,17 @@ import com.datastrato.graviton.rel.Table;import com.datastrato.graviton.rel.TableCatalog;import com.datastrato.graviton.rel.TableChange;import com.datastrato.graviton.rel.transforms.Transform;+import com.datastrato.graviton.storage.IdGenerator;import com.datastrato.graviton.utils.ThrowableFunction;import com.google.common.annotations.VisibleForTesting;+import java.time.Instant;import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.stream.Stream;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** A catalog operation dispatcher that dispatches the catalog operations to the underlying catalog@@ -37,15 +53,26 @@ import java.util.stream.Stream;*/public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas {+ private static final Logger LOG = LoggerFactory.getLogger(CatalogOperationDispatcher.class);+private final CatalogManager catalogManager;+ private final EntityStore store;++ private final IdGenerator idGenerator;+/*** Creates a new CatalogOperationDispatcher instance.** @param catalogManager The CatalogManager instance to be used for catalog operations.+ * @param store The EntityStore instance to be used for catalog operations.+ * @param idGenerator The IdGenerator instance to be used for catalog operations.*/- public CatalogOperationDispatcher(CatalogManager catalogManager) {+ public CatalogOperationDispatcher(+ CatalogManager catalogManager, EntityStore store, IdGenerator idGenerator) {this.catalogManager = catalogManager;+ this.store = store;+ this.idGenerator = idGenerator;}/**@@ -58,10 +85,8 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas*/@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {- NameIdentifier catalogIdent = NameIdentifier.of(namespace.levels());-return doWithCatalog(- catalogIdent,+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),c -> c.doWithSchemaOps(s -> s.listSchemas(namespace)),NoSuchCatalogException.class);}@@ -80,13 +105,42 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> metadata)throws NoSuchCatalogException, SchemaAlreadyExistsException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ long uid = idGenerator.nextId();+ // Add StringIdentifier to the properties, the specific catalog will handle this+ // StringIdentifier to make sure only when the operation is successful, the related+ // SchemaEntity will be visible.+ StringIdentifier stringId = StringIdentifier.fromId(uid);+ Map<String, String> updatedProperties = StringIdentifier.addToProperties(stringId, metadata);- return doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, metadata)),- NoSuchCatalogException.class,- SchemaAlreadyExistsException.class);+ Schema schema =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),+ NoSuchCatalogException.class,+ SchemaAlreadyExistsException.class);++ SchemaEntity schemaEntity =+ new SchemaEntity.Builder()+ .withId(uid)+ .withName(ident.name())+ .withNamespace(ident.namespace())+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton") // TODO. hardcoded as user "graviton" for now, will+ // change to real user once user system is ready.+ .withCreateTime(Instant.now())+ .build())+ .build();++ try {+ store.put(schemaEntity, true /* overwrite */);+ } catch (Exception e) {+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);+ return EntityCombinedSchema.of(schema);+ }++ // Merge both the metadata from catalog operation and the metadata from entity store.+ return EntityCombinedSchema.of(schema, schemaEntity);}/**@@ -98,12 +152,25 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas*/@Overridepublic Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ Schema schema =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithSchemaOps(s -> s.loadSchema(ident)),+ NoSuchSchemaException.class);- return doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.loadSchema(ident)),- NoSuchSchemaException.class);+ StringIdentifier stringId = getStringIdFromProperties(schema.properties());+ // Case 1: The schema is not created by Graviton.+ if (stringId == null) {+ return EntityCombinedSchema.of(schema);+ }++ SchemaEntity schemaEntity =+ operateOnEntity(+ ident,+ identifier -> store.get(identifier, SCHEMA, SchemaEntity.class),+ "GET",+ stringId.id());+ return EntityCombinedSchema.of(schema, schemaEntity);}/**@@ -118,12 +185,44 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas@Overridepublic Schema alterSchema(NameIdentifier ident, SchemaChange... changes)throws NoSuchSchemaException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ Schema alteredSchema =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithSchemaOps(s -> s.alterSchema(ident, changes)),+ NoSuchSchemaException.class);- return doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.alterSchema(ident, changes)),- NoSuchSchemaException.class);+ StringIdentifier stringId = getStringIdFromProperties(alteredSchema.properties());+ // Case 1: The schema is not created by Graviton.+ if (stringId == null) {+ return EntityCombinedSchema.of(alteredSchema);+ }++ SchemaEntity updatedSchemaEntity =+ operateOnEntity(+ ident,+ id ->+ store.update(+ id,+ SchemaEntity.class,+ SCHEMA,+ schemaEntity ->+ new SchemaEntity.Builder()+ .withId(schemaEntity.id())+ .withName(schemaEntity.name())+ .withNamespace(ident.namespace())+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator(schemaEntity.auditInfo().creator())+ .withCreateTime(schemaEntity.auditInfo().createTime())+ .withLastModifier(+ "graviton") // TODO. hardcoded as user "graviton"+ // for now, will change to real user once user system is ready.+ .withLastModifiedTime(Instant.now())+ .build())+ .build()),+ "UPDATE",+ stringId.id());+ return EntityCombinedSchema.of(alteredSchema, updatedSchemaEntity);}/**@@ -136,12 +235,23 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas*/@Overridepublic boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ boolean dropped =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithSchemaOps(s -> s.dropSchema(ident, cascade)),+ NonEmptySchemaException.class);- return doWithCatalog(- catalogIdent,- c -> c.doWithSchemaOps(s -> s.dropSchema(ident, cascade)),- NonEmptySchemaException.class);+ if (!dropped) {+ return false;+ }++ try {+ store.delete(ident, SCHEMA, cascade);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }++ return true;}/**@@ -154,10 +264,8 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas*/@Overridepublic NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {- NameIdentifier catalogIdent = NameIdentifier.of(namespace.levels());-return doWithCatalog(- catalogIdent,+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),c -> c.doWithTableOps(t -> t.listTables(namespace)),NoSuchSchemaException.class);}@@ -171,10 +279,25 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas*/@Overridepublic Table loadTable(NameIdentifier ident) throws NoSuchTableException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ Table table =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithTableOps(t -> t.loadTable(ident)),+ NoSuchTableException.class);- return doWithCatalog(- catalogIdent, c -> c.doWithTableOps(t -> t.loadTable(ident)), NoSuchTableException.class);+ StringIdentifier stringId = getStringIdFromProperties(table.properties());+ // Case 1: The table is not created by Graviton.+ if (stringId == null) {+ return EntityCombinedTable.of(table);+ }++ TableEntity tableEntity =+ operateOnEntity(+ ident,+ identifier -> store.get(identifier, TABLE, TableEntity.class),+ "GET",+ stringId.id());+ return EntityCombinedTable.of(table, tableEntity);}/**@@ -199,23 +322,50 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemasDistribution distribution,SortOrder[] sortOrders)throws NoSuchSchemaException, TableAlreadyExistsException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ long uid = idGenerator.nextId();+ // Add StringIdentifier to the properties, the specific catalog will handle this+ // StringIdentifier to make sure only when the operation is successful, the related+ // TableEntity will be visible.+ StringIdentifier stringId = StringIdentifier.fromId(uid);+ Map<String, String> updatedProperties = StringIdentifier.addToProperties(stringId, properties);- return doWithCatalog(- catalogIdent,- c ->- c.doWithTableOps(- t ->- t.createTable(- ident,- columns,- comment,- properties,- partitions == null ? new Transform[0] : partitions,- distribution == null ? Distribution.NONE : distribution,- sortOrders == null ? new SortOrder[0] : sortOrders)),- NoSuchSchemaException.class,- TableAlreadyExistsException.class);+ Table table =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c ->+ c.doWithTableOps(+ t ->+ t.createTable(+ ident,+ columns,+ comment,+ updatedProperties,+ partitions == null ? new Transform[0] : partitions,+ distribution == null ? Distribution.NONE : distribution,+ sortOrders == null ? new SortOrder[0] : sortOrders)),+ NoSuchSchemaException.class,+ TableAlreadyExistsException.class);++ TableEntity tableEntity =+ new TableEntity.Builder()+ .withId(uid)+ .withName(ident.name())+ .withNamespace(ident.namespace())+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton")+ .withCreateTime(Instant.now())+ .build())+ .build();++ try {+ store.put(tableEntity, true /* overwrite */);+ } catch (Exception e) {+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);+ return EntityCombinedTable.of(table);+ }++ return EntityCombinedTable.of(table, tableEntity);}/**@@ -231,12 +381,55 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas@Overridepublic Table alterTable(NameIdentifier ident, TableChange... changes)throws NoSuchTableException, IllegalArgumentException {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());- return doWithCatalog(- catalogIdent,- c -> c.doWithTableOps(t -> t.alterTable(ident, changes)),- NoSuchTableException.class,- IllegalArgumentException.class);+ Table alteredTable =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithTableOps(t -> t.alterTable(ident, changes)),+ NoSuchTableException.class,+ IllegalArgumentException.class);++ StringIdentifier stringId = getStringIdFromProperties(alteredTable.properties());+ // Case 1: The table is not created by Graviton.+ if (stringId == null) {+ return EntityCombinedTable.of(alteredTable);+ }++ TableEntity updatedTableEntity =+ operateOnEntity(+ ident,+ id ->+ store.update(+ id,+ TableEntity.class,+ TABLE,+ tableEntity -> {+ String newName =+ Arrays.stream(changes)+ .filter(c -> c instanceof TableChange.RenameTable)+ .map(c -> ((TableChange.RenameTable) c).getNewName())+ .reduce((c1, c2) -> c2)+ .orElse(tableEntity.name());++ return new TableEntity.Builder()+ .withId(tableEntity.id())+ .withName(newName)+ .withNamespace(ident.namespace())+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator(tableEntity.auditInfo().creator())+ .withCreateTime(tableEntity.auditInfo().createTime())+ .withLastModifier(+ "graviton") // hardcoded as user "graviton" for now, will+ // change+ // to real user once user system is ready.+ .withLastModifiedTime(Instant.now())+ .build())+ .build();+ }),+ "UPDATE",+ stringId.id());++ return EntityCombinedTable.of(alteredTable, updatedTableEntity);}/**@@ -249,18 +442,30 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas*/@Overridepublic boolean dropTable(NameIdentifier ident) {- NameIdentifier catalogIdent = NameIdentifier.of(ident.namespace().levels());+ boolean dropped =+ doWithCatalog(+ getCatalogIdentifier(ident),+ c -> c.doWithTableOps(t -> t.dropTable(ident)),+ NoSuchTableException.class);- return doWithCatalog(- catalogIdent, c -> c.doWithTableOps(t -> t.dropTable(ident)), NoSuchTableException.class);+ if (!dropped) {+ return false;+ }++ try {+ store.delete(ident, TABLE);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }++ return true;}private <R, E extends Throwable> R doWithCatalog(NameIdentifier ident, ThrowableFunction<CatalogManager.CatalogWrapper, R> fn, Class<E> ex)throws E {try {- NameIdentifier catalogIdent = getCatalogIdentifier(ident);- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(catalogIdent);+ CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);return fn.apply(c);} catch (Throwable throwable) {if (ex.isInstance(throwable)) {@@ -277,9 +482,7 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemasClass<E2> ex2)throws E1, E2 {try {- NameIdentifier catalogIdent = getCatalogIdentifier(ident);-- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(catalogIdent);+ CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);return fn.apply(c);} catch (Throwable throwable) {if (ex1.isInstance(throwable)) {@@ -292,6 +495,43 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas}}+ private StringIdentifier getStringIdFromProperties(Map<String, String> properties) {+ try {+ StringIdentifier stringId = StringIdentifier.fromProperties(properties);+ if (stringId == null) {+ LOG.warn(FormattedErrorMessages.STRING_ID_NOT_FOUND);+ }+ return stringId;+ } catch (IllegalArgumentException e) {+ LOG.warn(FormattedErrorMessages.STRING_ID_PARSE_ERROR, e.getMessage());+ return null;+ }+ }++ private <R extends HasIdentifier> R operateOnEntity(+ NameIdentifier ident, ThrowableFunction<NameIdentifier, R> fn, String opName, long id) {+ R ret = null;+ try {+ ret = fn.apply(ident);+ } catch (NoSuchEntityException e) {+ // Case 2: The table is created by Graviton, but has no corresponding entity in Graviton.+ LOG.error(FormattedErrorMessages.ENTITY_NOT_FOUND, ident);+ } catch (Exception e) {+ // Case 3: The table is created by Graviton, but failed to operate the corresponding entity+ // in Graviton+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, opName, ident, e);+ }++ // Case 4: The table is created by Graviton, but the uid in the corresponding entity is not+ // matched.+ if (ret != null && ret.id() != id) {+ LOG.error(FormattedErrorMessages.ENTITY_UNMATCHED, ident, ret.id(), id);+ ret = null;+ }++ return ret;+ }+@VisibleForTesting// TODO(xun): Remove this method when we implement a better way to get the catalog identifier// [#257] Add an explicit get catalog functions in NameIdentifier@@ -313,4 +553,32 @@ public class CatalogOperationDispatcher implements TableCatalog, SupportsSchemas}return NameIdentifier.of(allElems.get(0), allElems.get(1));}++ private static final class FormattedErrorMessages {+ static final String STORE_OP_FAILURE =+ "Failed to {} entity for {} in "+ + "Graviton, with this situation the returned object will not contain the metadata from "+ + "Graviton.";++ static final String STRING_ID_NOT_FOUND =+ "String identifier is not set in schema properties, "+ + "this is because the schema is not created by Graviton, or the schema is created by "+ + "Graviton but the string identifier is removed by the user.";++ static final String STRING_ID_PARSE_ERROR =+ "Failed to get string identifier from schema "+ + "properties: {}, this maybe caused by the same-name string identifier is set by the user "+ + "with unsupported format.";++ static final String ENTITY_NOT_FOUND =+ "Entity for {} doesn't exist in Graviton, "+ + "this is unexpected if this is created by Graviton. With this situation the "+ + "returned object will not contain the metadata from Graviton";++ static final String ENTITY_UNMATCHED =+ "Entity {} with uid {} doesn't match the string "+ + "identifier in the property {}, this is unexpected if this object is created by "+ + "Graviton. This might be due to some operations that are not performed through Graviton. "+ + "With this situation the returned object will not contain the metadata from Graviton";+ }}diff --git a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseColumn.java b/core/src/main/java/com/datastrato/graviton/catalog/rel/BaseColumn.javasimilarity index 71%rename from core/src/main/java/com/datastrato/graviton/meta/rel/BaseColumn.javarename to core/src/main/java/com/datastrato/graviton/catalog/rel/BaseColumn.javaindex c9d1c6a6aa..7e1d49e3e9 100644--- a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseColumn.java+++ b/core/src/main/java/com/datastrato/graviton/catalog/rel/BaseColumn.java@@ -3,27 +3,18 @@* This software is licensed under the Apache License version 2.*/-package com.datastrato.graviton.meta.rel;+package com.datastrato.graviton.catalog.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;/** An abstract class representing a base column in a relational database. */-@EqualsAndHashCode@ToString-public abstract class BaseColumn implements Column, Entity {- public static final Field NAME = Field.required("name", String.class, "The column's name");- public static final Field COMMENT =- Field.optional("comment", String.class, "The comment or description for the column");- public static final Field TYPE =- Field.required("dataType", Type.class, "The data type of the column");+@EqualsAndHashCode+public abstract class BaseColumn implements Column {protected String name;@@ -62,31 +53,6 @@ public abstract class BaseColumn implements Column, Entity {return comment;}- /**- * Returns the type of the entity, which is {@link EntityType#COLUMN}.- *- * @return The type of the entity.- */- @Override- public EntityType type() {- return EntityType.COLUMN;- }-- /**- * Returns a map of the fields and their corresponding values for this column.- *- * @return A map of the fields and values.- */- @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;- }-/*** Builder interface for creating instances of {@link BaseColumn}.*@@ -160,7 +126,6 @@ public abstract class BaseColumn implements Column, Entity {@Overridepublic T build() {T t = internalBuild();- t.validate();return t;}diff --git a/core/src/main/java/com/datastrato/graviton/catalog/rel/BaseSchema.java b/core/src/main/java/com/datastrato/graviton/catalog/rel/BaseSchema.javanew file mode 100644index 0000000000..0fdb22d20a--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/catalog/rel/BaseSchema.java@@ -0,0 +1,147 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog.rel;++import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.rel.Schema;+import java.util.Map;+import javax.annotation.Nullable;+import lombok.ToString;++/** An abstract class representing a base schema in a relational database. */+@ToString+public abstract class BaseSchema implements Schema {++ protected String name;++ @Nullable protected String comment;++ @Nullable protected Map<String, String> properties;++ protected AuditInfo auditInfo;++ /** Returns the name of the schema. */+ @Override+ public String name() {+ return name;+ }++ /** Returns the comment or description for the schema. */+ @Override+ public String comment() {+ return comment;+ }++ /** Returns the associated properties of the schema. */+ @Override+ public Map<String, String> properties() {+ return properties;+ }++ /** Returns the audit details of the schema. */+ @Override+ public AuditInfo auditInfo() {+ return auditInfo;+ }++ /**+ * Builder interface for creating instances of {@link BaseSchema}.+ *+ * @param <SELF> The type of the builder.+ * @param <T> The type of the schema being built.+ */+ interface Builder<SELF extends Builder<SELF, T>, T extends BaseSchema> {++ SELF withName(String name);++ SELF withComment(String comment);++ SELF withProperties(Map<String, String> properties);++ SELF withAuditInfo(AuditInfo auditInfo);++ T build();+ }++ /**+ * An abstract class implementing the builder interface for {@link BaseSchema}.+ *+ * @param <SELF> The type of the builder.+ * @param <T> The type of the schema being built.+ */+ public abstract static class BaseSchemaBuilder<+ SELF extends Builder<SELF, T>, T extends BaseSchema>+ implements Builder<SELF, T> {+ protected String name;+ protected String comment;+ protected Map<String, String> properties;+ protected AuditInfo auditInfo;++ /**+ * Sets the name of the schema.+ *+ * @param name The name of the schema.+ * @return The builder instance.+ */+ @Override+ public SELF withName(String name) {+ this.name = name;+ return self();+ }++ /**+ * Sets the comment of the schema.+ *+ * @param comment The comment or description for the schema.+ * @return The builder instance.+ */+ @Override+ public SELF withComment(String comment) {+ this.comment = comment;+ return self();+ }++ /**+ * Sets the associated properties of the schema.+ *+ * @param properties The associated properties of the schema.+ * @return The builder instance.+ */+ @Override+ public SELF withProperties(Map<String, String> properties) {+ this.properties = properties;+ return self();+ }++ /**+ * Sets the audit details of the schema.+ *+ * @param auditInfo The audit details of the schema.+ * @return The builder instance.+ */+ @Override+ public SELF withAuditInfo(AuditInfo auditInfo) {+ this.auditInfo = auditInfo;+ return self();+ }++ /**+ * Builds the instance of the schema with the provided attributes.+ *+ * @return The built schema instance.+ */+ @Override+ public T build() {+ T t = internalBuild();+ 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/catalog/rel/BaseTable.javasimilarity index 53%rename from core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.javarename to core/src/main/java/com/datastrato/graviton/catalog/rel/BaseTable.javaindex 0f4db61dbe..da392c3c40 100644--- a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java+++ b/core/src/main/java/com/datastrato/graviton/catalog/rel/BaseTable.java@@ -2,43 +2,21 @@* Copyright 2023 Datastrato.* This software is licensed under the Apache License version 2.*/+package com.datastrato.graviton.catalog.rel;-package com.datastrato.graviton.meta.rel;--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.Distribution;import com.datastrato.graviton.rel.SortOrder;import com.datastrato.graviton.rel.Table;import com.datastrato.graviton.rel.transforms.Transform;-import com.google.common.base.Objects;-import com.google.common.collect.Maps;import java.util.Map;import javax.annotation.Nullable;import lombok.ToString;/** An abstract class representing a base table in a relational database. */@ToString-public class BaseTable implements Table, Entity, HasIdentifier {-- public static final Field ID = Field.required("id", Long.class, "The table's unique identifier");- public static final Field NAME = Field.required("name", String.class, "The table's name");- public static final Field COMMENT =- Field.optional("comment", String.class, "The comment or description for the table");- public static final Field PROPERTIES =- Field.optional("properties", Map.class, "The associated properties of the table");- public static final Field AUDIT_INFO =- Field.required("audit_info", AuditInfo.class, "The audit details of the table");-- // we do not save columns in Graviton store, so it is an optional field- public static final Field COLUMNS =- Field.optional("columns", Column[].class, "The columns that make up the table");-- protected Long id;+public abstract class BaseTable implements Table {protected String name;@@ -50,148 +28,63 @@ public class BaseTable implements Table, Entity, HasIdentifier {protected Column[] columns;- protected Namespace namespace;-@Nullable protected Transform[] partitions;@Nullable protected SortOrder[] sortOrders;@Nullable protected Distribution distribution;- /**- * Returns a map of the fields and their corresponding values for this table.- *- * @return A map of the fields and values.- */- @Override- public Map<Field, Object> fields() {- Map<Field, Object> fields = Maps.newHashMap();- fields.put(ID, id);- fields.put(NAME, name);- fields.put(COMMENT, comment);- fields.put(PROPERTIES, properties);- fields.put(AUDIT_INFO, auditInfo);- fields.put(COLUMNS, columns);-- return fields;- }-- /**- * Returns the audit details of the table.- *- * @return The audit details of the table.- */+ /** Returns the audit details of the table. */@Overridepublic AuditInfo auditInfo() {return auditInfo;}- /**- * Returns the name of the table.- *- * @return The name of the table.- */+ /** Returns the name of the table. */@Overridepublic String name() {return name;}- /**- * Returns the unique id of the table.- *- * @return The unique id of the table.- */- @Override- public Long id() {- return id;- }-- /**- * Returns an array of columns that make up the table.- *- * @return An array of columns.- */+ /** Returns an array of columns that make up the table. */@Overridepublic Column[] columns() {return columns;}- /**- * Returns the comment or description for the table.- *- * @return The comment or description for the table.- */+ /** Returns the comment or description for the table. */@Nullable@Overridepublic String comment() {return comment;}- /**- * Returns the associated properties of the table.- *- * @return The associated properties of the table.- */+ /** Returns the associated properties of the table. */@Overridepublic Map<String, String> properties() {return properties;}- /**- * Returns the namespace of the table.- *- * @return The namespace of the table.- */- @Override- public Namespace namespace() {- return namespace;- }-+ /** Returns the partitioning strategies of the table. */@Overridepublic Transform[] partitioning() {return partitions;}+ /** Return the array of {@link SortOrder} of the table. */@Overridepublic SortOrder[] sortOrder() {return sortOrders;}- @Override- public Distribution distribution() {- return distribution;- }-/**- * Returns the type of the entity, which is {@link EntityType#TABLE}.+ * Returns the distribution strategy of the table.*- * @return The type of the entity.+ * @return*/@Override- public EntityType type() {- return EntityType.TABLE;- }-- // Ignore field namespace, columns and comment- @Override- public boolean equals(Object o) {- if (this == o) {- return true;- }- if (o == null || getClass() != o.getClass()) {- return false;- }-- BaseTable baseTable = (BaseTable) o;- return Objects.equal(id, baseTable.id)- && Objects.equal(name, baseTable.name)- && Objects.equal(properties, baseTable.properties)- && Objects.equal(auditInfo, baseTable.auditInfo);- }-- @Override- public int hashCode() {- return Objects.hashCode(id, name, comment, properties, auditInfo);+ public Distribution distribution() {+ return distribution;}/**@@ -201,9 +94,6 @@ public class BaseTable implements Table, Entity, HasIdentifier {* @param <T> The type of the table being built.*/interface Builder<SELF extends Builder<SELF, T>, T extends BaseTable> {- SELF withId(Long id);-- SELF withNameSpace(Namespace namespace);SELF withName(String name);@@ -232,9 +122,7 @@ public class BaseTable implements Table, Entity, HasIdentifier {*/public abstract static class BaseTableBuilder<SELF extends Builder<SELF, T>, T extends BaseTable>implements Builder<SELF, T> {- protected Long id;protected String name;- protected Namespace namespace;protected String comment;protected Map<String, String> properties;protected AuditInfo auditInfo;@@ -244,30 +132,6 @@ public class BaseTable implements Table, Entity, HasIdentifier {protected Distribution distribution;- /**- * Sets the unique identifier of the table.- *- * @param id The unique identifier of the table.- * @return The builder instance.- */- @Override- public SELF withId(Long id) {- this.id = id;- return self();- }-- /**- * Sets the namespace of the table.- *- * @param namespace The namespace of the table.- * @return The builder instance.- */- @Override- public SELF withNameSpace(Namespace namespace) {- this.namespace = namespace;- return self();- }-/*** Sets the name of the table.*@@ -328,6 +192,12 @@ public class BaseTable implements Table, Entity, HasIdentifier {return self();}+ /**+ * Sets the partitioning strategies of the table.+ *+ * @param partitions The partitioning strategies of the table.+ * @return The builder instance.+ */@Overridepublic SELF withPartitions(Transform[] partitions) {this.partitions = partitions;@@ -352,7 +222,6 @@ public class BaseTable implements Table, Entity, HasIdentifier {@Overridepublic T build() {T t = internalBuild();- t.validate();return t;}@@ -362,17 +231,4 @@ public class BaseTable implements Table, Entity, HasIdentifier {protected abstract T internalBuild();}-- public static class TableBuilder extends BaseTableBuilder<TableBuilder, BaseTable> {- @Override- protected BaseTable internalBuild() {- BaseTable table = new BaseTable();- table.id = id;- table.name = name;- table.comment = comment;- table.properties = properties;- table.auditInfo = auditInfo;- return table;- }- }}diff --git a/core/src/main/java/com/datastrato/graviton/catalog/rel/EntityCombinedSchema.java b/core/src/main/java/com/datastrato/graviton/catalog/rel/EntityCombinedSchema.javanew file mode 100644index 0000000000..8d5ac10e50--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/catalog/rel/EntityCombinedSchema.java@@ -0,0 +1,64 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog.rel;++import com.datastrato.graviton.Audit;+import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.meta.SchemaEntity;+import com.datastrato.graviton.rel.Schema;+import java.util.Map;++/**+ * A Schema class to represent a schema metadata object that combines the metadata both from {@link+ * Schema} and {@link SchemaEntity}.+ */+public final class EntityCombinedSchema implements Schema {++ private final Schema schema;+ private final SchemaEntity schemaEntity;++ private EntityCombinedSchema(Schema schema, SchemaEntity schemaEntity) {+ this.schema = schema;+ this.schemaEntity = schemaEntity;+ }++ public static EntityCombinedSchema of(Schema schema, SchemaEntity schemaEntity) {+ return new EntityCombinedSchema(schema, schemaEntity);+ }++ public static EntityCombinedSchema of(Schema schema) {+ return of(schema, null);+ }++ @Override+ public String name() {+ return schema.name();+ }++ @Override+ public String comment() {+ return schema.comment();+ }++ @Override+ public Map<String, String> properties() {+ return schema.properties();+ }++ @Override+ public Audit auditInfo() {+ AuditInfo mergedAudit =+ new AuditInfo.Builder()+ .withCreator(schema.auditInfo().creator())+ .withCreateTime(schema.auditInfo().createTime())+ .withLastModifier(schema.auditInfo().lastModifier())+ .withLastModifiedTime(schema.auditInfo().lastModifiedTime())+ .build();++ return schemaEntity == null+ ? schema.auditInfo()+ : mergedAudit.merge(schemaEntity.auditInfo(), true /* overwrite */);+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/catalog/rel/EntityCombinedTable.java b/core/src/main/java/com/datastrato/graviton/catalog/rel/EntityCombinedTable.javanew file mode 100644index 0000000000..f188d7c1ab--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/catalog/rel/EntityCombinedTable.java@@ -0,0 +1,89 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog.rel;++import com.datastrato.graviton.Audit;+import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.meta.TableEntity;+import com.datastrato.graviton.rel.Column;+import com.datastrato.graviton.rel.Distribution;+import com.datastrato.graviton.rel.SortOrder;+import com.datastrato.graviton.rel.Table;+import com.datastrato.graviton.rel.transforms.Transform;+import java.util.Map;++/**+ * A Table class to represent a table metadata object that combines the metadata both from {@link+ * Table} and {@link TableEntity}.+ */+public final class EntityCombinedTable implements Table {++ private final Table table;++ private final TableEntity tableEntity;++ private EntityCombinedTable(Table table, TableEntity tableEntity) {+ this.table = table;+ this.tableEntity = tableEntity;+ }++ public static EntityCombinedTable of(Table table, TableEntity tableEntity) {+ return new EntityCombinedTable(table, tableEntity);+ }++ public static EntityCombinedTable of(Table table) {+ return of(table, null);+ }++ @Override+ public String name() {+ return table.name();+ }++ @Override+ public String comment() {+ return table.comment();+ }++ @Override+ public Column[] columns() {+ return table.columns();+ }++ @Override+ public Map<String, String> properties() {+ return table.properties();+ }++ @Override+ public Transform[] partitioning() {+ return table.partitioning();+ }++ @Override+ public SortOrder[] sortOrder() {+ return table.sortOrder();+ }++ @Override+ public Distribution distribution() {+ return table.distribution();+ }++ @Override+ public Audit auditInfo() {+ AuditInfo mergedAudit =+ new AuditInfo.Builder()+ .withCreator(table.auditInfo().creator())+ .withCreateTime(table.auditInfo().createTime())+ .withLastModifier(table.auditInfo().lastModifier())+ .withLastModifiedTime(table.auditInfo().lastModifiedTime())+ .build();++ return tableEntity == null+ ? table.auditInfo()+ : mergedAudit.merge(tableEntity.auditInfo(), true /* overwrite */);+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/meta/SchemaEntity.java b/core/src/main/java/com/datastrato/graviton/meta/SchemaEntity.javanew file mode 100644index 0000000000..332e595fa5--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/meta/SchemaEntity.java@@ -0,0 +1,183 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.meta;++import com.datastrato.graviton.Auditable;+import com.datastrato.graviton.Entity;+import com.datastrato.graviton.Field;+import com.datastrato.graviton.HasIdentifier;+import com.datastrato.graviton.Namespace;+import com.google.common.base.Objects;+import com.google.common.collect.Maps;+import java.util.Collections;+import java.util.Map;+import lombok.ToString;++/** A class representing a schema entity in Graviton. */+@ToString+public class SchemaEntity implements Entity, Auditable, HasIdentifier {++ public static final Field ID = Field.required("id", Long.class, "The schema's unique identifier");+ public static final Field NAME = Field.required("name", String.class, "The schema's name");+ public static final Field AUDIT_INFO =+ Field.required("audit_info", AuditInfo.class, "The audit details of the schema");++ private Long id;++ private String name;++ private AuditInfo auditInfo;++ protected Namespace namespace;++ /**+ * Returns an unmodifiable map of the fields and their corresponding values for this schema.+ *+ * @return An unmodifiable map of the fields and values.+ */+ @Override+ public Map<Field, Object> fields() {+ Map<Field, Object> fields = Maps.newHashMap();+ fields.put(ID, id);+ fields.put(NAME, name);+ fields.put(AUDIT_INFO, auditInfo);++ return Collections.unmodifiableMap(fields);+ }++ /**+ * Returns the name of the schema.+ *+ * @return The name of the schema.+ */+ @Override+ public String name() {+ return name;+ }++ /**+ * Returns the unique id of the schema.+ *+ * @return The unique id of the schema.+ */+ @Override+ public Long id() {+ return id;+ }++ /**+ * Returns the namespace of the schema.+ *+ * @return The namespace of the schema.+ */+ @Override+ public Namespace namespace() {+ return namespace;+ }++ /**+ * Returns the audit details of the schema.+ *+ * @return The audit details of the schema.+ */+ @Override+ public AuditInfo auditInfo() {+ return auditInfo;+ }++ /**+ * Returns the type of the entity, which is {@link EntityType#SCHEMA}.+ *+ * @return The type of the entity.+ */+ @Override+ public EntityType type() {+ return EntityType.SCHEMA;+ }++ // Ignore field namespace+ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (o == null || getClass() != o.getClass()) {+ return false;+ }+ SchemaEntity schema = (SchemaEntity) o;+ return Objects.equal(id, schema.id)+ && Objects.equal(name, schema.name)+ && Objects.equal(auditInfo, schema.auditInfo);+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(id, name, auditInfo);+ }++ /** A builder class for {@link SchemaEntity}. */+ public static class Builder {++ private final SchemaEntity schema;++ public Builder() {+ this.schema = new SchemaEntity();+ }++ /**+ * Sets the unique identifier of the schema.+ *+ * @param id The unique identifier of the schema.+ * @return The builder instance.+ */+ public Builder withId(Long id) {+ schema.id = id;+ return this;+ }++ /**+ * Sets the name of the schema.+ *+ * @param name The name of the schema.+ * @return The builder instance.+ */+ public Builder withName(String name) {+ schema.name = name;+ return this;+ }++ /**+ * Sets the namespace of the schema.+ *+ * @param namespace The namespace of the schema.+ * @return The builder instance.+ */+ public Builder withNamespace(Namespace namespace) {+ schema.namespace = namespace;+ return this;+ }++ /**+ * Sets the audit details of the schema.+ *+ * @param auditInfo The audit details of the schema.+ * @return The builder instance.+ */+ public Builder withAuditInfo(AuditInfo auditInfo) {+ schema.auditInfo = auditInfo;+ return this;+ }++ /**+ * Builds the instance of the schema with the provided attributes.+ *+ * @return The built schema instance.+ */+ public SchemaEntity build() {+ schema.validate();+ return schema;+ }+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/meta/TableEntity.java b/core/src/main/java/com/datastrato/graviton/meta/TableEntity.javanew file mode 100644index 0000000000..be17a756ee--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/meta/TableEntity.java@@ -0,0 +1,153 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.meta;++import com.datastrato.graviton.Auditable;+import com.datastrato.graviton.Entity;+import com.datastrato.graviton.Field;+import com.datastrato.graviton.HasIdentifier;+import com.datastrato.graviton.Namespace;+import com.google.common.base.Objects;+import com.google.common.collect.Maps;+import java.util.Map;+import lombok.ToString;++/** A class representing a table entity in Graviton. */+@ToString+public class TableEntity implements Entity, Auditable, HasIdentifier {++ public static final Field ID = Field.required("id", Long.class, "The table's unique identifier");+ public static final Field NAME = Field.required("name", String.class, "The table's name");+ public static final Field AUDIT_INFO =+ Field.required("audit_info", AuditInfo.class, "The audit details of the table");++ private Long id;++ private String name;++ private AuditInfo auditInfo;++ private Namespace namespace;++ /**+ * Returns a map of the fields and their corresponding values for this table.+ *+ * @return A map of the fields and values.+ */+ @Override+ public Map<Field, Object> fields() {+ Map<Field, Object> fields = Maps.newHashMap();+ fields.put(ID, id);+ fields.put(NAME, name);+ fields.put(AUDIT_INFO, auditInfo);++ return fields;+ }++ /**+ * Returns the type of the entity.+ *+ * @return The type of the entity.+ */+ @Override+ public EntityType type() {+ return EntityType.TABLE;+ }++ /**+ * Returns the audit details of the table.+ *+ * @return The audit details of the table.+ */+ @Override+ public AuditInfo auditInfo() {+ return auditInfo;+ }++ /**+ * Returns the name of the table.+ *+ * @return The name of the table.+ */+ @Override+ public String name() {+ return name;+ }++ /**+ * Returns the unique id of the table.+ *+ * @return The unique id of the table.+ */+ @Override+ public Long id() {+ return id;+ }++ /**+ * Returns the namespace of the table.+ *+ * @return The namespace of the table.+ */+ @Override+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (o == null || getClass() != o.getClass()) {+ return false;+ }++ // Ignore field namespace+ TableEntity baseTable = (TableEntity) o;+ return Objects.equal(id, baseTable.id)+ && Objects.equal(name, baseTable.name)+ && Objects.equal(auditInfo, baseTable.auditInfo);+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(id, name, auditInfo);+ }++ public static class Builder {++ private final TableEntity tableEntity;++ public Builder() {+ this.tableEntity = new TableEntity();+ }++ public Builder withId(Long id) {+ tableEntity.id = id;+ return this;+ }++ public Builder withName(String name) {+ tableEntity.name = name;+ return this;+ }++ public Builder withAuditInfo(AuditInfo auditInfo) {+ tableEntity.auditInfo = auditInfo;+ return this;+ }++ public Builder withNamespace(Namespace namespace) {+ tableEntity.namespace = namespace;+ return this;+ }++ public TableEntity build() {+ tableEntity.validate();+ return tableEntity;+ }+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.javadeleted file mode 100644index 507714750c..0000000000--- a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java+++ /dev/null@@ -1,297 +0,0 @@-/*- * 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.HasIdentifier;-import com.datastrato.graviton.Namespace;-import com.datastrato.graviton.meta.AuditInfo;-import com.datastrato.graviton.rel.Schema;-import com.google.common.base.Objects;-import com.google.common.collect.Maps;-import java.util.Collections;-import java.util.Map;-import javax.annotation.Nullable;-import lombok.ToString;--/** An abstract class representing a base schema in a relational database. */-@ToString-public class BaseSchema implements Schema, Entity, HasIdentifier {-- public static final Field ID = Field.required("id", Long.class, "The schema's unique identifier");- public static final Field NAME = Field.required("name", String.class, "The schema's name");- public static final Field COMMENT =- Field.optional("comment", String.class, "The comment or description for the schema");- public static final Field PROPERTIES =- Field.optional("properties", Map.class, "The associated properties of the schema");- public static final Field AUDIT_INFO =- Field.required("audit_info", AuditInfo.class, "The audit details of the schema");-- protected Long id;-- protected String name;-- @Nullable protected String comment;-- @Nullable protected Map<String, String> properties;-- protected AuditInfo auditInfo;-- protected Namespace namespace;-- /**- * Returns an unmodifiable map of the fields and their corresponding values for this schema.- *- * @return An unmodifiable map of the fields and values.- */- @Override- public Map<Field, Object> fields() {- Map<Field, Object> fields = Maps.newHashMap();- fields.put(ID, id);- fields.put(NAME, name);- fields.put(COMMENT, comment);- fields.put(PROPERTIES, properties);- fields.put(AUDIT_INFO, auditInfo);-- return Collections.unmodifiableMap(fields);- }-- /**- * Returns the name of the schema.- *- * @return The name of the schema.- */- @Override- public String name() {- return name;- }-- /**- * Returns the unique id of the schema.- *- * @return The unique id of the schema.- */- @Override- public Long id() {- return id;- }-- /**- * Returns the namespace of the schema.- *- * @return The namespace of the schema.- */- @Override- public Namespace namespace() {- return namespace;- }-- /**- * Returns the comment or description for the schema.- *- * @return The comment or description for the schema.- */- @Override- public String comment() {- return comment;- }-- /**- * Returns the associated properties of the schema.- *- * @return The associated properties of the schema.- */- @Override- public Map<String, String> properties() {- return properties;- }-- /**- * Returns the audit details of the schema.- *- * @return The audit details of the schema.- */- @Override- public AuditInfo auditInfo() {- return auditInfo;- }-- /**- * Returns the type of the entity, which is {@link EntityType#SCHEMA}.- *- * @return The type of the entity.- */- @Override- public EntityType type() {- return EntityType.SCHEMA;- }-- // Ignore field namespace and comment- @Override- public boolean equals(Object o) {- if (this == o) {- return true;- }- if (o == null || getClass() != o.getClass()) {- return false;- }- BaseSchema schema = (BaseSchema) o;- return Objects.equal(id, schema.id)- && Objects.equal(name, schema.name)- && Objects.equal(properties, schema.properties)- && Objects.equal(auditInfo, schema.auditInfo);- }-- @Override- public int hashCode() {- return Objects.hashCode(id, name, properties, auditInfo);- }-- /**- * Builder interface for creating instances of {@link BaseSchema}.- *- * @param <SELF> The type of the builder.- * @param <T> The type of the schema being built.- */- interface Builder<SELF extends Builder<SELF, T>, T extends BaseSchema> {- SELF withId(Long id);-- SELF withName(String name);-- SELF withNamespace(Namespace namespace);-- SELF withComment(String comment);-- SELF withProperties(Map<String, String> properties);-- SELF withAuditInfo(AuditInfo auditInfo);-- T build();- }-- /**- * An abstract class implementing the builder interface for {@link BaseSchema}.- *- * @param <SELF> The type of the builder.- * @param <T> The type of the schema being built.- */- public abstract static class BaseSchemaBuilder<- SELF extends Builder<SELF, T>, T extends BaseSchema>- implements Builder<SELF, T> {- protected Long id;- protected String name;- protected Namespace namespace;- protected String comment;- protected Map<String, String> properties;- protected AuditInfo auditInfo;-- /**- * Sets the unique identifier of the schema.- *- * @param id The unique identifier of the schema.- * @return The builder instance.- */- @Override- public SELF withId(Long id) {- this.id = id;- return self();- }-- /**- * Sets the name of the schema.- *- * @param name The name of the schema.- * @return The builder instance.- */- @Override- public SELF withName(String name) {- this.name = name;- return self();- }-- /**- * Sets the namespace of the schema.- *- * @param namespace The namespace of the schema.- * @return The builder instance.- */- @Override- public SELF withNamespace(Namespace namespace) {- this.namespace = namespace;- return self();- }-- /**- * Sets the comment of the schema.- *- * @param comment The comment or description for the schema.- * @return The builder instance.- */- @Override- public SELF withComment(String comment) {- this.comment = comment;- return self();- }-- /**- * Sets the associated properties of the schema.- *- * @param properties The associated properties of the schema.- * @return The builder instance.- */- @Override- public SELF withProperties(Map<String, String> properties) {- this.properties = properties;- return self();- }-- /**- * Sets the audit details of the schema.- *- * @param auditInfo The audit details of the schema.- * @return The builder instance.- */- @Override- public SELF withAuditInfo(AuditInfo auditInfo) {- this.auditInfo = auditInfo;- return self();- }-- /**- * Builds the instance of the schema with the provided attributes.- *- * @return The built schema instance.- */- @Override- public T build() {- T t = internalBuild();- t.validate();- return t;- }-- private SELF self() {- return (SELF) this;- }-- protected abstract T internalBuild();- }-- public static class SchemaBuilder extends BaseSchemaBuilder<SchemaBuilder, BaseSchema> {-- @Override- protected BaseSchema internalBuild() {- BaseSchema baseSchema = new BaseSchema();- baseSchema.id = id;- baseSchema.name = name;- baseSchema.comment = comment;- baseSchema.properties = properties;- baseSchema.auditInfo = auditInfo;-- return baseSchema;- }- }-}diff --git a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.javaindex 4e389782cd..b075cb63a9 100644--- a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java+++ b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java@@ -29,16 +29,10 @@ public class ProtoEntitySerDe implements EntitySerDe {"com.datastrato.graviton.meta.CatalogEntity","com.datastrato.graviton.proto.CatalogEntitySerDe").put(- "com.datastrato.graviton.meta.rel.BaseSchema",+ "com.datastrato.graviton.meta.SchemaEntity","com.datastrato.graviton.proto.SchemaEntitySerDe").put(- "com.datastrato.graviton.catalog.hive.HiveSchema",- "com.datastrato.graviton.proto.SchemaEntitySerDe")- .put(- "com.datastrato.graviton.meta.rel.BaseTable",- "com.datastrato.graviton.proto.TableEntitySerde")- .put(- "com.datastrato.graviton.catalog.hive.HiveTable",+ "com.datastrato.graviton.meta.TableEntity","com.datastrato.graviton.proto.TableEntitySerde").build();@@ -50,9 +44,9 @@ public class ProtoEntitySerDe implements EntitySerDe {"com.datastrato.graviton.proto.Metalake","com.datastrato.graviton.meta.CatalogEntity","com.datastrato.graviton.proto.Catalog",- "com.datastrato.graviton.meta.rel.BaseSchema",+ "com.datastrato.graviton.meta.SchemaEntity","com.datastrato.graviton.proto.Schema",- "com.datastrato.graviton.meta.rel.BaseTable",+ "com.datastrato.graviton.meta.TableEntity","com.datastrato.graviton.proto.Table");private final Map<Class<? extends Entity>, ProtoSerDe<? extends Entity, ? extends Message>>diff --git a/core/src/main/java/com/datastrato/graviton/proto/SchemaEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/SchemaEntitySerDe.javaindex 9b0aadcf0f..0809d768cc 100644--- a/core/src/main/java/com/datastrato/graviton/proto/SchemaEntitySerDe.java+++ b/core/src/main/java/com/datastrato/graviton/proto/SchemaEntitySerDe.java@@ -4,11 +4,11 @@*/package com.datastrato.graviton.proto;-import com.datastrato.graviton.meta.rel.BaseSchema;+import com.datastrato.graviton.meta.SchemaEntity;-public class SchemaEntitySerDe implements ProtoSerDe<BaseSchema, Schema> {+public class SchemaEntitySerDe implements ProtoSerDe<SchemaEntity, Schema> {@Override- public Schema serialize(BaseSchema schemaEntity) {+ public Schema serialize(SchemaEntity schemaEntity) {return Schema.newBuilder().setId(schemaEntity.id()).setName(schemaEntity.name())@@ -17,8 +17,8 @@ public class SchemaEntitySerDe implements ProtoSerDe<BaseSchema, Schema> {}@Override- public BaseSchema deserialize(Schema p) {- return new BaseSchema.SchemaBuilder()+ public SchemaEntity deserialize(Schema p) {+ return new SchemaEntity.Builder().withId(p.getId()).withName(p.getName()).withAuditInfo(new AuditInfoSerDe().deserialize(p.getAuditInfo()))diff --git a/core/src/main/java/com/datastrato/graviton/proto/TableEntitySerde.java b/core/src/main/java/com/datastrato/graviton/proto/TableEntitySerde.javaindex 5c34e12d3c..7d11057834 100644--- a/core/src/main/java/com/datastrato/graviton/proto/TableEntitySerde.java+++ b/core/src/main/java/com/datastrato/graviton/proto/TableEntitySerde.java@@ -4,11 +4,11 @@*/package com.datastrato.graviton.proto;-import com.datastrato.graviton.meta.rel.BaseTable;+import com.datastrato.graviton.meta.TableEntity;-public class TableEntitySerde implements ProtoSerDe<BaseTable, Table> {+public class TableEntitySerde implements ProtoSerDe<TableEntity, Table> {@Override- public Table serialize(BaseTable tableEntity) {+ public Table serialize(TableEntity tableEntity) {return Table.newBuilder().setId(tableEntity.id()).setName(tableEntity.name())@@ -17,8 +17,8 @@ public class TableEntitySerde implements ProtoSerDe<BaseTable, Table> {}@Override- public BaseTable deserialize(Table p) {- return new BaseTable.TableBuilder()+ public TableEntity deserialize(Table p) {+ return new TableEntity.Builder().withId(p.getId()).withName(p.getName()).withAuditInfo(new AuditInfoSerDe().deserialize(p.getAuditInfo()))diff --git a/core/src/test/java/com/datastrato/graviton/TestCatalog.java b/core/src/test/java/com/datastrato/graviton/TestCatalog.javaindex 2c5b10f686..d84172d04b 100644--- a/core/src/test/java/com/datastrato/graviton/TestCatalog.java+++ b/core/src/test/java/com/datastrato/graviton/TestCatalog.java@@ -19,7 +19,7 @@ public class TestCatalog extends BaseCatalog<TestCatalog> {}@Override- protected CatalogOperations newOps(Map config) {+ protected CatalogOperations newOps(Map<String, String> config) {return new TestCatalogOperations();}diff --git a/core/src/test/java/com/datastrato/graviton/TestCatalogOperations.java b/core/src/test/java/com/datastrato/graviton/TestCatalogOperations.javaindex 77b2a66470..de5be13b94 100644--- a/core/src/test/java/com/datastrato/graviton/TestCatalogOperations.java+++ b/core/src/test/java/com/datastrato/graviton/TestCatalogOperations.java@@ -5,13 +5,19 @@package com.datastrato.graviton;import com.datastrato.graviton.catalog.CatalogOperations;+import com.datastrato.graviton.exceptions.NoSuchCatalogException;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.rel.Column;import com.datastrato.graviton.rel.Distribution;+import com.datastrato.graviton.rel.Schema;+import com.datastrato.graviton.rel.SchemaChange;import com.datastrato.graviton.rel.SortOrder;+import com.datastrato.graviton.rel.SupportsSchemas;import com.datastrato.graviton.rel.Table;import com.datastrato.graviton.rel.TableCatalog;import com.datastrato.graviton.rel.TableChange;@@ -21,12 +27,15 @@ import java.io.IOException;import java.time.Instant;import java.util.Map;-public class TestCatalogOperations implements CatalogOperations, TableCatalog {+public class TestCatalogOperations implements CatalogOperations, TableCatalog, SupportsSchemas {private final Map<NameIdentifier, TestTable> tables;+ private final Map<NameIdentifier, TestSchema> schemas;+public TestCatalogOperations() {tables = Maps.newHashMap();+ schemas = Maps.newHashMap();}@Override@@ -66,15 +75,14 @@ public class TestCatalogOperations implements CatalogOperations, TableCatalog {TestTable table =new TestTable.Builder()- .withId(1L).withName(ident.name())- .withNameSpace(ident.namespace()).withComment(comment).withProperties(properties).withAuditInfo(auditInfo).withColumns(columns).withDistribution(distribution).withSortOrders(sortOrders)+ .withPartitions(partitions).build();if (tables.containsKey(ident)) {@@ -89,7 +97,46 @@ public class TestCatalogOperations implements CatalogOperations, TableCatalog {@Overridepublic Table alterTable(NameIdentifier ident, TableChange... changes)throws NoSuchTableException, IllegalArgumentException {- throw new UnsupportedOperationException("unsupported");+ if (!tables.containsKey(ident)) {+ throw new NoSuchTableException("Table " + ident + " does not exist");+ }++ AuditInfo updatedAuditInfo =+ new AuditInfo.Builder()+ .withCreator("test")+ .withCreateTime(Instant.now())+ .withLastModifier("test")+ .withLastModifiedTime(Instant.now())+ .build();++ TestTable table = tables.get(ident);+ Map<String, String> newProps =+ table.properties() != null ? Maps.newHashMap(table.properties()) : Maps.newHashMap();++ for (TableChange change : changes) {+ if (change instanceof TableChange.SetProperty) {+ newProps.put(+ ((TableChange.SetProperty) change).getProperty(),+ ((TableChange.SetProperty) change).getValue());+ } else if (change instanceof TableChange.RemoveProperty) {+ newProps.remove(((TableChange.RemoveProperty) change).getProperty());+ } else {+ throw new IllegalArgumentException("Unsupported table change: " + change);+ }+ }++ TestTable updatedTable =+ new TestTable.Builder()+ .withName(ident.name())+ .withComment(table.comment())+ .withProperties(newProps)+ .withAuditInfo(updatedAuditInfo)+ .withColumns(table.columns())+ .withPartitions(table.partitioning())+ .build();++ tables.put(ident, updatedTable);+ return updatedTable;}@Override@@ -101,4 +148,102 @@ public class TestCatalogOperations implements CatalogOperations, TableCatalog {return false;}}++ @Override+ public NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {+ return schemas.keySet().stream()+ .filter(ident -> ident.namespace().equals(namespace))+ .toArray(NameIdentifier[]::new);+ }++ @Override+ public Schema createSchema(NameIdentifier ident, String comment, Map<String, String> metadata)+ throws NoSuchCatalogException, SchemaAlreadyExistsException {+ AuditInfo auditInfo =+ new AuditInfo.Builder().withCreator("test").withCreateTime(Instant.now()).build();++ TestSchema schema =+ new TestSchema.Builder()+ .withName(ident.name())+ .withComment(comment)+ .withProperties(metadata)+ .withAuditInfo(auditInfo)+ .build();++ if (schemas.containsKey(ident)) {+ throw new SchemaAlreadyExistsException("Schema " + ident + " already exists");+ } else {+ schemas.put(ident, schema);+ }++ return schema;+ }++ @Override+ public Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {+ if (schemas.containsKey(ident)) {+ return schemas.get(ident);+ } else {+ throw new NoSuchSchemaException("Schema " + ident + " does not exist");+ }+ }++ @Override+ public Schema alterSchema(NameIdentifier ident, SchemaChange... changes)+ throws NoSuchSchemaException {+ if (!schemas.containsKey(ident)) {+ throw new NoSuchSchemaException("Schema " + ident + " does not exist");+ }++ AuditInfo updatedAuditInfo =+ new AuditInfo.Builder()+ .withCreator("test")+ .withCreateTime(Instant.now())+ .withLastModifier("test")+ .withLastModifiedTime(Instant.now())+ .build();++ TestSchema schema = schemas.get(ident);+ Map<String, String> newProps =+ schema.properties() != null ? Maps.newHashMap(schema.properties()) : Maps.newHashMap();++ for (SchemaChange change : changes) {+ if (change instanceof SchemaChange.SetProperty) {+ newProps.put(+ ((SchemaChange.SetProperty) change).getProperty(),+ ((SchemaChange.SetProperty) change).getValue());+ } else if (change instanceof SchemaChange.RemoveProperty) {+ newProps.remove(((SchemaChange.RemoveProperty) change).getProperty());+ } else {+ throw new IllegalArgumentException("Unsupported schema change: " + change);+ }+ }++ TestSchema updatedSchema =+ new TestSchema.Builder()+ .withName(ident.name())+ .withComment(schema.comment())+ .withProperties(newProps)+ .withAuditInfo(updatedAuditInfo)+ .build();++ schemas.put(ident, updatedSchema);+ return updatedSchema;+ }++ @Override+ public boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {+ if (!schemas.containsKey(ident)) {+ return false;+ }++ schemas.remove(ident);+ if (cascade) {+ tables.keySet().stream()+ .filter(table -> table.namespace().toString().equals(ident.toString()))+ .forEach(table -> tables.remove(table));+ }++ return true;+ }}diff --git a/core/src/test/java/com/datastrato/graviton/TestColumn.java b/core/src/test/java/com/datastrato/graviton/TestColumn.javaindex 5a02d73dba..e6d0b7610c 100644--- a/core/src/test/java/com/datastrato/graviton/TestColumn.java+++ b/core/src/test/java/com/datastrato/graviton/TestColumn.java@@ -4,7 +4,7 @@*/package com.datastrato.graviton;-import com.datastrato.graviton.meta.rel.BaseColumn;+import com.datastrato.graviton.catalog.rel.BaseColumn;import lombok.EqualsAndHashCode;import lombok.ToString;diff --git a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java b/core/src/test/java/com/datastrato/graviton/TestEntityStore.javaindex 23cc832399..f8c0a7600e 100644--- a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java+++ b/core/src/test/java/com/datastrato/graviton/TestEntityStore.java@@ -9,19 +9,11 @@ import com.datastrato.graviton.exceptions.NoSuchEntityException;import com.datastrato.graviton.meta.AuditInfo;import com.datastrato.graviton.meta.BaseMetalake;import com.datastrato.graviton.meta.CatalogEntity;+import com.datastrato.graviton.meta.SchemaEntity;import com.datastrato.graviton.meta.SchemaVersion;-import com.datastrato.graviton.rel.Column;-import com.datastrato.graviton.rel.Distribution;-import com.datastrato.graviton.rel.Distribution.Strategy;-import com.datastrato.graviton.rel.SortOrder;-import com.datastrato.graviton.rel.SortOrder.Direction;-import com.datastrato.graviton.rel.SortOrder.NullOrdering;-import com.datastrato.graviton.rel.Table;-import com.datastrato.graviton.rel.transforms.Transform;-import com.datastrato.graviton.rel.transforms.Transforms;+import com.datastrato.graviton.meta.TableEntity;import com.datastrato.graviton.utils.Executable;import com.google.common.collect.Maps;-import io.substrait.type.TypeCreator;import java.io.IOException;import java.time.Instant;import java.util.List;@@ -167,40 +159,20 @@ public class TestEntityStore {.withAuditInfo(auditInfo).build();- TestColumn column =- new TestColumn.Builder()- .withName("column")- .withComment("comment")- .withType(TypeCreator.NULLABLE.I8)- .build();-- Distribution distribution =- Distribution.builder()- .withNumber(10)- .withTransforms(new Transform[] {Transforms.field(new String[] {"column"})})- .withStrategy(Strategy.EVEN)+ SchemaEntity schemaEntity =+ new SchemaEntity.Builder()+ .withId(1L)+ .withName("schema")+ .withNamespace(Namespace.of("metalake", "catalog"))+ .withAuditInfo(auditInfo).build();- SortOrder[] sortOrders =- new SortOrder[] {- SortOrder.builder()- .withNullOrdering(NullOrdering.FIRST)- .withDirection(Direction.DESC)- .withTransform(Transforms.field(new String[] {"column"}))- .build()- };-- TestTable table =- new TestTable.Builder()+ TableEntity tableEntity =+ new TableEntity.Builder().withId(1L).withName("table")- .withNameSpace(Namespace.of("metalake", "catalog", "db"))- .withComment("comment")- .withProperties(Maps.newHashMap())- .withColumns(new Column[] {column})+ .withNamespace(Namespace.of("metalake", "catalog", "db")).withAuditInfo(auditInfo)- .withDistribution(distribution)- .withSortOrders(sortOrders).build();InMemoryEntityStore store = new InMemoryEntityStore();@@ -209,7 +181,8 @@ public class TestEntityStore {store.put(metalake);store.put(catalog);- store.put(table);+ store.put(schemaEntity);+ store.put(tableEntity);Metalake retrievedMetalake =store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);@@ -219,8 +192,13 @@ public class TestEntityStore {store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);Assertions.assertEquals(catalog, retrievedCatalog);- Table retrievedTable = store.get(table.nameIdentifier(), EntityType.TABLE, TestTable.class);- Assertions.assertEquals(table, retrievedTable);+ SchemaEntity retrievedSchema =+ store.get(schemaEntity.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class);+ Assertions.assertEquals(schemaEntity, retrievedSchema);++ TableEntity retrievedTable =+ store.get(tableEntity.nameIdentifier(), EntityType.TABLE, TableEntity.class);+ Assertions.assertEquals(tableEntity, retrievedTable);store.delete(metalake.nameIdentifier(), EntityType.METALAKE);Assertions.assertThrows(diff --git a/core/src/test/java/com/datastrato/graviton/TestSchema.java b/core/src/test/java/com/datastrato/graviton/TestSchema.javanew file mode 100644index 0000000000..84094d5aa5--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/TestSchema.java@@ -0,0 +1,29 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton;++import com.datastrato.graviton.catalog.rel.BaseSchema;+import lombok.EqualsAndHashCode;++@EqualsAndHashCode(callSuper = true)+public class TestSchema extends BaseSchema {++ private TestSchema() {}++ public static class Builder extends BaseSchema.BaseSchemaBuilder<Builder, TestSchema> {++ @Override+ protected TestSchema internalBuild() {+ TestSchema schema = new TestSchema();++ schema.name = name;+ schema.comment = comment;+ schema.properties = properties;+ schema.auditInfo = auditInfo;++ return schema;+ }+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/TestTable.java b/core/src/test/java/com/datastrato/graviton/TestTable.javaindex 12eb539b43..dbe79d92d1 100644--- a/core/src/test/java/com/datastrato/graviton/TestTable.java+++ b/core/src/test/java/com/datastrato/graviton/TestTable.java@@ -4,40 +4,19 @@*/package com.datastrato.graviton;-import com.datastrato.graviton.meta.rel.BaseTable;-import com.datastrato.graviton.rel.Distribution;-import com.datastrato.graviton.rel.SortOrder;+import com.datastrato.graviton.catalog.rel.BaseTable;import lombok.EqualsAndHashCode;@EqualsAndHashCode(callSuper = true)public class TestTable extends BaseTable {- protected Distribution distribution;-- protected SortOrder[] sortOrders;-public static class Builder extends BaseTable.BaseTableBuilder<Builder, TestTable> {- private Distribution distribution;-- private SortOrder[] sortOrders;-- public Builder withDistribution(Distribution distribution) {- this.distribution = distribution;- return this;- }-- public Builder withSortOrders(SortOrder[] sortOrders) {- this.sortOrders = sortOrders;- return this;- }@Overrideprotected TestTable internalBuild() {TestTable table = new TestTable();- table.id = id;table.name = name;table.comment = comment;- table.namespace = namespace;table.properties = properties;table.columns = columns;table.auditInfo = auditInfo;diff --git a/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogOperationDispatcher.java b/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogOperationDispatcher.javaindex fb7213ee2b..2db57575b7 100644--- a/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogOperationDispatcher.java+++ b/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogOperationDispatcher.java@@ -4,17 +4,485 @@*/package com.datastrato.graviton.catalog;+import static com.datastrato.graviton.Entity.EntityType.SCHEMA;+import static com.datastrato.graviton.Entity.EntityType.TABLE;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyBoolean;+import static org.mockito.Mockito.doReturn;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.reset;+import static org.mockito.Mockito.spy;+import com.datastrato.graviton.Catalog;+import com.datastrato.graviton.Config;+import com.datastrato.graviton.Configs;+import com.datastrato.graviton.EntityStore;import com.datastrato.graviton.NameIdentifier;+import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.StringIdentifier;+import com.datastrato.graviton.TestColumn;+import com.datastrato.graviton.TestEntityStore;import com.datastrato.graviton.exceptions.IllegalNamespaceException;+import com.datastrato.graviton.exceptions.NoSuchEntityException;+import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.meta.BaseMetalake;+import com.datastrato.graviton.meta.SchemaEntity;+import com.datastrato.graviton.meta.SchemaVersion;+import com.datastrato.graviton.meta.TableEntity;+import com.datastrato.graviton.rel.Column;+import com.datastrato.graviton.rel.Schema;+import com.datastrato.graviton.rel.SchemaChange;+import com.datastrato.graviton.rel.Table;+import com.datastrato.graviton.rel.TableChange;+import com.datastrato.graviton.rel.transforms.Transform;+import com.datastrato.graviton.storage.IdGenerator;+import com.datastrato.graviton.storage.RandomIdGenerator;+import com.google.common.collect.ImmutableMap;+import io.substrait.type.TypeCreator;+import java.io.IOException;+import java.time.Instant;+import java.util.Arrays;+import java.util.Map;+import java.util.Optional;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;public class TestCatalogOperationDispatcher {++ private static EntityStore entityStore;++ private static final IdGenerator idGenerator = new RandomIdGenerator();++ private static final String metalake = "metalake";++ private static final String catalog = "catalog";++ private static CatalogManager catalogManager;++ private static Config config;++ private static CatalogOperationDispatcher dispatcher;++ @BeforeAll+ public static void setUp() throws IOException {+ config = new Config(false) {};+ config.set(Configs.CATALOG_LOAD_ISOLATED, false);++ entityStore = spy(new TestEntityStore.InMemoryEntityStore());+ entityStore.initialize(config);+ entityStore.setSerDe(null);++ BaseMetalake metalakeEntity =+ new BaseMetalake.Builder()+ .withId(1L)+ .withName(metalake)+ .withAuditInfo(+ new AuditInfo.Builder().withCreator("test").withCreateTime(Instant.now()).build())+ .withVersion(SchemaVersion.V_0_1)+ .build();+ entityStore.put(metalakeEntity, true);++ catalogManager = new CatalogManager(config, entityStore, idGenerator);+ dispatcher = new CatalogOperationDispatcher(catalogManager, entityStore, idGenerator);++ NameIdentifier ident = NameIdentifier.of(metalake, catalog);+ Map<String, String> props = ImmutableMap.of("provider", "test");+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "comment", props);+ }++ @AfterAll+ public static void tearDown() throws IOException {+ if (entityStore != null) {+ entityStore.close();+ entityStore = null;+ }++ if (catalogManager != null) {+ catalogManager.close();+ catalogManager = null;+ }+ }++ @BeforeEach+ public void beforeStart() throws IOException {+ reset(entityStore);+ }++ @Test+ public void testCreateAndListSchemas() throws IOException {+ Namespace ns = Namespace.of(metalake, catalog);++ NameIdentifier schemaIdent = NameIdentifier.of(ns, "schema1");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ Schema schema = dispatcher.createSchema(schemaIdent, "comment", props);++ // Check if the created Schema's field values are correct+ Assertions.assertEquals("schema1", schema.name());+ Assertions.assertEquals("comment", schema.comment());+ testProperties(props, schema.properties());++ // Check if the Schema entity is stored in the EntityStore+ SchemaEntity schemaEntity = entityStore.get(schemaIdent, SCHEMA, SchemaEntity.class);+ Assertions.assertNotNull(schemaEntity);+ Assertions.assertEquals("schema1", schemaEntity.name());++ StringIdentifier stringId = StringIdentifier.fromProperties(schema.properties());+ Assertions.assertEquals(stringId.id(), schemaEntity.id());++ Optional<NameIdentifier> ident1 =+ Arrays.stream(dispatcher.listSchemas(ns))+ .filter(s -> s.name().equals("schema1"))+ .findFirst();+ Assertions.assertTrue(ident1.isPresent());++ // Test when the entity store failed to put the schema entity+ doThrow(new IOException()).when(entityStore).put(any(), anyBoolean());+ NameIdentifier schemaIdent2 = NameIdentifier.of(ns, "schema2");+ Schema schema2 = dispatcher.createSchema(schemaIdent2, "comment", props);++ // Check if the created Schema's field values are correct+ Assertions.assertEquals("schema2", schema2.name());+ Assertions.assertEquals("comment", schema2.comment());+ testProperties(props, schema2.properties());++ // Check if the Schema entity is stored in the EntityStore+ Assertions.assertFalse(entityStore.exists(schemaIdent2, SCHEMA));+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> entityStore.get(schemaIdent2, SCHEMA, SchemaEntity.class));++ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", schema2.auditInfo().creator());+ }++ @Test+ public void testCreateAndLoadSchema() throws IOException {+ NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, "schema11");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ Schema schema = dispatcher.createSchema(schemaIdent, "comment", props);++ Schema loadedSchema = dispatcher.loadSchema(schemaIdent);+ Assertions.assertEquals(schema.name(), loadedSchema.name());+ Assertions.assertEquals(schema.comment(), loadedSchema.comment());+ testProperties(schema.properties(), loadedSchema.properties());+ // Audit info is gotten from entity store+ Assertions.assertEquals("graviton", loadedSchema.auditInfo().creator());++ // Case 2: Test if the schema is not found in entity store+ doThrow(new NoSuchEntityException("mock error")).when(entityStore).get(any(), any(), any());+ Schema loadedSchema1 = dispatcher.loadSchema(schemaIdent);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", loadedSchema1.auditInfo().creator());++ // Case 3: Test if entity store is failed to get the schema entity+ reset(entityStore);+ doThrow(new IOException()).when(entityStore).get(any(), any(), any());+ Schema loadedSchema2 = dispatcher.loadSchema(schemaIdent);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", loadedSchema2.auditInfo().creator());++ // Case 4: Test if the fetched schema entity is matched.+ reset(entityStore);+ SchemaEntity unmatchedEntity =+ new SchemaEntity.Builder()+ .withId(1L)+ .withName("schema11")+ .withNamespace(Namespace.of(metalake, catalog))+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton")+ .withCreateTime(Instant.now())+ .build())+ .build();+ doReturn(unmatchedEntity).when(entityStore).get(any(), any(), any());+ Schema loadedSchema3 = dispatcher.loadSchema(schemaIdent);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", loadedSchema2.auditInfo().creator());+ }++ @Test+ public void testCreateAndAlterSchema() throws IOException {+ NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, "schema21");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ Schema schema = dispatcher.createSchema(schemaIdent, "comment", props);++ SchemaChange[] changes =+ new SchemaChange[] {+ SchemaChange.setProperty("k3", "v3"), SchemaChange.removeProperty("k1")+ };++ Schema alteredSchema = dispatcher.alterSchema(schemaIdent, changes);+ Assertions.assertEquals(schema.name(), alteredSchema.name());+ Assertions.assertEquals(schema.comment(), alteredSchema.comment());+ Map<String, String> expectedProps = ImmutableMap.of("k2", "v2", "k3", "v3");+ testProperties(expectedProps, alteredSchema.properties());+ // Audit info is gotten from graviton entity store.+ Assertions.assertEquals("graviton", alteredSchema.auditInfo().creator());+ Assertions.assertEquals("graviton", alteredSchema.auditInfo().lastModifier());++ // Case 2: Test if the schema is not found in entity store+ doThrow(new NoSuchEntityException("mock error"))+ .when(entityStore)+ .update(any(), any(), any(), any());+ Schema alteredSchema1 = dispatcher.alterSchema(schemaIdent, changes);+ Assertions.assertEquals(schema.name(), alteredSchema1.name());+ Assertions.assertEquals(schema.comment(), alteredSchema1.comment());+ testProperties(expectedProps, alteredSchema1.properties());+ // Audit info is gotten from catalog, not from the entity store+ Assertions.assertEquals("test", alteredSchema1.auditInfo().creator());+ Assertions.assertEquals("test", alteredSchema1.auditInfo().lastModifier());++ // Case 3: Test if entity store is failed to get the schema entity+ reset(entityStore);+ doThrow(new IOException()).when(entityStore).update(any(), any(), any(), any());+ Schema alteredSchema2 = dispatcher.alterSchema(schemaIdent, changes);+ Assertions.assertEquals(schema.name(), alteredSchema2.name());+ Assertions.assertEquals(schema.comment(), alteredSchema2.comment());+ testProperties(expectedProps, alteredSchema2.properties());+ // Audit info is gotten from catalog, not from the entity store+ Assertions.assertEquals("test", alteredSchema2.auditInfo().creator());+ Assertions.assertEquals("test", alteredSchema1.auditInfo().lastModifier());++ // Case 4: Test if the fetched schema entity is matched.+ reset(entityStore);+ SchemaEntity unmatchedEntity =+ new SchemaEntity.Builder()+ .withId(1L)+ .withName("schema21")+ .withNamespace(Namespace.of(metalake, catalog))+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton")+ .withCreateTime(Instant.now())+ .build())+ .build();+ doReturn(unmatchedEntity).when(entityStore).update(any(), any(), any(), any());+ Schema alteredSchema3 = dispatcher.alterSchema(schemaIdent, changes);+ Assertions.assertEquals(schema.name(), alteredSchema3.name());+ Assertions.assertEquals(schema.comment(), alteredSchema3.comment());+ testProperties(expectedProps, alteredSchema3.properties());+ // Audit info is gotten from catalog, not from the entity store+ Assertions.assertEquals("test", alteredSchema3.auditInfo().creator());+ Assertions.assertEquals("test", alteredSchema1.auditInfo().lastModifier());+ }++ @Test+ public void testCreateAndDropSchema() throws IOException {+ NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, "schema31");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ Schema schema = dispatcher.createSchema(schemaIdent, "comment", props);++ boolean dropped = dispatcher.dropSchema(schemaIdent, false);+ Assertions.assertTrue(dropped);++ // Test if entity store is failed to drop the schema entity+ dispatcher.createSchema(schemaIdent, "comment", props);+ doThrow(new IOException()).when(entityStore).delete(any(), any(), anyBoolean());+ Assertions.assertThrows(+ RuntimeException.class, () -> dispatcher.dropSchema(schemaIdent, false));+ }++ @Test+ public void testCreateAndListTables() throws IOException {+ Namespace tableNs = Namespace.of(metalake, catalog, "schema41");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ Schema schema = dispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);++ NameIdentifier tableIdent1 = NameIdentifier.of(tableNs, "table1");+ Column[] columns =+ new Column[] {+ new TestColumn.Builder().withName("col1").withType(TypeCreator.NULLABLE.STRING).build(),+ new TestColumn.Builder().withName("col2").withType(TypeCreator.NULLABLE.STRING).build()+ };++ Table table1 = dispatcher.createTable(tableIdent1, columns, "comment", props, new Transform[0]);+ Assertions.assertEquals("table1", table1.name());+ Assertions.assertEquals("comment", table1.comment());+ testProperties(props, table1.properties());+ Assertions.assertEquals(0, table1.partitioning().length);+ Assertions.assertArrayEquals(columns, table1.columns());++ // Check if the Table entity is stored in the EntityStore+ TableEntity tableEntity = entityStore.get(tableIdent1, TABLE, TableEntity.class);+ Assertions.assertNotNull(tableEntity);+ Assertions.assertEquals("table1", tableEntity.name());++ StringIdentifier stringId = StringIdentifier.fromProperties(table1.properties());+ Assertions.assertEquals(stringId.id(), tableEntity.id());++ Optional<NameIdentifier> ident1 =+ Arrays.stream(dispatcher.listTables(tableNs))+ .filter(s -> s.name().equals("table1"))+ .findFirst();+ Assertions.assertTrue(ident1.isPresent());++ // Test when the entity store failed to put the table entity+ doThrow(new IOException()).when(entityStore).put(any(), anyBoolean());+ NameIdentifier tableIdent2 = NameIdentifier.of(tableNs, "table2");+ Table table2 = dispatcher.createTable(tableIdent2, columns, "comment", props, new Transform[0]);++ // Check if the created Schema's field values are correct+ Assertions.assertEquals("table2", table2.name());+ Assertions.assertEquals("comment", table2.comment());+ testProperties(props, table2.properties());++ // Check if the Table entity is stored in the EntityStore+ Assertions.assertFalse(entityStore.exists(tableIdent2, TABLE));+ Assertions.assertThrows(+ NoSuchEntityException.class, () -> entityStore.get(tableIdent2, TABLE, TableEntity.class));++ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", table2.auditInfo().creator());+ }++ @Test+ public void testCreateAndLoadTable() throws IOException {+ Namespace tableNs = Namespace.of(metalake, catalog, "schema51");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ dispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);++ NameIdentifier tableIdent1 = NameIdentifier.of(tableNs, "table11");+ Column[] columns =+ new Column[] {+ new TestColumn.Builder().withName("col1").withType(TypeCreator.NULLABLE.STRING).build(),+ new TestColumn.Builder().withName("col2").withType(TypeCreator.NULLABLE.STRING).build()+ };++ Table table1 = dispatcher.createTable(tableIdent1, columns, "comment", props, new Transform[0]);+ Table loadedTable1 = dispatcher.loadTable(tableIdent1);+ Assertions.assertEquals(table1.name(), loadedTable1.name());+ Assertions.assertEquals(table1.comment(), loadedTable1.comment());+ testProperties(table1.properties(), loadedTable1.properties());+ Assertions.assertEquals(0, loadedTable1.partitioning().length);+ Assertions.assertArrayEquals(table1.columns(), loadedTable1.columns());+ // Audit info is gotten from the entity store+ Assertions.assertEquals("graviton", loadedTable1.auditInfo().creator());++ // Case 2: Test if the table entity is not found in the entity store+ reset(entityStore);+ doThrow(new NoSuchEntityException("")).when(entityStore).get(any(), any(), any());+ Table loadedTable2 = dispatcher.loadTable(tableIdent1);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", loadedTable2.auditInfo().creator());++ // Case 3: Test if the entity store is failed to get the table entity+ reset(entityStore);+ doThrow(new IOException()).when(entityStore).get(any(), any(), any());+ Table loadedTable3 = dispatcher.loadTable(tableIdent1);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", loadedTable3.auditInfo().creator());++ // Case 4: Test if the table entity is not matched+ reset(entityStore);+ TableEntity tableEntity =+ new TableEntity.Builder()+ .withId(1L)+ .withName("table11")+ .withNamespace(tableNs)+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton")+ .withCreateTime(Instant.now())+ .build())+ .build();+ doReturn(tableEntity).when(entityStore).get(any(), any(), any());+ Table loadedTable4 = dispatcher.loadTable(tableIdent1);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", loadedTable4.auditInfo().creator());+ }++ @Test+ public void testCreateAndAlterTable() throws IOException {+ Namespace tableNs = Namespace.of(metalake, catalog, "schema61");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ dispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);++ NameIdentifier tableIdent = NameIdentifier.of(tableNs, "table21");+ Column[] columns =+ new Column[] {+ new TestColumn.Builder().withName("col1").withType(TypeCreator.NULLABLE.STRING).build(),+ new TestColumn.Builder().withName("col2").withType(TypeCreator.NULLABLE.STRING).build()+ };++ Table table = dispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);++ TableChange[] changes =+ new TableChange[] {TableChange.setProperty("k3", "v3"), TableChange.removeProperty("k1")};++ Table alteredTable = dispatcher.alterTable(tableIdent, changes);+ Assertions.assertEquals(table.name(), alteredTable.name());+ Assertions.assertEquals(table.comment(), alteredTable.comment());+ Map<String, String> expectedProps = ImmutableMap.of("k2", "v2", "k3", "v3");+ testProperties(expectedProps, alteredTable.properties());+ // Audit info is gotten from graviton entity store+ Assertions.assertEquals("graviton", alteredTable.auditInfo().creator());+ Assertions.assertEquals("graviton", alteredTable.auditInfo().lastModifier());++ // Case 2: Test if the table entity is not found in the entity store+ reset(entityStore);+ doThrow(new NoSuchEntityException("")).when(entityStore).update(any(), any(), any(), any());+ Table alteredTable2 = dispatcher.alterTable(tableIdent, changes);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", alteredTable2.auditInfo().creator());+ Assertions.assertEquals("test", alteredTable2.auditInfo().lastModifier());++ // Case 3: Test if the entity store is failed to update the table entity+ reset(entityStore);+ doThrow(new IOException()).when(entityStore).update(any(), any(), any(), any());+ Table alteredTable3 = dispatcher.alterTable(tableIdent, changes);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", alteredTable3.auditInfo().creator());+ Assertions.assertEquals("test", alteredTable3.auditInfo().lastModifier());++ // Case 4: Test if the table entity is not matched+ reset(entityStore);+ TableEntity unmatchedEntity =+ new TableEntity.Builder()+ .withId(1L)+ .withName("table21")+ .withNamespace(tableNs)+ .withAuditInfo(+ new AuditInfo.Builder()+ .withCreator("graviton")+ .withCreateTime(Instant.now())+ .build())+ .build();+ doReturn(unmatchedEntity).when(entityStore).update(any(), any(), any(), any());+ Table alteredTable4 = dispatcher.alterTable(tableIdent, changes);+ // Audit info is gotten from the catalog, not from the entity store+ Assertions.assertEquals("test", alteredTable4.auditInfo().creator());+ Assertions.assertEquals("test", alteredTable4.auditInfo().lastModifier());+ }++ @Test+ public void testCreateAndDropTable() throws IOException {+ NameIdentifier tableIdent = NameIdentifier.of(metalake, catalog, "schema71", "table31");+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ Column[] columns =+ new Column[] {+ new TestColumn.Builder().withName("col1").withType(TypeCreator.NULLABLE.STRING).build(),+ new TestColumn.Builder().withName("col2").withType(TypeCreator.NULLABLE.STRING).build()+ };+ Table table = dispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);++ boolean dropped = dispatcher.dropTable(tableIdent);+ Assertions.assertTrue(dropped);++ // Test if the entity store is failed to drop the table entity+ dispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);+ reset(entityStore);+ doThrow(new IOException()).when(entityStore).delete(any(), any(), anyBoolean());+ Assertions.assertThrows(RuntimeException.class, () -> dispatcher.dropTable(tableIdent));+ }+@Testpublic void testGetCatalogIdentifier() {- CatalogOperationDispatcher dispatcher = new CatalogOperationDispatcher(null);+ CatalogOperationDispatcher dispatcher = new CatalogOperationDispatcher(null, null, null);NameIdentifier id1 = NameIdentifier.of("a");assertThrows(IllegalNamespaceException.class, () -> dispatcher.getCatalogIdentifier(id1));@@ -31,4 +499,15 @@ public class TestCatalogOperationDispatcher {NameIdentifier id5 = NameIdentifier.of("a", "b", "c", "d", "e");assertEquals(dispatcher.getCatalogIdentifier(id5), NameIdentifier.of("a", "b"));}++ private void testProperties(Map<String, String> expectedProps, Map<String, String> testProps) {+ expectedProps.forEach(+ (k, v) -> {+ Assertions.assertEquals(v, testProps.get(k));+ });++ Assertions.assertTrue(testProps.containsKey(StringIdentifier.ID_KEY));+ StringIdentifier StringId = StringIdentifier.fromString(testProps.get(StringIdentifier.ID_KEY));+ Assertions.assertEquals(StringId.toString(), testProps.get(StringIdentifier.ID_KEY));+ }}diff --git a/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseColumn.java b/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseColumn.javanew file mode 100644index 0000000000..b3201c830e--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseColumn.java@@ -0,0 +1,80 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog.rel;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;++import io.substrait.type.TypeCreator;+import org.junit.jupiter.api.Test;++final class BaseColumnExtension extends BaseColumn {+ private BaseColumnExtension() {}++ public static class Builder extends BaseColumnBuilder<Builder, BaseColumnExtension> {++ @Override+ protected BaseColumnExtension internalBuild() {+ BaseColumnExtension column = new BaseColumnExtension();+ column.name = name;+ column.comment = comment;+ column.dataType = dataType;+ return column;+ }+ }+}++public class TestBaseColumn {++ @Test+ void testColumnFields() {+ BaseColumn column =+ new BaseColumnExtension.Builder()+ .withName("testColumnName")+ .withComment("testColumnComment")+ .withType(TypeCreator.NULLABLE.STRING)+ .build();++ assertEquals("testColumnName", column.name());+ assertEquals("testColumnComment", column.comment());+ assertEquals(TypeCreator.NULLABLE.STRING, column.dataType());+ }++ @Test+ void testEqualsAndHashCode() {+ BaseColumn column1 =+ new BaseColumnExtension.Builder()+ .withName("testColumnName")+ .withComment("testColumnComment")+ .withType(TypeCreator.NULLABLE.STRING)+ .build();++ BaseColumn column2 =+ new BaseColumnExtension.Builder()+ .withName("testColumnName")+ .withComment("testColumnComment")+ .withType(TypeCreator.NULLABLE.STRING)+ .build();++ BaseColumn column3 =+ new BaseColumnExtension.Builder()+ .withName("differentColumnName")+ .withComment("testColumnComment")+ .withType(TypeCreator.NULLABLE.STRING)+ .build();++ BaseColumn column4 =+ new BaseColumnExtension.Builder()+ .withName("testColumnName")+ .withComment("testColumnComment")+ .withType(TypeCreator.NULLABLE.I32)+ .build();++ assertEquals(column1, column2);+ assertEquals(column1.hashCode(), column2.hashCode());+ assertNotEquals(column1, column3);+ assertNotEquals(column1, column4);+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseSchema.java b/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseSchema.javanew file mode 100644index 0000000000..aaba308cef--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseSchema.java@@ -0,0 +1,56 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog.rel;++import static org.junit.jupiter.api.Assertions.assertEquals;++import com.datastrato.graviton.meta.AuditInfo;+import java.time.Instant;+import java.util.HashMap;+import java.util.Map;+import org.junit.jupiter.api.Test;++final class BaseSchemaExtension extends BaseSchema {++ private BaseSchemaExtension() {}++ public static class Builder extends BaseSchemaBuilder<Builder, BaseSchemaExtension> {++ @Override+ protected BaseSchemaExtension internalBuild() {+ BaseSchemaExtension schema = new BaseSchemaExtension();+ schema.name = name;+ schema.comment = comment;+ schema.properties = properties;+ schema.auditInfo = auditInfo;+ return schema;+ }+ }+}++public class TestBaseSchema {++ @Test+ void testSchemaFields() {+ Map<String, String> properties = new HashMap<>();+ properties.put("key1", "value1");+ properties.put("key2", "value2");+ AuditInfo auditInfo =+ new AuditInfo.Builder().withCreator("Justin").withCreateTime(Instant.now()).build();++ BaseSchema schema =+ new BaseSchemaExtension.Builder()+ .withName("testSchemaName")+ .withComment("testSchemaComment")+ .withProperties(properties)+ .withAuditInfo(auditInfo)+ .build();++ assertEquals("testSchemaName", schema.name());+ assertEquals("testSchemaComment", schema.comment());+ assertEquals(properties, schema.properties());+ assertEquals(auditInfo, schema.auditInfo());+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseTable.java b/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseTable.javanew file mode 100644index 0000000000..a6862d4396--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/catalog/rel/TestBaseTable.java@@ -0,0 +1,65 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.catalog.rel;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;++import com.datastrato.graviton.meta.AuditInfo;+import com.datastrato.graviton.rel.Column;+import com.datastrato.graviton.rel.transforms.Transform;+import java.time.Instant;+import java.util.HashMap;+import java.util.Map;+import org.junit.jupiter.api.Test;++final class BaseTableExtension extends BaseTable {++ private BaseTableExtension() {}++ public static class Builder extends BaseTableBuilder<Builder, BaseTableExtension> {++ @Override+ protected BaseTableExtension internalBuild() {+ BaseTableExtension table = new BaseTableExtension();+ table.name = name;+ table.comment = comment;+ table.properties = properties;+ table.auditInfo = auditInfo;+ table.columns = columns;+ table.partitions = partitions;+ return table;+ }+ }+}++public class TestBaseTable {++ @Test+ void testTableFields() {+ Map<String, String> properties = new HashMap<>();+ properties.put("key1", "value1");+ properties.put("key2", "value2");+ AuditInfo auditInfo =+ new AuditInfo.Builder().withCreator("Justin").withCreateTime(Instant.now()).build();++ BaseTable table =+ new BaseTableExtension.Builder()+ .withName("testTableName")+ .withComment("testTableComment")+ .withColumns(new Column[0])+ .withProperties(properties)+ .withPartitions(new Transform[0])+ .withAuditInfo(auditInfo)+ .build();++ assertEquals("testTableName", table.name());+ assertEquals("testTableComment", table.comment());+ assertEquals(table.properties, table.properties());+ assertEquals(table.auditInfo, table.auditInfo());+ assertArrayEquals(new Column[0], table.columns);+ assertArrayEquals(new Transform[0], table.partitions);+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/meta/TestEntity.java b/core/src/test/java/com/datastrato/graviton/meta/TestEntity.javaindex 0e390931b9..df3ac57a8a 100644--- a/core/src/test/java/com/datastrato/graviton/meta/TestEntity.java+++ b/core/src/test/java/com/datastrato/graviton/meta/TestEntity.java@@ -29,6 +29,14 @@ public class TestEntity {private final String catalogName = "testCatalog";private final Catalog.Type type = Catalog.Type.RELATIONAL;+ // Schema test data+ private final Long schemaId = 1L;+ private final String schemaName = "testSchema";++ // Table test data+ private final Long tableId = 1L;+ private final String tableName = "testTable";+@Testpublic void testMetalake() {BaseMetalake metalake =@@ -70,4 +78,34 @@ public class TestEntity {Assertions.assertEquals(map, fields.get(CatalogEntity.PROPERTIES));Assertions.assertEquals(auditInfo, fields.get(CatalogEntity.AUDIT_INFO));}++ @Test+ public void testSchema() {+ SchemaEntity testSchema =+ new SchemaEntity.Builder()+ .withId(schemaId)+ .withName(schemaName)+ .withAuditInfo(auditInfo)+ .build();++ Map<Field, Object> fields = testSchema.fields();+ Assertions.assertEquals(schemaId, fields.get(SchemaEntity.ID));+ Assertions.assertEquals(schemaName, fields.get(SchemaEntity.NAME));+ Assertions.assertEquals(auditInfo, fields.get(SchemaEntity.AUDIT_INFO));+ }++ @Test+ public void testTable() {+ TableEntity testTable =+ new TableEntity.Builder()+ .withId(tableId)+ .withName(tableName)+ .withAuditInfo(auditInfo)+ .build();++ Map<Field, Object> fields = testTable.fields();+ Assertions.assertEquals(tableId, fields.get(TableEntity.ID));+ Assertions.assertEquals(tableName, fields.get(TableEntity.NAME));+ Assertions.assertEquals(auditInfo, fields.get(TableEntity.AUDIT_INFO));+ }}diff --git a/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseColumn.java b/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseColumn.javadeleted file mode 100644index 6a19aed983..0000000000--- a/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseColumn.java+++ /dev/null@@ -1,78 +0,0 @@-/*- * Copyright 2023 Datastrato.- * This software is licensed under the Apache License version 2.- */-package com.datastrato.graviton.meta.rel;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotEquals;--import com.datastrato.graviton.Entity;-import com.datastrato.graviton.Field;-import com.google.common.collect.Maps;-import io.substrait.type.Type;-import java.util.Map;-import org.junit.jupiter.api.Test;--class TestBaseColumn {-- private final class BaseColumnExtension extends BaseColumn {- @Override- public void validate() {}- }-- @Test- void testColumnFields() {- BaseColumn column = new BaseColumnExtension();-- column.name = "testColumnName";- column.comment = "testColumnComment";- column.dataType = Type.withNullability(false).STRING;-- Map<Field, Object> expectedFields = Maps.newHashMap();- expectedFields.put(BaseColumn.NAME, "testColumnName");- expectedFields.put(BaseColumn.COMMENT, "testColumnComment");- expectedFields.put(BaseColumn.TYPE, Type.withNullability(false).STRING);-- assertEquals("testColumnName", column.name());- assertEquals("testColumnComment", column.comment());- assertEquals(Type.withNullability(false).STRING, column.dataType());- assertEquals(Entity.EntityType.COLUMN, column.type());- assertEquals(expectedFields, column.fields());- }-- @Test- void testColumnType() {- BaseColumn table = new BaseColumnExtension();-- assertEquals(Entity.EntityType.COLUMN, table.type());- }-- @Test- void testEqualsAndHashCode() {- BaseColumn column1 = new BaseColumnExtension();- column1.name = "testColumnName";- column1.comment = "testColumnComment";- column1.dataType = Type.withNullability(false).STRING;-- BaseColumn column2 = new BaseColumnExtension();- column2.name = "testColumnName";- column2.comment = "testColumnComment";- column2.dataType = Type.withNullability(false).STRING;-- BaseColumn column3 = new BaseColumnExtension();- column3.name = "differntColumnName";- column3.comment = "testColumnComment";- column3.dataType = Type.withNullability(false).STRING;-- BaseColumn column4 = new BaseColumnExtension();- column4.name = "testColumnName";- column4.comment = "testColumnComment";- column4.dataType = Type.withNullability(false).I32;-- assertEquals(column1, column2);- assertEquals(column1.hashCode(), column2.hashCode());- assertNotEquals(column1, column3);- assertNotEquals(column1, column4);- }-}diff --git a/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseSchema.java b/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseSchema.javadeleted file mode 100644index 9dd764a5a2..0000000000--- a/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseSchema.java+++ /dev/null@@ -1,81 +0,0 @@-/*- * Copyright 2023 Datastrato.- * This software is licensed under the Apache License version 2.- */-package com.datastrato.graviton.meta.rel;--import static org.junit.jupiter.api.Assertions.assertEquals;--import com.datastrato.graviton.Entity;-import com.datastrato.graviton.Field;-import com.datastrato.graviton.meta.AuditInfo;-import com.google.common.collect.Maps;-import java.time.Instant;-import java.util.HashMap;-import java.util.Map;-import org.junit.jupiter.api.Test;--class BaseSchemaTest {-- private final class BaseSchemaExtension extends BaseSchema {- @Override- public void validate() {}- }-- @Test- void testSchemaFields() {- BaseSchema schema = new BaseSchemaExtension();- schema.id = 1L;- schema.name = "testSchemaName";- schema.comment = "testSchemaComment";- schema.properties = new HashMap<>();- schema.properties.put("key1", "value1");- schema.properties.put("key2", "value2");- schema.auditInfo =- new AuditInfo.Builder().withCreator("Justin").withCreateTime(Instant.now()).build();- Map<Field, Object> expectedFields = Maps.newHashMap();- expectedFields.put(BaseSchema.ID, 1L);- expectedFields.put(BaseSchema.NAME, "testSchemaName");- expectedFields.put(BaseSchema.COMMENT, "testSchemaComment");- expectedFields.put(BaseSchema.PROPERTIES, schema.properties);- expectedFields.put(BaseSchema.AUDIT_INFO, schema.auditInfo);-- assertEquals(1L, schema.fields().get(BaseSchema.ID));- assertEquals("testSchemaName", schema.fields().get(BaseSchema.NAME));- assertEquals("testSchemaComment", schema.fields().get(BaseSchema.COMMENT));- assertEquals(schema.properties, schema.fields().get(BaseSchema.PROPERTIES));- assertEquals(schema.auditInfo, schema.fields().get(BaseSchema.AUDIT_INFO));- }-- @Test- void testSchemaType() {- BaseSchema schema = new BaseSchemaExtension();-- assertEquals(Entity.EntityType.SCHEMA, schema.type());- }-- @Test- void testEqualsAndHashCode() {- Instant now = Instant.now();- BaseSchema schema1 = new BaseSchemaExtension();- schema1.id = 1L;- schema1.name = "testSchemaName";- schema1.comment = "testSchemaComment";- schema1.properties = new HashMap<>();- schema1.properties.put("key1", "value1");- schema1.properties.put("key2", "value2");- schema1.auditInfo = new AuditInfo.Builder().withCreator("Justin").withCreateTime(now).build();-- BaseSchema schema2 = new BaseSchemaExtension();- schema2.id = 1L;- schema2.name = "testSchemaName";- schema2.comment = "testSchemaComment";- schema2.properties = new HashMap<>();- schema2.properties.put("key1", "value1");- schema2.properties.put("key2", "value2");- schema2.auditInfo = new AuditInfo.Builder().withCreator("Justin").withCreateTime(now).build();-- assertEquals(schema1, schema2);- assertEquals(schema1.hashCode(), schema2.hashCode());- }-}diff --git a/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseTable.java b/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseTable.javadeleted file mode 100644index 72b331ecc2..0000000000--- a/core/src/test/java/com/datastrato/graviton/meta/rel/TestBaseTable.java+++ /dev/null@@ -1,89 +0,0 @@-/*- * Copyright 2023 Datastrato.- * This software is licensed under the Apache License version 2.- */-package com.datastrato.graviton.meta.rel;--import static org.junit.jupiter.api.Assertions.assertArrayEquals;-import static org.junit.jupiter.api.Assertions.assertEquals;--import com.datastrato.graviton.Entity;-import com.datastrato.graviton.Field;-import com.datastrato.graviton.meta.AuditInfo;-import com.datastrato.graviton.rel.Column;-import com.google.common.collect.Maps;-import java.time.Instant;-import java.util.HashMap;-import java.util.Map;-import org.junit.jupiter.api.Test;--class BaseTableTest {-- private final class BaseTableExtension extends BaseTable {- @Override- public void validate() {}- }-- @Test- void testTableFields() {- BaseTable table = new BaseTableExtension();- table.id = 1L;- table.name = "testTableName";- table.comment = "testTableComment";- table.properties = new HashMap<>();- table.properties.put("key1", "value1");- table.properties.put("key2", "value2");- table.auditInfo =- new AuditInfo.Builder().withCreator("Justin").withCreateTime(Instant.now()).build();- table.columns = new Column[0];-- Map<Field, Object> expectedFields = Maps.newHashMap();- expectedFields.put(BaseTable.ID, 1L);- expectedFields.put(BaseTable.NAME, "testTableName");- expectedFields.put(BaseTable.COMMENT, "testTableComment");- expectedFields.put(BaseTable.PROPERTIES, table.properties);- expectedFields.put(BaseTable.AUDIT_INFO, table.auditInfo);- expectedFields.put(BaseTable.COLUMNS, table.columns);-- assertEquals(1L, table.fields().get(BaseTable.ID));- assertEquals("testTableName", table.fields().get(BaseTable.NAME));- assertEquals("testTableComment", table.fields().get(BaseTable.COMMENT));- assertEquals(table.properties, table.fields().get(BaseTable.PROPERTIES));- assertEquals(table.auditInfo, table.fields().get(BaseTable.AUDIT_INFO));- assertArrayEquals(table.columns, (Column[]) table.fields().get(BaseTable.COLUMNS));- }-- @Test- void testTableType() {- BaseTable table = new BaseTableExtension();-- assertEquals(Entity.EntityType.TABLE, table.type());- }-- @Test- void testEqualsAndHashCode() {- Instant now = Instant.now();- BaseTable table1 = new BaseTableExtension();- table1.id = 1L;- table1.name = "testTableName";- table1.comment = "testTableComment";- table1.properties = new HashMap<>();- table1.properties.put("key1", "value1");- table1.properties.put("key2", "value2");- table1.auditInfo = new AuditInfo.Builder().withCreator("Justin").withCreateTime(now).build();- table1.columns = new Column[0];-- BaseTable table2 = new BaseTableExtension();- table2.id = 1L;- table2.name = "testTableName";- table2.comment = "testTableComment";- table2.properties = new HashMap<>();- table2.properties.put("key1", "value1");- table2.properties.put("key2", "value2");- table2.auditInfo = new AuditInfo.Builder().withCreator("Justin").withCreateTime(now).build();- table2.columns = new Column[0];-- assertEquals(table1, table2);- assertEquals(table1.hashCode(), table2.hashCode());- }-}diff --git a/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java b/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.javaindex 1e32e8ba51..b2c462d352 100644--- a/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java+++ b/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java@@ -129,5 +129,35 @@ public class TestEntityProtoSerDe {protoEntitySerDe.deserialize(catalogBytes, com.datastrato.graviton.meta.CatalogEntity.class);Assertions.assertEquals(catalogEntity, catalogEntityFromBytes);++ // Test SchemaEntity+ Long schemaId = 1L;+ String schemaName = "schema";+ com.datastrato.graviton.meta.SchemaEntity schemaEntity =+ new com.datastrato.graviton.meta.SchemaEntity.Builder()+ .withId(schemaId)+ .withName(schemaName)+ .withAuditInfo(auditInfo)+ .build();++ byte[] schemaBytes = protoEntitySerDe.serialize(schemaEntity);+ com.datastrato.graviton.meta.SchemaEntity schemaEntityFromBytes =+ protoEntitySerDe.deserialize(schemaBytes, com.datastrato.graviton.meta.SchemaEntity.class);+ Assertions.assertEquals(schemaEntity, schemaEntityFromBytes);++ // Test TableEntity+ Long tableId = 1L;+ String tableName = "table";+ com.datastrato.graviton.meta.TableEntity tableEntity =+ new com.datastrato.graviton.meta.TableEntity.Builder()+ .withId(tableId)+ .withName(tableName)+ .withAuditInfo(auditInfo)+ .build();++ byte[] tableBytes = protoEntitySerDe.serialize(tableEntity);+ com.datastrato.graviton.meta.TableEntity tableEntityFromBytes =+ protoEntitySerDe.deserialize(tableBytes, com.datastrato.graviton.meta.TableEntity.class);+ Assertions.assertEquals(tableEntity, tableEntityFromBytes);}}diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.javaindex 2d5a598021..f26063d267 100644--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.java+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.java@@ -27,13 +27,10 @@ import com.datastrato.graviton.exceptions.NonEmptyEntityException;import com.datastrato.graviton.meta.AuditInfo;import com.datastrato.graviton.meta.BaseMetalake;import com.datastrato.graviton.meta.CatalogEntity;+import com.datastrato.graviton.meta.SchemaEntity;import com.datastrato.graviton.meta.SchemaVersion;-import com.datastrato.graviton.meta.rel.BaseSchema;-import com.datastrato.graviton.meta.rel.BaseTable;-import com.datastrato.graviton.rel.Column;-import io.substrait.type.TypeCreator;+import com.datastrato.graviton.meta.TableEntity;import java.io.IOException;-import java.lang.reflect.Field;import java.time.Instant;import java.util.List;import java.util.UUID;@@ -58,59 +55,6 @@ public class TestKvEntityStorage {}}- static class MockSchemaBuilder- extends BaseSchema.BaseSchemaBuilder<MockSchemaBuilder, BaseSchema> {- @Override- protected BaseSchema internalBuild() {- BaseSchema baseSchema = new BaseSchema();- try {- setField(baseSchema, "id", id);- setField(baseSchema, "namespace", namespace);- setField(baseSchema, "name", name);- setField(baseSchema, "comment", comment);- setField(baseSchema, "properties", properties);- setField(baseSchema, "auditInfo", auditInfo);- } catch (Exception e) {- throw new RuntimeException(e);- }- return baseSchema;- }-- private void setField(BaseSchema object, String fieldName, Object value)- throws NoSuchFieldException, IllegalAccessException {- Field field = object.getClass().getDeclaredField(fieldName);- field.setAccessible(true);- field.set(object, value);- }- }-- static class MockTableBuilder extends BaseTable.BaseTableBuilder<MockTableBuilder, BaseTable> {-- @Override- protected BaseTable internalBuild() {- BaseTable baseTable = new BaseTable();- try {- setField(baseTable, "id", id);- setField(baseTable, "namespace", namespace);- setField(baseTable, "name", name);- setField(baseTable, "comment", comment);- setField(baseTable, "properties", properties);- setField(baseTable, "auditInfo", auditInfo);- setField(baseTable, "columns", columns);- } catch (Exception e) {- throw new RuntimeException(e);- }- return baseTable;- }-- private void setField(BaseTable object, String fieldName, Object value)- throws NoSuchFieldException, IllegalAccessException {- Field field = object.getClass().getDeclaredField(fieldName);- field.setAccessible(true);- field.set(object, value);- }- }-public BaseMetalake createBaseMakeLake(String name, AuditInfo auditInfo) {return new BaseMetalake.Builder().withId(1L)@@ -130,42 +74,21 @@ public class TestKvEntityStorage {.build();}- public BaseSchema createBaseschema(Namespace namespace, String name, AuditInfo auditInfo) {- return new MockSchemaBuilder()+ public SchemaEntity createSchemaEntity(Namespace namespace, String name, AuditInfo auditInfo) {+ return new SchemaEntity.Builder().withId(1L).withName(name).withNamespace(namespace).withAuditInfo(auditInfo)- .withComment("a schmea").build();}- public BaseTable createBaseTable(Namespace namespace, String name, AuditInfo auditInfo) {- return new MockTableBuilder()+ public TableEntity createTableEntity(Namespace namespace, String name, AuditInfo auditInfo) {+ return new TableEntity.Builder().withId(1L).withName(name)- .withNameSpace(namespace)+ .withNamespace(namespace).withAuditInfo(auditInfo)- .withComment("a table")- .withColumns(- new Column[] {- new Column() {- @Override- public String name() {- return "test";- }-- @Override- public io.substrait.type.Type dataType() {- return TypeCreator.NULLABLE.I32;- }-- @Override- public String comment() {- return "test";- }- }- }).build();}@@ -189,15 +112,16 @@ public class TestKvEntityStorage {BaseMetalake metalake = createBaseMakeLake("metalake", auditInfo);CatalogEntity catalog = createCatalog(Namespace.of("metalake"), "catalog", auditInfo);CatalogEntity catalogCopy = createCatalog(Namespace.of("metalake"), "catalogCopy", auditInfo);- BaseSchema schema1 =- createBaseschema(Namespace.of("metalake", "catalog"), "schema1", auditInfo);- BaseTable table1 =- createBaseTable(Namespace.of("metalake", "catalog", "schema1"), "table1", auditInfo);- BaseSchema schema2 =- createBaseschema(Namespace.of("metalake", "catalog"), "schema2", auditInfo);- BaseTable table1InSchema2 =- createBaseTable(Namespace.of("metalake", "catalog", "schema2"), "table1", auditInfo);+ SchemaEntity schema1 =+ createSchemaEntity(Namespace.of("metalake", "catalog"), "schema1", auditInfo);+ TableEntity table1 =+ createTableEntity(Namespace.of("metalake", "catalog", "schema1"), "table1", auditInfo);++ SchemaEntity schema2 =+ createSchemaEntity(Namespace.of("metalake", "catalog"), "schema2", auditInfo);+ TableEntity table1InSchema2 =+ createTableEntity(Namespace.of("metalake", "catalog", "schema2"), "table1", auditInfo);// Store all entitiesstore.put(metalake);@@ -208,7 +132,7 @@ public class TestKvEntityStorage {store.put(table1);store.put(table1InSchema2);- // Try to check an update option is what exepct+ // Try to check an update option is what we expectedstore.update(metalake.nameIdentifier(),BaseMetalake.class,@@ -222,7 +146,7 @@ public class TestKvEntityStorage {return createBaseMakeLake("metalakeChanged", auditInfo1);});- // Check metalake entity and subenties are already changed.+ // Check metalake entity and sub-entities are already changed.BaseMetalake updatedMetalake =store.get(NameIdentifier.of("metalakeChanged"), EntityType.METALAKE, BaseMetalake.class);Assertions.assertEquals("creator1", updatedMetalake.auditInfo().creator());@@ -239,24 +163,24 @@ public class TestKvEntityStorage {store.get(NameIdentifier.of("metalakeChanged", "catalog", "schema1"),EntityType.SCHEMA,- BaseSchema.class));+ SchemaEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalog", "schema1", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalog", "schema2"),EntityType.SCHEMA,- BaseSchema.class));+ SchemaEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalog", "schema1", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));- // Check catalog entitis and sub-entities are already changed.+ // Check catalog entities and sub-entities are already changed.store.update(NameIdentifier.of("metalakeChanged", "catalog"),CatalogEntity.class,@@ -286,27 +210,27 @@ public class TestKvEntityStorage {store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1"),EntityType.SCHEMA,- BaseSchema.class));+ SchemaEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),EntityType.SCHEMA,- BaseSchema.class));+ SchemaEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));- // Check schema entitis and sub-entities are already changed.+ // Check schema entities and sub-entities are already changed.store.update(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1"),- BaseSchema.class,+ SchemaEntity.class,EntityType.SCHEMA,e -> {AuditInfo auditInfo1 =@@ -314,7 +238,7 @@ public class TestKvEntityStorage {.withCreator("creator3").withCreateTime(Instant.now()).build();- return createBaseschema(+ return createSchemaEntity(Namespace.of("metalakeChanged", "catalogChanged"), "schemaChanged", auditInfo1);});@@ -324,39 +248,39 @@ public class TestKvEntityStorage {store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1"),EntityType.SCHEMA,- BaseSchema.class));- BaseSchema updatedSchema =+ SchemaEntity.class));+ SchemaEntity updatedSchema =store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged"),EntityType.SCHEMA,- BaseSchema.class);+ SchemaEntity.class);Assertions.assertEquals("creator3", updatedSchema.auditInfo().creator());Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged"),EntityType.SCHEMA,- BaseSchema.class));+ SchemaEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),EntityType.SCHEMA,- BaseSchema.class));+ SchemaEntity.class));Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));// Check table entitiesstore.update(NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged", "table1"),- BaseTable.class,+ TableEntity.class,EntityType.TABLE,e -> {AuditInfo auditInfo1 =@@ -364,7 +288,7 @@ public class TestKvEntityStorage {.withCreator("creator4").withCreateTime(Instant.now()).build();- return createBaseTable(+ return createTableEntity(Namespace.of("metalakeChanged", "catalogChanged", "schemaChanged"),"tableChanged",auditInfo1);@@ -376,20 +300,20 @@ public class TestKvEntityStorage {store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1", "table1"),EntityType.TABLE,- BaseTable.class));- BaseTable updatedTable =+ TableEntity.class));+ TableEntity updatedTable =store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged", "tableChanged"),EntityType.TABLE,- BaseTable.class);+ TableEntity.class);Assertions.assertEquals("creator4", updatedTable.auditInfo().creator());Assertions.assertNotNull(store.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),EntityType.TABLE,- BaseTable.class));+ TableEntity.class));store.delete(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),@@ -400,7 +324,7 @@ public class TestKvEntityStorage {() ->store.update(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),- BaseTable.class,+ TableEntity.class,EntityType.TABLE,(e) -> e));// The updated entities already existed, should throw exception@@ -409,7 +333,7 @@ public class TestKvEntityStorage {() ->store.update(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),- BaseSchema.class,+ SchemaEntity.class,EntityType.SCHEMA,e -> {AuditInfo auditInfo1 =@@ -417,7 +341,7 @@ public class TestKvEntityStorage {.withCreator("creator5").withCreateTime(Instant.now()).build();- return createBaseschema(+ return createSchemaEntity(Namespace.of("metalakeChanged", "catalogChanged"),"schemaChanged",auditInfo1);@@ -425,7 +349,7 @@ public class TestKvEntityStorage {// Update operations do not conatin any changes in namestore.update(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),- BaseSchema.class,+ SchemaEntity.class,EntityType.SCHEMA,e -> {AuditInfo auditInfo1 =@@ -433,7 +357,7 @@ public class TestKvEntityStorage {.withCreator("creator6").withCreateTime(Instant.now()).build();- return createBaseschema(+ return createSchemaEntity(Namespace.of("metalakeChanged", "catalogChanged"), "schema2", auditInfo1);});Assertions.assertEquals(@@ -442,7 +366,7 @@ public class TestKvEntityStorage {.get(NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),EntityType.SCHEMA,- BaseSchema.class)+ SchemaEntity.class).auditInfo().creator());}@@ -469,15 +393,15 @@ public class TestKvEntityStorage {CatalogEntity catalog = createCatalog(Namespace.of("metalake"), "catalog", auditInfo);CatalogEntity catalogCopy = createCatalog(Namespace.of("metalake"), "catalogCopy", auditInfo);- BaseSchema schema1 =- createBaseschema(Namespace.of("metalake", "catalog"), "schema1", auditInfo);- BaseTable table1 =- createBaseTable(Namespace.of("metalake", "catalog", "schema1"), "table1", auditInfo);+ SchemaEntity schema1 =+ createSchemaEntity(Namespace.of("metalake", "catalog"), "schema1", auditInfo);+ TableEntity table1 =+ createTableEntity(Namespace.of("metalake", "catalog", "schema1"), "table1", auditInfo);- BaseSchema schema2 =- createBaseschema(Namespace.of("metalake", "catalog"), "schema2", auditInfo);- BaseTable table1InSchema2 =- createBaseTable(Namespace.of("metalake", "catalog", "schema2"), "table1", auditInfo);+ SchemaEntity schema2 =+ createSchemaEntity(Namespace.of("metalake", "catalog"), "schema2", auditInfo);+ TableEntity table1InSchema2 =+ createTableEntity(Namespace.of("metalake", "catalog", "schema2"), "table1", auditInfo);// Store all entitiesstore.put(metalake);@@ -497,24 +421,24 @@ public class TestKvEntityStorage {catalogCopy,store.get(catalogCopy.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));Assertions.assertEquals(- schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));+ schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class));Assertions.assertEquals(- schema2, store.get(schema2.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));+ schema2, store.get(schema2.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class));Assertions.assertEquals(- table1, store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class));+ table1, store.get(table1.nameIdentifier(), EntityType.TABLE, TableEntity.class));Assertions.assertEquals(table1InSchema2,- store.get(table1InSchema2.nameIdentifier(), EntityType.TABLE, BaseTable.class));+ store.get(table1InSchema2.nameIdentifier(), EntityType.TABLE, TableEntity.class));// Delete the table 'metalake.catalog.schema2.table1'Assertions.assertTrue(store.delete(table1InSchema2.nameIdentifier(), EntityType.TABLE));Assertions.assertFalse(store.exists(table1InSchema2.nameIdentifier(), EntityType.TABLE));// Make sure table 'metalake.catalog.schema1.table1' still exist;Assertions.assertEquals(- table1, store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class));+ table1, store.get(table1.nameIdentifier(), EntityType.TABLE, TableEntity.class));// Make sure schema 'metalake.catalog.schema2' still exist;Assertions.assertEquals(- schema2, store.get(schema2.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));+ schema2, store.get(schema2.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class));// Re-insert table1Inschema2 and everything is OKstore.put(table1InSchema2);Assertions.assertTrue(store.exists(table1InSchema2.nameIdentifier(), EntityType.TABLE));@@ -538,9 +462,9 @@ public class TestKvEntityStorage {store.put(schema1);store.put(table1);Assertions.assertEquals(- schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));+ schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class));Assertions.assertEquals(- table1, store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class));+ table1, store.get(table1.nameIdentifier(), EntityType.TABLE, TableEntity.class));// Now try to delete all schemas under catalog;Assertions.assertThrowsExactly(@@ -578,12 +502,12 @@ public class TestKvEntityStorage {() -> store.delete(schema1.nameIdentifier(), EntityType.SCHEMA));Assertions.assertEquals(- schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));+ schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class));// Test cascade deletestore.delete(schema1.nameIdentifier(), EntityType.SCHEMA, true);try {- store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class);+ store.get(table1.nameIdentifier(), EntityType.TABLE, TableEntity.class);} catch (Exception e) {Assertions.assertTrue(e instanceof NoSuchEntityException);Assertions.assertTrue(e.getMessage().contains("metalake.catalog.schema1"));