Skip to content

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

[#2727] refactor(core,server): refactor CatalogOperationDispatcher (#2728)

mchades0d36d2f4b378
diff --git a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java
index 7537a1e8d5..bd23f9bff4 100644
--- a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java
+++ b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java
@@ -7,7 +7,9 @@ package com.datastrato.gravitino;
import com.datastrato.gravitino.authorization.AccessControlManager;
import com.datastrato.gravitino.auxiliary.AuxiliaryServiceManager;
import com.datastrato.gravitino.catalog.CatalogManager;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.FilesetOperationDispatcher;
+import com.datastrato.gravitino.catalog.SchemaOperationDispatcher;
+import com.datastrato.gravitino.catalog.TableOperationDispatcher;
import com.datastrato.gravitino.lock.LockManager;
import com.datastrato.gravitino.metalake.MetalakeManager;
import com.datastrato.gravitino.metrics.MetricsSystem;
@@ -32,7 +34,11 @@ public class GravitinoEnv {
private CatalogManager catalogManager;
- private CatalogOperationDispatcher catalogOperationDispatcher;
+ private SchemaOperationDispatcher schemaOperationDispatcher;
+
+ private TableOperationDispatcher tableOperationDispatcher;
+
+ private FilesetOperationDispatcher filesetOperationDispatcher;
private MetalakeManager metalakeManager;
@@ -97,8 +103,12 @@ public class GravitinoEnv {
// Create and initialize Catalog related modules
this.catalogManager = new CatalogManager(config, entityStore, idGenerator);
- this.catalogOperationDispatcher =
- new CatalogOperationDispatcher(catalogManager, entityStore, idGenerator);
+ this.schemaOperationDispatcher =
+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator);
+ this.tableOperationDispatcher =
+ new TableOperationDispatcher(catalogManager, entityStore, idGenerator);
+ this.filesetOperationDispatcher =
+ new FilesetOperationDispatcher(catalogManager, entityStore, idGenerator);
// Create and initialize access control related modules
this.accessControlManager = new AccessControlManager(entityStore, idGenerator);
@@ -141,12 +151,30 @@ public class GravitinoEnv {
}
/**
- * Get the CatalogOperationDispatcher associated with the Gravitino environment.
+ * Get the SchemaOperationDispatcher associated with the Gravitino environment.
+ *
+ * @return The SchemaOperationDispatcher instance.
+ */
+ public SchemaOperationDispatcher schemaOperationDispatcher() {
+ return schemaOperationDispatcher;
+ }
+
+ /**
+ * Get the TableOperationDispatcher associated with the Gravitino environment.
+ *
+ * @return The TableOperationDispatcher instance.
+ */
+ public TableOperationDispatcher tableOperationDispatcher() {
+ return tableOperationDispatcher;
+ }
+
+ /**
+ * Get the FilesetOperationDispatcher associated with the Gravitino environment.
*
- * @return The CatalogOperationDispatcher instance.
+ * @return The FilesetOperationDispatcher instance.
*/
- public CatalogOperationDispatcher catalogOperationDispatcher() {
- return catalogOperationDispatcher;
+ public FilesetOperationDispatcher filesetOperationDispatcher() {
+ return filesetOperationDispatcher;
}
/**
diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/CatalogOperationDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/CatalogOperationDispatcher.java
deleted file mode 100644
index 5cfa5e18ef..0000000000
--- a/core/src/main/java/com/datastrato/gravitino/catalog/CatalogOperationDispatcher.java
+++ /dev/null
@@ -1,946 +0,0 @@
-/*
- * Copyright 2023 Datastrato Pvt Ltd.
- * This software is licensed under the Apache License version 2.
- */
-package com.datastrato.gravitino.catalog;
-
-import static com.datastrato.gravitino.Entity.EntityType.SCHEMA;
-import static com.datastrato.gravitino.Entity.EntityType.TABLE;
-import static com.datastrato.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForAlter;
-import static com.datastrato.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;
-import static com.datastrato.gravitino.rel.expressions.transforms.Transforms.EMPTY_TRANSFORM;
-
-import com.datastrato.gravitino.EntityStore;
-import com.datastrato.gravitino.HasIdentifier;
-import com.datastrato.gravitino.NameIdentifier;
-import com.datastrato.gravitino.Namespace;
-import com.datastrato.gravitino.StringIdentifier;
-import com.datastrato.gravitino.connector.BasePropertiesMetadata;
-import com.datastrato.gravitino.connector.HasPropertyMetadata;
-import com.datastrato.gravitino.connector.PropertiesMetadata;
-import com.datastrato.gravitino.exceptions.FilesetAlreadyExistsException;
-import com.datastrato.gravitino.exceptions.IllegalNameIdentifierException;
-import com.datastrato.gravitino.exceptions.NoSuchCatalogException;
-import com.datastrato.gravitino.exceptions.NoSuchEntityException;
-import com.datastrato.gravitino.exceptions.NoSuchFilesetException;
-import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
-import com.datastrato.gravitino.exceptions.NoSuchTableException;
-import com.datastrato.gravitino.exceptions.NonEmptyEntityException;
-import com.datastrato.gravitino.exceptions.NonEmptySchemaException;
-import com.datastrato.gravitino.exceptions.SchemaAlreadyExistsException;
-import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;
-import com.datastrato.gravitino.file.Fileset;
-import com.datastrato.gravitino.file.FilesetCatalog;
-import com.datastrato.gravitino.file.FilesetChange;
-import com.datastrato.gravitino.meta.AuditInfo;
-import com.datastrato.gravitino.meta.SchemaEntity;
-import com.datastrato.gravitino.meta.TableEntity;
-import com.datastrato.gravitino.rel.Column;
-import com.datastrato.gravitino.rel.Schema;
-import com.datastrato.gravitino.rel.SchemaChange;
-import com.datastrato.gravitino.rel.SupportsSchemas;
-import com.datastrato.gravitino.rel.Table;
-import com.datastrato.gravitino.rel.TableCatalog;
-import com.datastrato.gravitino.rel.TableChange;
-import com.datastrato.gravitino.rel.expressions.distributions.Distribution;
-import com.datastrato.gravitino.rel.expressions.distributions.Distributions;
-import com.datastrato.gravitino.rel.expressions.sorts.SortOrder;
-import com.datastrato.gravitino.rel.expressions.transforms.Transform;
-import com.datastrato.gravitino.rel.indexes.Index;
-import com.datastrato.gravitino.rel.indexes.Indexes;
-import com.datastrato.gravitino.storage.IdGenerator;
-import com.datastrato.gravitino.utils.PrincipalUtils;
-import com.datastrato.gravitino.utils.ThrowableFunction;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Maps;
-import java.time.Instant;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-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
- * implementation.
- */
-public class CatalogOperationDispatcher implements TableCatalog, FilesetCatalog, 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, EntityStore store, IdGenerator idGenerator) {
- this.catalogManager = catalogManager;
- this.store = store;
- this.idGenerator = idGenerator;
- }
-
- /**
- * Lists the schemas within the specified namespace.
- *
- * @param namespace The namespace in which to list schemas.
- * @return An array of NameIdentifier objects representing the schemas within the specified
- * namespace.
- * @throws NoSuchCatalogException If the catalog namespace does not exist.
- */
- @Override
- public NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {
- return doWithCatalog(
- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
- c -> c.doWithSchemaOps(s -> s.listSchemas(namespace)),
- NoSuchCatalogException.class);
- }
-
- /**
- * Creates a new schema.
- *
- * @param ident The identifier for the schema to be created.
- * @param comment The comment for the new schema.
- * @param properties Additional properties for the new schema.
- * @return The created Schema object.
- * @throws NoSuchCatalogException If the catalog corresponding to the provided identifier does not
- * exist.
- * @throws SchemaAlreadyExistsException If a schema with the same identifier already exists.
- */
- @Override
- public Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)
- throws NoSuchCatalogException, SchemaAlreadyExistsException {
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p -> {
- validatePropertyForCreate(p.schemaPropertiesMetadata(), properties);
- return null;
- }),
- IllegalArgumentException.class);
- 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.newPropertiesWithId(stringId, properties);
-
- Schema createdSchema =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),
- NoSuchCatalogException.class,
- SchemaAlreadyExistsException.class);
-
- // If the Schema is maintained by the Gravitino's store, we don't have to store again.
- boolean isManagedSchema = isManagedEntity(createdSchema.properties());
- if (isManagedSchema) {
- return EntityCombinedSchema.of(createdSchema)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- createdSchema.properties()));
- }
-
- // Retrieve the Schema again to obtain some values generated by underlying catalog
- Schema schema =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithSchemaOps(s -> s.loadSchema(ident)),
- NoSuchSchemaException.class);
-
- SchemaEntity schemaEntity =
- SchemaEntity.builder()
- .withId(uid)
- .withName(ident.name())
- .withNamespace(ident.namespace())
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
- .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)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
- }
-
- // Merge both the metadata from catalog operation and the metadata from entity store.
- return EntityCombinedSchema.of(schema, schemaEntity)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent, HasPropertyMetadata::schemaPropertiesMetadata, schema.properties()));
- }
-
- /**
- * Loads and retrieves a schema.
- *
- * @param ident The identifier of the schema to be loaded.
- * @return The loaded Schema object.
- * @throws NoSuchSchemaException If the schema does not exist.
- */
- @Override
- public Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {
- NameIdentifier catalogIdentifier = getCatalogIdentifier(ident);
- Schema schema =
- doWithCatalog(
- catalogIdentifier,
- c -> c.doWithSchemaOps(s -> s.loadSchema(ident)),
- NoSuchSchemaException.class);
-
- // If the Schema is maintained by the Gravitino's store, we don't have to load again.
- boolean isManagedSchema = isManagedEntity(schema.properties());
- if (isManagedSchema) {
- return EntityCombinedSchema.of(schema)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdentifier,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
- }
-
- StringIdentifier stringId = getStringIdFromProperties(schema.properties());
- // Case 1: The schema is not created by Gravitino.
- if (stringId == null) {
- return EntityCombinedSchema.of(schema)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdentifier,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
- }
-
- SchemaEntity schemaEntity =
- operateOnEntity(
- ident,
- identifier -> store.get(identifier, SCHEMA, SchemaEntity.class),
- "GET",
- stringId.id());
- return EntityCombinedSchema.of(schema, schemaEntity)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdentifier,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
- }
-
- /**
- * Alters the schema by applying the provided schema changes.
- *
- * @param ident The identifier of the schema to be altered.
- * @param changes The array of SchemaChange objects representing the alterations to apply.
- * @return The altered Schema object.
- * @throws NoSuchSchemaException If the schema corresponding to the provided identifier does not
- * exist.
- */
- @Override
- public Schema alterSchema(NameIdentifier ident, SchemaChange... changes)
- throws NoSuchSchemaException {
- validateAlterProperties(ident, HasPropertyMetadata::schemaPropertiesMetadata, changes);
-
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- Schema tempAlteredSchema =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithSchemaOps(s -> s.alterSchema(ident, changes)),
- NoSuchSchemaException.class);
-
- // Retrieve the Schema again to obtain some values generated by underlying catalog
- Schema alteredSchema =
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithSchemaOps(
- s ->
- s.loadSchema(
- NameIdentifier.of(ident.namespace(), tempAlteredSchema.name()))),
- NoSuchSchemaException.class);
-
- // If the Schema is maintained by the Gravitino's store, we don't have to alter again.
- boolean isManagedSchema = isManagedEntity(alteredSchema.properties());
- if (isManagedSchema) {
- return EntityCombinedSchema.of(alteredSchema)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- alteredSchema.properties()));
- }
-
- StringIdentifier stringId = getStringIdFromProperties(alteredSchema.properties());
- // Case 1: The schema is not created by Gravitino.
- if (stringId == null) {
- return EntityCombinedSchema.of(alteredSchema)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- alteredSchema.properties()));
- }
-
- SchemaEntity updatedSchemaEntity =
- operateOnEntity(
- ident,
- id ->
- store.update(
- id,
- SchemaEntity.class,
- SCHEMA,
- schemaEntity ->
- SchemaEntity.builder()
- .withId(schemaEntity.id())
- .withName(schemaEntity.name())
- .withNamespace(ident.namespace())
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(schemaEntity.auditInfo().creator())
- .withCreateTime(schemaEntity.auditInfo().createTime())
- .withLastModifier(
- PrincipalUtils.getCurrentPrincipal().getName())
- .withLastModifiedTime(Instant.now())
- .build())
- .build()),
- "UPDATE",
- stringId.id());
- return EntityCombinedSchema.of(alteredSchema, updatedSchemaEntity)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- alteredSchema.properties()));
- }
-
- /**
- * Drops a schema.
- *
- * @param ident The identifier of the schema to be dropped.
- * @param cascade If true, drops all tables within the schema as well.
- * @return True if the schema was successfully dropped, false otherwise.
- * @throws NonEmptySchemaException If the schema contains tables and cascade is set to false.
- */
- @Override
- public boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {
- boolean dropped =
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithSchemaOps(s -> s.dropSchema(ident, cascade)),
- NonEmptySchemaException.class);
-
- if (!dropped) {
- return false;
- }
-
- try {
- return store.delete(ident, SCHEMA, cascade);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Lists the tables within a schema.
- *
- * @param namespace The namespace of the schema containing the tables.
- * @return An array of {@link NameIdentifier} objects representing the identifiers of the tables
- * in the schema.
- * @throws NoSuchSchemaException If the specified schema does not exist.
- */
- @Override
- public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
- return doWithCatalog(
- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
- c -> c.doWithTableOps(t -> t.listTables(namespace)),
- NoSuchSchemaException.class);
- }
-
- /**
- * Loads a table.
- *
- * @param ident The identifier of the table to load.
- * @return The loaded {@link Table} object representing the requested table.
- * @throws NoSuchTableException If the specified table does not exist.
- */
- @Override
- public Table loadTable(NameIdentifier ident) throws NoSuchTableException {
- NameIdentifier catalogIdentifier = getCatalogIdentifier(ident);
- Table table =
- doWithCatalog(
- catalogIdentifier,
- c -> c.doWithTableOps(t -> t.loadTable(ident)),
- NoSuchTableException.class);
-
- StringIdentifier stringId = getStringIdFromProperties(table.properties());
- // Case 1: The table is not created by Gravitino.
- if (stringId == null) {
- return EntityCombinedTable.of(table)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdentifier,
- HasPropertyMetadata::tablePropertiesMetadata,
- table.properties()));
- }
-
- TableEntity tableEntity =
- operateOnEntity(
- ident,
- identifier -> store.get(identifier, TABLE, TableEntity.class),
- "GET",
- stringId.id());
-
- return EntityCombinedTable.of(table, tableEntity)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdentifier,
- HasPropertyMetadata::tablePropertiesMetadata,
- table.properties()));
- }
-
- /**
- * Creates a new table in a schema.
- *
- * @param ident The identifier of the table to create.
- * @param columns An array of {@link Column} objects representing the columns of the table.
- * @param comment A description or comment associated with the table.
- * @param properties Additional properties to set for the table.
- * @param partitions An array of {@link Transform} objects representing the partitioning of table
- * @param indexes An array of {@link Index} objects representing the indexes of the table.
- * @return The newly created {@link Table} object.
- * @throws NoSuchSchemaException If the schema in which to create the table does not exist.
- * @throws TableAlreadyExistsException If a table with the same name already exists in the schema.
- */
- @Override
- public Table createTable(
- NameIdentifier ident,
- Column[] columns,
- String comment,
- Map<String, String> properties,
- Transform[] partitions,
- Distribution distribution,
- SortOrder[] sortOrders,
- Index[] indexes)
- throws NoSuchSchemaException, TableAlreadyExistsException {
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p -> {
- validatePropertyForCreate(p.tablePropertiesMetadata(), properties);
- return null;
- }),
- IllegalArgumentException.class);
- 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.newPropertiesWithId(stringId, properties);
-
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithTableOps(
- t ->
- t.createTable(
- ident,
- columns,
- comment,
- updatedProperties,
- partitions == null ? EMPTY_TRANSFORM : partitions,
- distribution == null ? Distributions.NONE : distribution,
- sortOrders == null ? new SortOrder[0] : sortOrders,
- indexes == null ? Indexes.EMPTY_INDEXES : indexes)),
- NoSuchSchemaException.class,
- TableAlreadyExistsException.class);
-
- // Retrieve the Table again to obtain some values generated by underlying catalog
- Table table =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithTableOps(t -> t.loadTable(ident)),
- NoSuchTableException.class);
-
- TableEntity tableEntity =
- TableEntity.builder()
- .withId(uid)
- .withName(ident.name())
- .withNamespace(ident.namespace())
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
- .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)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
- }
-
- return EntityCombinedTable.of(table, tableEntity)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
- }
-
- /**
- * Alters an existing table.
- *
- * @param ident The identifier of the table to alter.
- * @param changes An array of {@link TableChange} objects representing the changes to apply to the
- * table.
- * @return The altered {@link Table} object after applying the changes.
- * @throws NoSuchTableException If the table to alter does not exist.
- * @throws IllegalArgumentException If an unsupported or invalid change is specified.
- */
- @Override
- public Table alterTable(NameIdentifier ident, TableChange... changes)
- throws NoSuchTableException, IllegalArgumentException {
- validateAlterProperties(ident, HasPropertyMetadata::tablePropertiesMetadata, changes);
-
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- Table tempAlteredTable =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithTableOps(t -> t.alterTable(ident, changes)),
- NoSuchTableException.class,
- IllegalArgumentException.class);
-
- // Retrieve the Table again to obtain some values generated by underlying catalog
- Table alteredTable =
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithTableOps(
- t ->
- t.loadTable(NameIdentifier.of(ident.namespace(), tempAlteredTable.name()))),
- NoSuchTableException.class);
-
- StringIdentifier stringId = getStringIdFromProperties(alteredTable.properties());
- // Case 1: The table is not created by Gravitino.
- if (stringId == null) {
- return EntityCombinedTable.of(alteredTable)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- getCatalogIdentifier(ident),
- HasPropertyMetadata::tablePropertiesMetadata,
- alteredTable.properties()));
- }
-
- 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 TableEntity.builder()
- .withId(tableEntity.id())
- .withName(newName)
- .withNamespace(ident.namespace())
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(tableEntity.auditInfo().creator())
- .withCreateTime(tableEntity.auditInfo().createTime())
- .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())
- .withLastModifiedTime(Instant.now())
- .build())
- .build();
- }),
- "UPDATE",
- stringId.id());
-
- return EntityCombinedTable.of(alteredTable, updatedTableEntity)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- getCatalogIdentifier(ident),
- HasPropertyMetadata::tablePropertiesMetadata,
- alteredTable.properties()));
- }
-
- /**
- * Drops a table from the catalog.
- *
- * @param ident The identifier of the table to drop.
- * @return {@code true} if the table was successfully dropped, {@code false} if the table does not
- * exist.
- * @throws NoSuchTableException If the table to drop does not exist.
- */
- @Override
- public boolean dropTable(NameIdentifier ident) {
- boolean dropped =
- doWithCatalog(
- getCatalogIdentifier(ident),
- 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;
- }
-
- @Override
- public boolean purgeTable(NameIdentifier ident) throws UnsupportedOperationException {
- boolean purged =
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithTableOps(t -> t.purgeTable(ident)),
- NoSuchTableException.class,
- UnsupportedOperationException.class);
-
- if (!purged) {
- return false;
- }
-
- try {
- store.delete(ident, TABLE);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- return true;
- }
-
- @Override
- public NameIdentifier[] listFilesets(Namespace namespace) throws NoSuchSchemaException {
- return doWithCatalog(
- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
- c -> c.doWithFilesetOps(f -> f.listFilesets(namespace)),
- NoSuchSchemaException.class);
- }
-
- @Override
- public Fileset loadFileset(NameIdentifier ident) throws NoSuchFilesetException {
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- Fileset fileset =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithFilesetOps(f -> f.loadFileset(ident)),
- NoSuchFilesetException.class);
-
- // Currently we only support maintaining the Fileset in the Gravitino's store.
- return EntityCombinedFileset.of(fileset)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::filesetPropertiesMetadata,
- fileset.properties()));
- }
-
- @Override
- public Fileset createFileset(
- NameIdentifier ident,
- String comment,
- Fileset.Type type,
- String storageLocation,
- Map<String, String> properties)
- throws NoSuchSchemaException, FilesetAlreadyExistsException {
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p -> {
- validatePropertyForCreate(p.filesetPropertiesMetadata(), properties);
- return null;
- }),
- IllegalArgumentException.class);
- long uid = idGenerator.nextId();
- StringIdentifier stringId = StringIdentifier.fromId(uid);
- Map<String, String> updatedProperties =
- StringIdentifier.newPropertiesWithId(stringId, properties);
-
- Fileset createdFileset =
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithFilesetOps(
- f -> f.createFileset(ident, comment, type, storageLocation, updatedProperties)),
- NoSuchSchemaException.class,
- FilesetAlreadyExistsException.class);
- return EntityCombinedFileset.of(createdFileset)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::filesetPropertiesMetadata,
- createdFileset.properties()));
- }
-
- @Override
- public Fileset alterFileset(NameIdentifier ident, FilesetChange... changes)
- throws NoSuchFilesetException, IllegalArgumentException {
- validateAlterProperties(ident, HasPropertyMetadata::filesetPropertiesMetadata, changes);
-
- NameIdentifier catalogIdent = getCatalogIdentifier(ident);
- Fileset alteredFileset =
- doWithCatalog(
- catalogIdent,
- c -> c.doWithFilesetOps(f -> f.alterFileset(ident, changes)),
- NoSuchFilesetException.class,
- IllegalArgumentException.class);
- return EntityCombinedFileset.of(alteredFileset)
- .withHiddenPropertiesSet(
- getHiddenPropertyNames(
- catalogIdent,
- HasPropertyMetadata::filesetPropertiesMetadata,
- alteredFileset.properties()));
- }
-
- @Override
- public boolean dropFileset(NameIdentifier ident) {
- return doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithFilesetOps(f -> f.dropFileset(ident)),
- NonEmptyEntityException.class);
- }
-
- private <R, E extends Throwable> R doWithCatalog(
- NameIdentifier ident, ThrowableFunction<CatalogManager.CatalogWrapper, R> fn, Class<E> ex)
- throws E {
- try {
- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);
- return fn.apply(c);
- } catch (Throwable throwable) {
- if (ex.isInstance(throwable)) {
- throw ex.cast(throwable);
- }
- throw new RuntimeException(throwable);
- }
- }
-
- private <R, E1 extends Throwable, E2 extends Throwable> R doWithCatalog(
- NameIdentifier ident,
- ThrowableFunction<CatalogManager.CatalogWrapper, R> fn,
- Class<E1> ex1,
- Class<E2> ex2)
- throws E1, E2 {
- try {
- CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);
- return fn.apply(c);
- } catch (Throwable throwable) {
- if (ex1.isInstance(throwable)) {
- throw ex1.cast(throwable);
- } else if (ex2.isInstance(throwable)) {
- throw ex2.cast(throwable);
- }
- if (RuntimeException.class.isAssignableFrom(throwable.getClass())) {
- throw (RuntimeException) throwable;
- }
-
- throw new RuntimeException(throwable);
- }
- }
-
- private Set<String> getHiddenPropertyNames(
- NameIdentifier catalogIdent,
- ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
- Map<String, String> properties) {
- return doWithCatalog(
- catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p -> {
- PropertiesMetadata propertiesMetadata = provider.apply(p);
- return properties.keySet().stream()
- .filter(propertiesMetadata::isHiddenProperty)
- .collect(Collectors.toSet());
- }),
- IllegalArgumentException.class);
- }
-
- private <T> void validateAlterProperties(
- NameIdentifier ident,
- ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
- T... changes) {
- doWithCatalog(
- getCatalogIdentifier(ident),
- c ->
- c.doWithPropertiesMeta(
- p -> {
- Map<String, String> upserts = getPropertiesForSet(changes);
- Map<String, String> deletes = getPropertiesForDelete(changes);
- validatePropertyForAlter(provider.apply(p), upserts, deletes);
- return null;
- }),
- IllegalArgumentException.class);
- }
-
- private <T> Map<String, String> getPropertiesForSet(T... t) {
- Map<String, String> properties = Maps.newHashMap();
- for (T item : t) {
- if (item instanceof TableChange.SetProperty) {
- TableChange.SetProperty setProperty = (TableChange.SetProperty) item;
- properties.put(setProperty.getProperty(), setProperty.getValue());
- } else if (item instanceof SchemaChange.SetProperty) {
- SchemaChange.SetProperty setProperty = (SchemaChange.SetProperty) item;
- properties.put(setProperty.getProperty(), setProperty.getValue());
- } else if (item instanceof FilesetChange.SetProperty) {
- FilesetChange.SetProperty setProperty = (FilesetChange.SetProperty) item;
- properties.put(setProperty.getProperty(), setProperty.getValue());
- }
- }
-
- return properties;
- }
-
- private <T> Map<String, String> getPropertiesForDelete(T... t) {
- Map<String, String> properties = Maps.newHashMap();
- for (T item : t) {
- if (item instanceof TableChange.RemoveProperty) {
- TableChange.RemoveProperty removeProperty = (TableChange.RemoveProperty) item;
- properties.put(removeProperty.getProperty(), removeProperty.getProperty());
- } else if (item instanceof SchemaChange.RemoveProperty) {
- SchemaChange.RemoveProperty removeProperty = (SchemaChange.RemoveProperty) item;
- properties.put(removeProperty.getProperty(), removeProperty.getProperty());
- } else if (item instanceof FilesetChange.RemoveProperty) {
- FilesetChange.RemoveProperty removeProperty = (FilesetChange.RemoveProperty) item;
- properties.put(removeProperty.getProperty(), removeProperty.getProperty());
- }
- }
-
- return properties;
- }
-
- 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 Gravitino, but has no corresponding entity in Gravitino.
- LOG.error(FormattedErrorMessages.ENTITY_NOT_FOUND, ident);
- } catch (Exception e) {
- // Case 3: The table is created by Gravitino, but failed to operate the corresponding entity
- // in Gravitino
- LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, opName, ident, e);
- }
-
- // Case 4: The table is created by Gravitino, 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
- NameIdentifier getCatalogIdentifier(NameIdentifier ident) {
- NameIdentifier.check(
- ident.name() != null, "The name variable in the NameIdentifier must have value.");
- Namespace.check(
- ident.namespace() != null && ident.namespace().length() > 0,
- "Catalog namespace must be non-null and have 1 level, the input namespace is %s",
- ident.namespace());
-
- List<String> allElems =
- Stream.concat(Arrays.stream(ident.namespace().levels()), Stream.of(ident.name()))
- .collect(Collectors.toList());
- if (allElems.size() < 2) {
- throw new IllegalNameIdentifierException(
- "Cannot create a catalog NameIdentifier less than two elements.");
- }
- return NameIdentifier.of(allElems.get(0), allElems.get(1));
- }
-
- private boolean isManagedEntity(Map<String, String> properties) {
- return Optional.ofNullable(properties)
- .map(
- p ->
- p.getOrDefault(
- BasePropertiesMetadata.GRAVITINO_MANAGED_ENTITY, Boolean.FALSE.toString())
- .equals(Boolean.TRUE.toString()))
- .orElse(false);
- }
-
- private static final class FormattedErrorMessages {
- static final String STORE_OP_FAILURE =
- "Failed to {} entity for {} in "
- + "Gravitino, with this situation the returned object will not contain the metadata from "
- + "Gravitino.";
-
- static final String STRING_ID_NOT_FOUND =
- "String identifier is not set in schema properties, "
- + "this is because the schema is not created by Gravitino, or the schema is created by "
- + "Gravitino 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 Gravitino, "
- + "this is unexpected if this is created by Gravitino. With this situation the "
- + "returned object will not contain the metadata from Gravitino";
-
- 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 "
- + "Gravitino. This might be due to some operations that are not performed through Gravitino. "
- + "With this situation the returned object will not contain the metadata from Gravitino";
- }
-}
diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/FilesetOperationDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/FilesetOperationDispatcher.java
new file mode 100644
index 0000000000..4d9166c810
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/catalog/FilesetOperationDispatcher.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;
+
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.StringIdentifier;
+import com.datastrato.gravitino.connector.HasPropertyMetadata;
+import com.datastrato.gravitino.exceptions.FilesetAlreadyExistsException;
+import com.datastrato.gravitino.exceptions.NoSuchFilesetException;
+import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
+import com.datastrato.gravitino.exceptions.NonEmptyEntityException;
+import com.datastrato.gravitino.file.Fileset;
+import com.datastrato.gravitino.file.FilesetCatalog;
+import com.datastrato.gravitino.file.FilesetChange;
+import com.datastrato.gravitino.storage.IdGenerator;
+import java.util.Map;
+
+public class FilesetOperationDispatcher extends OperationDispatcher implements FilesetCatalog {
+ /**
+ * Creates a new FilesetOperationDispatcher instance.
+ *
+ * @param catalogManager The CatalogManager instance to be used for fileset operations.
+ * @param store The EntityStore instance to be used for fileset operations.
+ * @param idGenerator The IdGenerator instance to be used for fileset operations.
+ */
+ public FilesetOperationDispatcher(
+ CatalogManager catalogManager, EntityStore store, IdGenerator idGenerator) {
+ super(catalogManager, store, idGenerator);
+ }
+
+ /**
+ * List the filesets in a schema namespace from the catalog.
+ *
+ * @param namespace A schema namespace.
+ * @return An array of fileset identifiers in the namespace.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ */
+ @Override
+ public NameIdentifier[] listFilesets(Namespace namespace) throws NoSuchSchemaException {
+ return doWithCatalog(
+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
+ c -> c.doWithFilesetOps(f -> f.listFilesets(namespace)),
+ NoSuchSchemaException.class);
+ }
+
+ /**
+ * Load fileset metadata by {@link NameIdentifier} from the catalog.
+ *
+ * @param ident A fileset identifier.
+ * @return The fileset metadata.
+ * @throws NoSuchFilesetException If the fileset does not exist.
+ */
+ @Override
+ public Fileset loadFileset(NameIdentifier ident) throws NoSuchFilesetException {
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ Fileset fileset =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithFilesetOps(f -> f.loadFileset(ident)),
+ NoSuchFilesetException.class);
+
+ // Currently we only support maintaining the Fileset in the Gravitino's store.
+ return EntityCombinedFileset.of(fileset)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::filesetPropertiesMetadata,
+ fileset.properties()));
+ }
+
+ /**
+ * Create a fileset metadata in the catalog.
+ *
+ * <p>If the type of the fileset object is "MANAGED", the underlying storageLocation can be null,
+ * and Gravitino will manage the storage location based on the location of the schema.
+ *
+ * <p>If the type of the fileset object is "EXTERNAL", the underlying storageLocation must be set.
+ *
+ * @param ident A fileset identifier.
+ * @param comment The comment of the fileset.
+ * @param type The type of the fileset.
+ * @param storageLocation The storage location of the fileset.
+ * @param properties The properties of the fileset.
+ * @return The created fileset metadata
+ * @throws NoSuchSchemaException If the schema does not exist.
+ * @throws FilesetAlreadyExistsException If the fileset already exists.
+ */
+ @Override
+ public Fileset createFileset(
+ NameIdentifier ident,
+ String comment,
+ Fileset.Type type,
+ String storageLocation,
+ Map<String, String> properties)
+ throws NoSuchSchemaException, FilesetAlreadyExistsException {
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithPropertiesMeta(
+ p -> {
+ validatePropertyForCreate(p.filesetPropertiesMetadata(), properties);
+ return null;
+ }),
+ IllegalArgumentException.class);
+ long uid = idGenerator.nextId();
+ StringIdentifier stringId = StringIdentifier.fromId(uid);
+ Map<String, String> updatedProperties =
+ StringIdentifier.newPropertiesWithId(stringId, properties);
+
+ Fileset createdFileset =
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithFilesetOps(
+ f -> f.createFileset(ident, comment, type, storageLocation, updatedProperties)),
+ NoSuchSchemaException.class,
+ FilesetAlreadyExistsException.class);
+ return EntityCombinedFileset.of(createdFileset)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::filesetPropertiesMetadata,
+ createdFileset.properties()));
+ }
+
+ /**
+ * Apply the {@link FilesetChange change} to a fileset in the catalog.
+ *
+ * <p>Implementation may reject the change. If any change is rejected, no changes should be
+ * applied to the fileset.
+ *
+ * <p>The {@link FilesetChange.RenameFileset} change will only update the fileset name, the
+ * underlying storage location for managed fileset will not be renamed.
+ *
+ * @param ident A fileset identifier.
+ * @param changes The changes to apply to the fileset.
+ * @return The altered fileset metadata.
+ * @throws NoSuchFilesetException If the fileset does not exist.
+ * @throws IllegalArgumentException If the change is rejected by the implementation.
+ */
+ @Override
+ public Fileset alterFileset(NameIdentifier ident, FilesetChange... changes)
+ throws NoSuchFilesetException, IllegalArgumentException {
+ validateAlterProperties(ident, HasPropertyMetadata::filesetPropertiesMetadata, changes);
+
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ Fileset alteredFileset =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithFilesetOps(f -> f.alterFileset(ident, changes)),
+ NoSuchFilesetException.class,
+ IllegalArgumentException.class);
+ return EntityCombinedFileset.of(alteredFileset)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::filesetPropertiesMetadata,
+ alteredFileset.properties()));
+ }
+
+ /**
+ * Drop a fileset from the catalog.
+ *
+ * <p>The underlying files will be deleted if this fileset type is managed, otherwise, only the
+ * metadata will be dropped.
+ *
+ * @param ident A fileset identifier.
+ * @return true If the fileset is dropped, false the fileset did not exist.
+ */
+ @Override
+ public boolean dropFileset(NameIdentifier ident) {
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithFilesetOps(f -> f.dropFileset(ident)),
+ NonEmptyEntityException.class);
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/OperationDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/OperationDispatcher.java
new file mode 100644
index 0000000000..d4a16ede9d
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/catalog/OperationDispatcher.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright 2023 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForAlter;
+
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.HasIdentifier;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.StringIdentifier;
+import com.datastrato.gravitino.connector.BasePropertiesMetadata;
+import com.datastrato.gravitino.connector.HasPropertyMetadata;
+import com.datastrato.gravitino.connector.PropertiesMetadata;
+import com.datastrato.gravitino.exceptions.IllegalNameIdentifierException;
+import com.datastrato.gravitino.exceptions.NoSuchEntityException;
+import com.datastrato.gravitino.file.FilesetChange;
+import com.datastrato.gravitino.rel.SchemaChange;
+import com.datastrato.gravitino.rel.TableChange;
+import com.datastrato.gravitino.storage.IdGenerator;
+import com.datastrato.gravitino.utils.ThrowableFunction;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Maps;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An operation dispatcher that dispatches the operations to the underlying catalog implementation.
+ */
+public abstract class OperationDispatcher {
+
+ private static final Logger LOG = LoggerFactory.getLogger(OperationDispatcher.class);
+
+ private final CatalogManager catalogManager;
+
+ protected final EntityStore store;
+
+ 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 OperationDispatcher(
+ CatalogManager catalogManager, EntityStore store, IdGenerator idGenerator) {
+ this.catalogManager = catalogManager;
+ this.store = store;
+ this.idGenerator = idGenerator;
+ }
+
+ <R, E extends Throwable> R doWithCatalog(
+ NameIdentifier ident, ThrowableFunction<CatalogManager.CatalogWrapper, R> fn, Class<E> ex)
+ throws E {
+ try {
+ CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);
+ return fn.apply(c);
+ } catch (Throwable throwable) {
+ if (ex.isInstance(throwable)) {
+ throw ex.cast(throwable);
+ }
+ throw new RuntimeException(throwable);
+ }
+ }
+
+ <R, E1 extends Throwable, E2 extends Throwable> R doWithCatalog(
+ NameIdentifier ident,
+ ThrowableFunction<CatalogManager.CatalogWrapper, R> fn,
+ Class<E1> ex1,
+ Class<E2> ex2)
+ throws E1, E2 {
+ try {
+ CatalogManager.CatalogWrapper c = catalogManager.loadCatalogAndWrap(ident);
+ return fn.apply(c);
+ } catch (Throwable throwable) {
+ if (ex1.isInstance(throwable)) {
+ throw ex1.cast(throwable);
+ } else if (ex2.isInstance(throwable)) {
+ throw ex2.cast(throwable);
+ }
+ if (RuntimeException.class.isAssignableFrom(throwable.getClass())) {
+ throw (RuntimeException) throwable;
+ }
+
+ throw new RuntimeException(throwable);
+ }
+ }
+
+ Set<String> getHiddenPropertyNames(
+ NameIdentifier catalogIdent,
+ ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
+ Map<String, String> properties) {
+ return doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithPropertiesMeta(
+ p -> {
+ PropertiesMetadata propertiesMetadata = provider.apply(p);
+ return properties.keySet().stream()
+ .filter(propertiesMetadata::isHiddenProperty)
+ .collect(Collectors.toSet());
+ }),
+ IllegalArgumentException.class);
+ }
+
+ <T> void validateAlterProperties(
+ NameIdentifier ident,
+ ThrowableFunction<HasPropertyMetadata, PropertiesMetadata> provider,
+ T... changes) {
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ c ->
+ c.doWithPropertiesMeta(
+ p -> {
+ Map<String, String> upserts = getPropertiesForSet(changes);
+ Map<String, String> deletes = getPropertiesForDelete(changes);
+ validatePropertyForAlter(provider.apply(p), upserts, deletes);
+ return null;
+ }),
+ IllegalArgumentException.class);
+ }
+
+ private <T> Map<String, String> getPropertiesForSet(T... t) {
+ Map<String, String> properties = Maps.newHashMap();
+ for (T item : t) {
+ if (item instanceof TableChange.SetProperty) {
+ TableChange.SetProperty setProperty = (TableChange.SetProperty) item;
+ properties.put(setProperty.getProperty(), setProperty.getValue());
+ } else if (item instanceof SchemaChange.SetProperty) {
+ SchemaChange.SetProperty setProperty = (SchemaChange.SetProperty) item;
+ properties.put(setProperty.getProperty(), setProperty.getValue());
+ } else if (item instanceof FilesetChange.SetProperty) {
+ FilesetChange.SetProperty setProperty = (FilesetChange.SetProperty) item;
+ properties.put(setProperty.getProperty(), setProperty.getValue());
+ }
+ }
+
+ return properties;
+ }
+
+ private <T> Map<String, String> getPropertiesForDelete(T... t) {
+ Map<String, String> properties = Maps.newHashMap();
+ for (T item : t) {
+ if (item instanceof TableChange.RemoveProperty) {
+ TableChange.RemoveProperty removeProperty = (TableChange.RemoveProperty) item;
+ properties.put(removeProperty.getProperty(), removeProperty.getProperty());
+ } else if (item instanceof SchemaChange.RemoveProperty) {
+ SchemaChange.RemoveProperty removeProperty = (SchemaChange.RemoveProperty) item;
+ properties.put(removeProperty.getProperty(), removeProperty.getProperty());
+ } else if (item instanceof FilesetChange.RemoveProperty) {
+ FilesetChange.RemoveProperty removeProperty = (FilesetChange.RemoveProperty) item;
+ properties.put(removeProperty.getProperty(), removeProperty.getProperty());
+ }
+ }
+
+ return properties;
+ }
+
+ 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;
+ }
+ }
+
+ <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 Gravitino, but has no corresponding entity in Gravitino.
+ LOG.error(FormattedErrorMessages.ENTITY_NOT_FOUND, ident);
+ } catch (Exception e) {
+ // Case 3: The table is created by Gravitino, but failed to operate the corresponding entity
+ // in Gravitino
+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, opName, ident, e);
+ }
+
+ // Case 4: The table is created by Gravitino, 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
+ NameIdentifier getCatalogIdentifier(NameIdentifier ident) {
+ NameIdentifier.check(
+ ident.name() != null, "The name variable in the NameIdentifier must have value.");
+ Namespace.check(
+ ident.namespace() != null && ident.namespace().length() > 0,
+ "Catalog namespace must be non-null and have 1 level, the input namespace is %s",
+ ident.namespace());
+
+ List<String> allElems =
+ Stream.concat(Arrays.stream(ident.namespace().levels()), Stream.of(ident.name()))
+ .collect(Collectors.toList());
+ if (allElems.size() < 2) {
+ throw new IllegalNameIdentifierException(
+ "Cannot create a catalog NameIdentifier less than two elements.");
+ }
+ return NameIdentifier.of(allElems.get(0), allElems.get(1));
+ }
+
+ boolean isManagedEntity(Map<String, String> properties) {
+ return Optional.ofNullable(properties)
+ .map(
+ p ->
+ p.getOrDefault(
+ BasePropertiesMetadata.GRAVITINO_MANAGED_ENTITY, Boolean.FALSE.toString())
+ .equals(Boolean.TRUE.toString()))
+ .orElse(false);
+ }
+
+ static final class FormattedErrorMessages {
+ static final String STORE_OP_FAILURE =
+ "Failed to {} entity for {} in "
+ + "Gravitino, with this situation the returned object will not contain the metadata from "
+ + "Gravitino.";
+
+ static final String STRING_ID_NOT_FOUND =
+ "String identifier is not set in schema properties, "
+ + "this is because the schema is not created by Gravitino, or the schema is created by "
+ + "Gravitino 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 Gravitino, "
+ + "this is unexpected if this is created by Gravitino. With this situation the "
+ + "returned object will not contain the metadata from Gravitino";
+
+ 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 "
+ + "Gravitino. This might be due to some operations that are not performed through Gravitino. "
+ + "With this situation the returned object will not contain the metadata from Gravitino";
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/SchemaOperationDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/SchemaOperationDispatcher.java
new file mode 100644
index 0000000000..ed750ce976
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/catalog/SchemaOperationDispatcher.java
@@ -0,0 +1,315 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.Entity.EntityType.SCHEMA;
+import static com.datastrato.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;
+
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.StringIdentifier;
+import com.datastrato.gravitino.connector.HasPropertyMetadata;
+import com.datastrato.gravitino.exceptions.NoSuchCatalogException;
+import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
+import com.datastrato.gravitino.exceptions.NonEmptySchemaException;
+import com.datastrato.gravitino.exceptions.SchemaAlreadyExistsException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.SchemaEntity;
+import com.datastrato.gravitino.rel.Schema;
+import com.datastrato.gravitino.rel.SchemaChange;
+import com.datastrato.gravitino.rel.SupportsSchemas;
+import com.datastrato.gravitino.storage.IdGenerator;
+import com.datastrato.gravitino.utils.PrincipalUtils;
+import java.time.Instant;
+import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SchemaOperationDispatcher extends OperationDispatcher implements SupportsSchemas {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SchemaOperationDispatcher.class);
+
+ /**
+ * Creates a new SchemaOperationDispatcher instance.
+ *
+ * @param catalogManager The CatalogManager instance to be used for schema operations.
+ * @param store The EntityStore instance to be used for schema operations.
+ * @param idGenerator The IdGenerator instance to be used for schema operations.
+ */
+ public SchemaOperationDispatcher(
+ CatalogManager catalogManager, EntityStore store, IdGenerator idGenerator) {
+ super(catalogManager, store, idGenerator);
+ }
+
+ /**
+ * Lists the schemas within the specified namespace.
+ *
+ * @param namespace The namespace in which to list schemas.
+ * @return An array of NameIdentifier objects representing the schemas within the specified
+ * namespace.
+ * @throws NoSuchCatalogException If the catalog namespace does not exist.
+ */
+ @Override
+ public NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {
+ return doWithCatalog(
+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
+ c -> c.doWithSchemaOps(s -> s.listSchemas(namespace)),
+ NoSuchCatalogException.class);
+ }
+
+ /**
+ * Creates a new schema.
+ *
+ * @param ident The identifier for the schema to be created.
+ * @param comment The comment for the new schema.
+ * @param properties Additional properties for the new schema.
+ * @return The created Schema object.
+ * @throws NoSuchCatalogException If the catalog corresponding to the provided identifier does not
+ * exist.
+ * @throws SchemaAlreadyExistsException If a schema with the same identifier already exists.
+ */
+ @Override
+ public Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)
+ throws NoSuchCatalogException, SchemaAlreadyExistsException {
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithPropertiesMeta(
+ p -> {
+ validatePropertyForCreate(p.schemaPropertiesMetadata(), properties);
+ return null;
+ }),
+ IllegalArgumentException.class);
+ 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.newPropertiesWithId(stringId, properties);
+
+ Schema createdSchema =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),
+ NoSuchCatalogException.class,
+ SchemaAlreadyExistsException.class);
+
+ // If the Schema is maintained by the Gravitino's store, we don't have to store again.
+ boolean isManagedSchema = isManagedEntity(createdSchema.properties());
+ if (isManagedSchema) {
+ return EntityCombinedSchema.of(createdSchema)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ createdSchema.properties()));
+ }
+
+ // Retrieve the Schema again to obtain some values generated by underlying catalog
+ Schema schema =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithSchemaOps(s -> s.loadSchema(ident)),
+ NoSuchSchemaException.class);
+
+ SchemaEntity schemaEntity =
+ SchemaEntity.builder()
+ .withId(uid)
+ .withName(ident.name())
+ .withNamespace(ident.namespace())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .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)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ schema.properties()));
+ }
+
+ // Merge both the metadata from catalog operation and the metadata from entity store.
+ return EntityCombinedSchema.of(schema, schemaEntity)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent, HasPropertyMetadata::schemaPropertiesMetadata, schema.properties()));
+ }
+
+ /**
+ * Loads and retrieves a schema.
+ *
+ * @param ident The identifier of the schema to be loaded.
+ * @return The loaded Schema object.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ */
+ @Override
+ public Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {
+ NameIdentifier catalogIdentifier = getCatalogIdentifier(ident);
+ Schema schema =
+ doWithCatalog(
+ catalogIdentifier,
+ c -> c.doWithSchemaOps(s -> s.loadSchema(ident)),
+ NoSuchSchemaException.class);
+
+ // If the Schema is maintained by the Gravitino's store, we don't have to load again.
+ boolean isManagedSchema = isManagedEntity(schema.properties());
+ if (isManagedSchema) {
+ return EntityCombinedSchema.of(schema)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdentifier,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ schema.properties()));
+ }
+
+ StringIdentifier stringId = getStringIdFromProperties(schema.properties());
+ // Case 1: The schema is not created by Gravitino.
+ if (stringId == null) {
+ return EntityCombinedSchema.of(schema)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdentifier,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ schema.properties()));
+ }
+
+ SchemaEntity schemaEntity =
+ operateOnEntity(
+ ident,
+ identifier -> store.get(identifier, SCHEMA, SchemaEntity.class),
+ "GET",
+ stringId.id());
+ return EntityCombinedSchema.of(schema, schemaEntity)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdentifier,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ schema.properties()));
+ }
+
+ /**
+ * Alters the schema by applying the provided schema changes.
+ *
+ * @param ident The identifier of the schema to be altered.
+ * @param changes The array of SchemaChange objects representing the alterations to apply.
+ * @return The altered Schema object.
+ * @throws NoSuchSchemaException If the schema corresponding to the provided identifier does not
+ * exist.
+ */
+ @Override
+ public Schema alterSchema(NameIdentifier ident, SchemaChange... changes)
+ throws NoSuchSchemaException {
+ validateAlterProperties(ident, HasPropertyMetadata::schemaPropertiesMetadata, changes);
+
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ Schema tempAlteredSchema =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithSchemaOps(s -> s.alterSchema(ident, changes)),
+ NoSuchSchemaException.class);
+
+ // Retrieve the Schema again to obtain some values generated by underlying catalog
+ Schema alteredSchema =
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithSchemaOps(
+ s ->
+ s.loadSchema(
+ NameIdentifier.of(ident.namespace(), tempAlteredSchema.name()))),
+ NoSuchSchemaException.class);
+
+ // If the Schema is maintained by the Gravitino's store, we don't have to alter again.
+ boolean isManagedSchema = isManagedEntity(alteredSchema.properties());
+ if (isManagedSchema) {
+ return EntityCombinedSchema.of(alteredSchema)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ alteredSchema.properties()));
+ }
+
+ StringIdentifier stringId = getStringIdFromProperties(alteredSchema.properties());
+ // Case 1: The schema is not created by Gravitino.
+ if (stringId == null) {
+ return EntityCombinedSchema.of(alteredSchema)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ alteredSchema.properties()));
+ }
+
+ SchemaEntity updatedSchemaEntity =
+ operateOnEntity(
+ ident,
+ id ->
+ store.update(
+ id,
+ SchemaEntity.class,
+ SCHEMA,
+ schemaEntity ->
+ SchemaEntity.builder()
+ .withId(schemaEntity.id())
+ .withName(schemaEntity.name())
+ .withNamespace(ident.namespace())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(schemaEntity.auditInfo().creator())
+ .withCreateTime(schemaEntity.auditInfo().createTime())
+ .withLastModifier(
+ PrincipalUtils.getCurrentPrincipal().getName())
+ .withLastModifiedTime(Instant.now())
+ .build())
+ .build()),
+ "UPDATE",
+ stringId.id());
+ return EntityCombinedSchema.of(alteredSchema, updatedSchemaEntity)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ alteredSchema.properties()));
+ }
+
+ /**
+ * Drops a schema.
+ *
+ * @param ident The identifier of the schema to be dropped.
+ * @param cascade If true, drops all tables within the schema as well.
+ * @return True if the schema was successfully dropped, false otherwise.
+ * @throws NonEmptySchemaException If the schema contains tables and cascade is set to false.
+ */
+ @Override
+ public boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {
+ boolean dropped =
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithSchemaOps(s -> s.dropSchema(ident, cascade)),
+ NonEmptySchemaException.class);
+
+ if (!dropped) {
+ return false;
+ }
+
+ try {
+ return store.delete(ident, SCHEMA, cascade);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.java
new file mode 100644
index 0000000000..2947ca3180
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.java
@@ -0,0 +1,354 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.Entity.EntityType.TABLE;
+import static com.datastrato.gravitino.catalog.PropertiesMetadataHelpers.validatePropertyForCreate;
+import static com.datastrato.gravitino.rel.expressions.transforms.Transforms.EMPTY_TRANSFORM;
+
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.StringIdentifier;
+import com.datastrato.gravitino.connector.HasPropertyMetadata;
+import com.datastrato.gravitino.exceptions.NoSuchSchemaException;
+import com.datastrato.gravitino.exceptions.NoSuchTableException;
+import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.TableEntity;
+import com.datastrato.gravitino.rel.Column;
+import com.datastrato.gravitino.rel.Table;
+import com.datastrato.gravitino.rel.TableCatalog;
+import com.datastrato.gravitino.rel.TableChange;
+import com.datastrato.gravitino.rel.expressions.distributions.Distribution;
+import com.datastrato.gravitino.rel.expressions.distributions.Distributions;
+import com.datastrato.gravitino.rel.expressions.sorts.SortOrder;
+import com.datastrato.gravitino.rel.expressions.transforms.Transform;
+import com.datastrato.gravitino.rel.indexes.Index;
+import com.datastrato.gravitino.rel.indexes.Indexes;
+import com.datastrato.gravitino.storage.IdGenerator;
+import com.datastrato.gravitino.utils.PrincipalUtils;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class TableOperationDispatcher extends OperationDispatcher implements TableCatalog {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TableOperationDispatcher.class);
+
+ /**
+ * Creates a new TableOperationDispatcher instance.
+ *
+ * @param catalogManager The CatalogManager instance to be used for table operations.
+ * @param store The EntityStore instance to be used for table operations.
+ * @param idGenerator The IdGenerator instance to be used for table operations.
+ */
+ public TableOperationDispatcher(
+ CatalogManager catalogManager, EntityStore store, IdGenerator idGenerator) {
+ super(catalogManager, store, idGenerator);
+ }
+
+ /**
+ * Lists the tables within a schema.
+ *
+ * @param namespace The namespace of the schema containing the tables.
+ * @return An array of {@link NameIdentifier} objects representing the identifiers of the tables
+ * in the schema.
+ * @throws NoSuchSchemaException If the specified schema does not exist.
+ */
+ @Override
+ public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
+ return doWithCatalog(
+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
+ c -> c.doWithTableOps(t -> t.listTables(namespace)),
+ NoSuchSchemaException.class);
+ }
+
+ /**
+ * Loads a table.
+ *
+ * @param ident The identifier of the table to load.
+ * @return The loaded {@link Table} object representing the requested table.
+ * @throws NoSuchTableException If the specified table does not exist.
+ */
+ @Override
+ public Table loadTable(NameIdentifier ident) throws NoSuchTableException {
+ NameIdentifier catalogIdentifier = getCatalogIdentifier(ident);
+ Table table =
+ doWithCatalog(
+ catalogIdentifier,
+ c -> c.doWithTableOps(t -> t.loadTable(ident)),
+ NoSuchTableException.class);
+
+ StringIdentifier stringId = getStringIdFromProperties(table.properties());
+ // Case 1: The table is not created by Gravitino.
+ if (stringId == null) {
+ return EntityCombinedTable.of(table)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdentifier,
+ HasPropertyMetadata::tablePropertiesMetadata,
+ table.properties()));
+ }
+
+ TableEntity tableEntity =
+ operateOnEntity(
+ ident,
+ identifier -> store.get(identifier, TABLE, TableEntity.class),
+ "GET",
+ stringId.id());
+
+ return EntityCombinedTable.of(table, tableEntity)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdentifier,
+ HasPropertyMetadata::tablePropertiesMetadata,
+ table.properties()));
+ }
+
+ /**
+ * Creates a new table in a schema.
+ *
+ * @param ident The identifier of the table to create.
+ * @param columns An array of {@link Column} objects representing the columns of the table.
+ * @param comment A description or comment associated with the table.
+ * @param properties Additional properties to set for the table.
+ * @param partitions An array of {@link Transform} objects representing the partitioning of table
+ * @param indexes An array of {@link Index} objects representing the indexes of the table.
+ * @return The newly created {@link Table} object.
+ * @throws NoSuchSchemaException If the schema in which to create the table does not exist.
+ * @throws TableAlreadyExistsException If a table with the same name already exists in the schema.
+ */
+ @Override
+ public Table createTable(
+ NameIdentifier ident,
+ Column[] columns,
+ String comment,
+ Map<String, String> properties,
+ Transform[] partitions,
+ Distribution distribution,
+ SortOrder[] sortOrders,
+ Index[] indexes)
+ throws NoSuchSchemaException, TableAlreadyExistsException {
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithPropertiesMeta(
+ p -> {
+ validatePropertyForCreate(p.tablePropertiesMetadata(), properties);
+ return null;
+ }),
+ IllegalArgumentException.class);
+ 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.newPropertiesWithId(stringId, properties);
+
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithTableOps(
+ t ->
+ t.createTable(
+ ident,
+ columns,
+ comment,
+ updatedProperties,
+ partitions == null ? EMPTY_TRANSFORM : partitions,
+ distribution == null ? Distributions.NONE : distribution,
+ sortOrders == null ? new SortOrder[0] : sortOrders,
+ indexes == null ? Indexes.EMPTY_INDEXES : indexes)),
+ NoSuchSchemaException.class,
+ TableAlreadyExistsException.class);
+
+ // Retrieve the Table again to obtain some values generated by underlying catalog
+ Table table =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithTableOps(t -> t.loadTable(ident)),
+ NoSuchTableException.class);
+
+ TableEntity tableEntity =
+ TableEntity.builder()
+ .withId(uid)
+ .withName(ident.name())
+ .withNamespace(ident.namespace())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .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)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
+ }
+
+ return EntityCombinedTable.of(table, tableEntity)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ catalogIdent, HasPropertyMetadata::tablePropertiesMetadata, table.properties()));
+ }
+
+ /**
+ * Alters an existing table.
+ *
+ * @param ident The identifier of the table to alter.
+ * @param changes An array of {@link TableChange} objects representing the changes to apply to the
+ * table.
+ * @return The altered {@link Table} object after applying the changes.
+ * @throws NoSuchTableException If the table to alter does not exist.
+ * @throws IllegalArgumentException If an unsupported or invalid change is specified.
+ */
+ @Override
+ public Table alterTable(NameIdentifier ident, TableChange... changes)
+ throws NoSuchTableException, IllegalArgumentException {
+ validateAlterProperties(ident, HasPropertyMetadata::tablePropertiesMetadata, changes);
+
+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);
+ Table tempAlteredTable =
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithTableOps(t -> t.alterTable(ident, changes)),
+ NoSuchTableException.class,
+ IllegalArgumentException.class);
+
+ // Retrieve the Table again to obtain some values generated by underlying catalog
+ Table alteredTable =
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithTableOps(
+ t ->
+ t.loadTable(NameIdentifier.of(ident.namespace(), tempAlteredTable.name()))),
+ NoSuchTableException.class);
+
+ StringIdentifier stringId = getStringIdFromProperties(alteredTable.properties());
+ // Case 1: The table is not created by Gravitino.
+ if (stringId == null) {
+ return EntityCombinedTable.of(alteredTable)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ getCatalogIdentifier(ident),
+ HasPropertyMetadata::tablePropertiesMetadata,
+ alteredTable.properties()));
+ }
+
+ 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 TableEntity.builder()
+ .withId(tableEntity.id())
+ .withName(newName)
+ .withNamespace(ident.namespace())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(tableEntity.auditInfo().creator())
+ .withCreateTime(tableEntity.auditInfo().createTime())
+ .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())
+ .withLastModifiedTime(Instant.now())
+ .build())
+ .build();
+ }),
+ "UPDATE",
+ stringId.id());
+
+ return EntityCombinedTable.of(alteredTable, updatedTableEntity)
+ .withHiddenPropertiesSet(
+ getHiddenPropertyNames(
+ getCatalogIdentifier(ident),
+ HasPropertyMetadata::tablePropertiesMetadata,
+ alteredTable.properties()));
+ }
+
+ /**
+ * Drops a table from the catalog.
+ *
+ * @param ident The identifier of the table to drop.
+ * @return {@code true} if the table was successfully dropped, {@code false} if the table does not
+ * exist.
+ * @throws NoSuchTableException If the table to drop does not exist.
+ */
+ @Override
+ public boolean dropTable(NameIdentifier ident) {
+ boolean dropped =
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ 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;
+ }
+
+ /**
+ * Drop a table from the catalog and completely remove its data. Removes both the metadata and the
+ * directory associated with the table completely and skipping trash. If the table is an external
+ * table or the catalogs don't support purge table, {@link UnsupportedOperationException} is
+ * thrown.
+ *
+ * <p>If the catalog supports to purge a table, this method should be overridden. The default
+ * implementation throws an {@link UnsupportedOperationException}.
+ *
+ * @param ident A table identifier.
+ * @return True if the table was purged, false if the table did not exist.
+ * @throws UnsupportedOperationException If the catalog does not support to purge a table.
+ */
+ @Override
+ public boolean purgeTable(NameIdentifier ident) throws UnsupportedOperationException {
+ boolean purged =
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithTableOps(t -> t.purgeTable(ident)),
+ NoSuchTableException.class,
+ UnsupportedOperationException.class);
+
+ if (!purged) {
+ return false;
+ }
+
+ try {
+ store.delete(ident, TABLE);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+}
diff --git a/core/src/test/java/com/datastrato/gravitino/catalog/TestCatalogOperationDispatcher.java b/core/src/test/java/com/datastrato/gravitino/catalog/TestCatalogOperationDispatcher.java
deleted file mode 100644
index 6c16536540..0000000000
--- a/core/src/test/java/com/datastrato/gravitino/catalog/TestCatalogOperationDispatcher.java
+++ /dev/null
@@ -1,693 +0,0 @@
-/*
- * Copyright 2023 Datastrato Pvt Ltd.
- * This software is licensed under the Apache License version 2.
- */
-package com.datastrato.gravitino.catalog;
-
-import static com.datastrato.gravitino.Entity.EntityType.SCHEMA;
-import static com.datastrato.gravitino.Entity.EntityType.TABLE;
-import static com.datastrato.gravitino.StringIdentifier.ID_KEY;
-import static com.datastrato.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;
-import static com.datastrato.gravitino.TestFilesetPropertiesMetadata.TEST_FILESET_HIDDEN_KEY;
-import static com.datastrato.gravitino.connector.BasePropertiesMetadata.GRAVITINO_MANAGED_ENTITY;
-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.gravitino.Catalog;
-import com.datastrato.gravitino.Config;
-import com.datastrato.gravitino.Configs;
-import com.datastrato.gravitino.EntityStore;
-import com.datastrato.gravitino.NameIdentifier;
-import com.datastrato.gravitino.Namespace;
-import com.datastrato.gravitino.StringIdentifier;
-import com.datastrato.gravitino.TestColumn;
-import com.datastrato.gravitino.auth.AuthConstants;
-import com.datastrato.gravitino.exceptions.IllegalNamespaceException;
-import com.datastrato.gravitino.exceptions.NoSuchEntityException;
-import com.datastrato.gravitino.file.Fileset;
-import com.datastrato.gravitino.file.FilesetChange;
-import com.datastrato.gravitino.meta.AuditInfo;
-import com.datastrato.gravitino.meta.BaseMetalake;
-import com.datastrato.gravitino.meta.SchemaEntity;
-import com.datastrato.gravitino.meta.SchemaVersion;
-import com.datastrato.gravitino.meta.TableEntity;
-import com.datastrato.gravitino.rel.Column;
-import com.datastrato.gravitino.rel.Schema;
-import com.datastrato.gravitino.rel.SchemaChange;
-import com.datastrato.gravitino.rel.Table;
-import com.datastrato.gravitino.rel.TableChange;
-import com.datastrato.gravitino.rel.expressions.transforms.Transform;
-import com.datastrato.gravitino.rel.types.Types;
-import com.datastrato.gravitino.storage.IdGenerator;
-import com.datastrato.gravitino.storage.RandomIdGenerator;
-import com.datastrato.gravitino.storage.memory.TestMemoryEntityStore;
-import com.google.common.collect.ImmutableMap;
-import java.io.IOException;
-import java.time.Instant;
-import java.util.Arrays;
-import java.util.HashMap;
-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;
-import org.junit.jupiter.api.function.Executable;
-
-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 TestMemoryEntityStore.InMemoryEntityStore());
- entityStore.initialize(config);
- entityStore.setSerDe(null);
-
- BaseMetalake metalakeEntity =
- BaseMetalake.builder()
- .withId(1L)
- .withName(metalake)
- .withAuditInfo(
- 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();
- catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "test", "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());
-
- // Test required table properties exception
- Map<String, String> illegalTableProperties =
- new HashMap<String, String>() {
- {
- put("k2", "v2");
- }
- };
-
- testPropertyException(
- () -> dispatcher.createSchema(schemaIdent, "comment", illegalTableProperties),
- "Properties are required and must be set");
-
- // Test reserved table properties exception
- illegalTableProperties.put(COMMENT_KEY, "table comment");
- illegalTableProperties.put(ID_KEY, "gravitino.v1.uidfdsafdsa");
- testPropertyException(
- () -> dispatcher.createSchema(schemaIdent, "comment", illegalTableProperties),
- "Properties are reserved and cannot be set",
- "comment",
- "gravitino.identifier");
-
- // 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());
- Assertions.assertNotNull(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(AuthConstants.ANONYMOUS_USER, 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 =
- SchemaEntity.builder()
- .withId(1L)
- .withName("schema11")
- .withNamespace(Namespace.of(metalake, catalog))
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(AuthConstants.ANONYMOUS_USER)
- .withCreateTime(Instant.now())
- .build())
- .build();
- doReturn(unmatchedEntity).when(entityStore).get(any(), any(), any());
- 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);
-
- // Test immutable schema properties
- SchemaChange[] illegalChange =
- new SchemaChange[] {SchemaChange.setProperty(COMMENT_KEY, "new comment")};
- testPropertyException(
- () -> dispatcher.alterSchema(schemaIdent, illegalChange),
- "Property comment is immutable or reserved, cannot be set");
-
- 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 gravitino entity store.
- Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, alteredSchema.auditInfo().creator());
- Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, 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 =
- SchemaEntity.builder()
- .withId(1L)
- .withName("schema21")
- .withNamespace(Namespace.of(metalake, catalog))
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(AuthConstants.ANONYMOUS_USER)
- .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");
-
- 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");
- dispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);
-
- NameIdentifier tableIdent1 = NameIdentifier.of(tableNs, "table1");
- Column[] columns =
- new Column[] {
- TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
- TestColumn.builder().withName("col2").withType(Types.StringType.get()).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());
-
- // Test required table properties exception
- Map<String, String> illegalTableProperties =
- new HashMap<String, String>() {
- {
- put("k2", "v2");
- }
- };
- testPropertyException(
- () ->
- dispatcher.createTable(
- tableIdent1, columns, "comment", illegalTableProperties, new Transform[0]),
- "Properties are required and must be set");
-
- // Test reserved table properties exception
- illegalTableProperties.put(COMMENT_KEY, "table comment");
- illegalTableProperties.put(ID_KEY, "gravitino.v1.uidfdsafdsa");
- testPropertyException(
- () ->
- dispatcher.createTable(
- tableIdent1, columns, "comment", illegalTableProperties, new Transform[0]),
- "Properties are reserved and cannot be set",
- "comment",
- "gravitino.identifier");
-
- // 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());
-
- Assertions.assertFalse(table1.properties().containsKey(ID_KEY));
-
- 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[] {
- TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
- TestColumn.builder().withName("col2").withType(Types.StringType.get()).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(AuthConstants.ANONYMOUS_USER, 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 =
- TableEntity.builder()
- .withId(1L)
- .withName("table11")
- .withNamespace(tableNs)
- .withAuditInfo(
- AuditInfo.builder().withCreator("gravitino").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[] {
- TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
- TestColumn.builder().withName("col2").withType(Types.StringType.get()).build()
- };
-
- Table table = dispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);
-
- // Test immutable table properties
- TableChange[] illegalChange =
- new TableChange[] {TableChange.setProperty(COMMENT_KEY, "new comment")};
- testPropertyException(
- () -> dispatcher.alterTable(tableIdent, illegalChange),
- "Property comment is immutable or reserved, cannot be set");
-
- 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 gravitino entity store
- Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, alteredTable.auditInfo().creator());
- Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, 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 =
- TableEntity.builder()
- .withId(1L)
- .withName("table21")
- .withNamespace(tableNs)
- .withAuditInfo(
- AuditInfo.builder().withCreator("gravitino").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[] {
- TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
- TestColumn.builder().withName("col2").withType(Types.StringType.get()).build()
- };
-
- 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));
- }
-
- @Test
- public void testCreateAndListFilesets() {
- Namespace filesetNs = Namespace.of(metalake, catalog, "schema81");
- Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
- dispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
-
- NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset1");
- Fileset fileset1 =
- dispatcher.createFileset(filesetIdent1, "comment", Fileset.Type.MANAGED, "test", props);
- Assertions.assertEquals("fileset1", fileset1.name());
- Assertions.assertEquals("comment", fileset1.comment());
- testProperties(props, fileset1.properties());
- Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
- Assertions.assertEquals("test", fileset1.storageLocation());
-
- NameIdentifier[] idents = dispatcher.listFilesets(filesetNs);
- Assertions.assertEquals(1, idents.length);
- Assertions.assertEquals(filesetIdent1, idents[0]);
-
- Map<String, String> illegalProps = ImmutableMap.of("k2", "v2");
- testPropertyException(
- () ->
- dispatcher.createFileset(
- filesetIdent1, "comment", Fileset.Type.MANAGED, "test", illegalProps),
- "Properties are required and must be set");
-
- Map<String, String> illegalProps2 = ImmutableMap.of("k1", "v1", ID_KEY, "test");
- testPropertyException(
- () ->
- dispatcher.createFileset(
- filesetIdent1, "comment", Fileset.Type.MANAGED, "test", illegalProps2),
- "Properties are reserved and cannot be set",
- "gravitino.identifier");
- }
-
- @Test
- public void testCreateAndLoadFileset() {
- Namespace filesetNs = Namespace.of(metalake, catalog, "schema91");
- Map<String, String> props = ImmutableMap.of("k1", "v1", "location", "schema91");
- dispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
-
- NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset11");
- Fileset fileset1 =
- dispatcher.createFileset(filesetIdent1, "comment", Fileset.Type.MANAGED, null, props);
- Assertions.assertEquals("fileset11", fileset1.name());
- Assertions.assertEquals("comment", fileset1.comment());
- testProperties(props, fileset1.properties());
- Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
- Assertions.assertNull(fileset1.storageLocation());
-
- Fileset loadedFileset1 = dispatcher.loadFileset(filesetIdent1);
- Assertions.assertEquals(fileset1.name(), loadedFileset1.name());
- Assertions.assertEquals(fileset1.comment(), loadedFileset1.comment());
- testProperties(props, loadedFileset1.properties());
- Assertions.assertEquals(fileset1.type(), loadedFileset1.type());
- Assertions.assertEquals(fileset1.storageLocation(), loadedFileset1.storageLocation());
- }
-
- @Test
- public void testCreateAndAlterFileset() {
- Namespace filesetNs = Namespace.of(metalake, catalog, "schema101");
- Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
- dispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
-
- NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset21");
- Fileset fileset1 =
- dispatcher.createFileset(
- filesetIdent1, "comment", Fileset.Type.MANAGED, "fileset21", props);
- Assertions.assertEquals("fileset21", fileset1.name());
- Assertions.assertEquals("comment", fileset1.comment());
- testProperties(props, fileset1.properties());
- Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
- Assertions.assertEquals("fileset21", fileset1.storageLocation());
-
- FilesetChange[] changes =
- new FilesetChange[] {
- FilesetChange.setProperty("k3", "v3"), FilesetChange.removeProperty("k1")
- };
-
- Fileset alteredFileset = dispatcher.alterFileset(filesetIdent1, changes);
- Assertions.assertEquals(fileset1.name(), alteredFileset.name());
- Assertions.assertEquals(fileset1.comment(), alteredFileset.comment());
- Map<String, String> expectedProps = ImmutableMap.of("k2", "v2", "k3", "v3");
- testProperties(expectedProps, alteredFileset.properties());
-
- // Test immutable fileset properties
- FilesetChange[] illegalChange =
- new FilesetChange[] {FilesetChange.setProperty(GRAVITINO_MANAGED_ENTITY, "test")};
- testPropertyException(
- () -> dispatcher.alterFileset(filesetIdent1, illegalChange),
- "Property gravitino.managed.entity is immutable or reserved, cannot be set");
- }
-
- @Test
- public void testCreateAndDropFileset() {
- Namespace filesetNs = Namespace.of(metalake, catalog, "schema111");
- Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
- dispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
-
- NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset31");
- Fileset fileset1 =
- dispatcher.createFileset(
- filesetIdent1, "comment", Fileset.Type.MANAGED, "fileset31", props);
- Assertions.assertEquals("fileset31", fileset1.name());
- Assertions.assertEquals("comment", fileset1.comment());
- testProperties(props, fileset1.properties());
- Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
- Assertions.assertEquals("fileset31", fileset1.storageLocation());
-
- boolean dropped = dispatcher.dropFileset(filesetIdent1);
- Assertions.assertTrue(dropped);
- }
-
- @Test
- public void testGetCatalogIdentifier() {
- CatalogOperationDispatcher dispatcher = new CatalogOperationDispatcher(null, null, null);
-
- NameIdentifier id1 = NameIdentifier.of("a");
- assertThrows(IllegalNamespaceException.class, () -> dispatcher.getCatalogIdentifier(id1));
-
- NameIdentifier id2 = NameIdentifier.of("a", "b");
- assertEquals(dispatcher.getCatalogIdentifier(id2), NameIdentifier.of("a", "b"));
-
- NameIdentifier id3 = NameIdentifier.of("a", "b", "c");
- assertEquals(dispatcher.getCatalogIdentifier(id3), NameIdentifier.of("a", "b"));
-
- NameIdentifier id4 = NameIdentifier.of("a", "b", "c", "d");
- assertEquals(dispatcher.getCatalogIdentifier(id4), NameIdentifier.of("a", "b"));
-
- 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.assertFalse(testProps.containsKey(StringIdentifier.ID_KEY));
- Assertions.assertFalse(testProps.containsKey(GRAVITINO_MANAGED_ENTITY));
- Assertions.assertFalse(testProps.containsKey(TEST_FILESET_HIDDEN_KEY));
- }
-
- private void testPropertyException(Executable operation, String... errorMessage) {
- IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, operation);
- for (String msg : errorMessage) {
- Assertions.assertTrue(exception.getMessage().contains(msg));
- }
- }
-}
diff --git a/core/src/test/java/com/datastrato/gravitino/catalog/TestFilesetOperationDispatcher.java b/core/src/test/java/com/datastrato/gravitino/catalog/TestFilesetOperationDispatcher.java
new file mode 100644
index 0000000000..3bcd906f33
--- /dev/null
+++ b/core/src/test/java/com/datastrato/gravitino/catalog/TestFilesetOperationDispatcher.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.StringIdentifier.ID_KEY;
+import static com.datastrato.gravitino.connector.BasePropertiesMetadata.GRAVITINO_MANAGED_ENTITY;
+
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.file.Fileset;
+import com.datastrato.gravitino.file.FilesetChange;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.util.Map;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestFilesetOperationDispatcher extends TestOperationDispatcher {
+ private static FilesetOperationDispatcher filesetOperationDispatcher;
+ private static SchemaOperationDispatcher schemaOperationDispatcher;
+
+ @BeforeAll
+ public static void initialize() throws IOException {
+ schemaOperationDispatcher =
+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator);
+ filesetOperationDispatcher =
+ new FilesetOperationDispatcher(catalogManager, entityStore, idGenerator);
+ }
+
+ @Test
+ public void testCreateAndListFilesets() {
+ Namespace filesetNs = Namespace.of(metalake, catalog, "schema81");
+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
+
+ NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset1");
+ Fileset fileset1 =
+ filesetOperationDispatcher.createFileset(
+ filesetIdent1, "comment", Fileset.Type.MANAGED, "test", props);
+ Assertions.assertEquals("fileset1", fileset1.name());
+ Assertions.assertEquals("comment", fileset1.comment());
+ testProperties(props, fileset1.properties());
+ Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
+ Assertions.assertEquals("test", fileset1.storageLocation());
+
+ NameIdentifier[] idents = filesetOperationDispatcher.listFilesets(filesetNs);
+ Assertions.assertEquals(1, idents.length);
+ Assertions.assertEquals(filesetIdent1, idents[0]);
+
+ Map<String, String> illegalProps = ImmutableMap.of("k2", "v2");
+ testPropertyException(
+ () ->
+ filesetOperationDispatcher.createFileset(
+ filesetIdent1, "comment", Fileset.Type.MANAGED, "test", illegalProps),
+ "Properties are required and must be set");
+
+ Map<String, String> illegalProps2 = ImmutableMap.of("k1", "v1", ID_KEY, "test");
+ testPropertyException(
+ () ->
+ filesetOperationDispatcher.createFileset(
+ filesetIdent1, "comment", Fileset.Type.MANAGED, "test", illegalProps2),
+ "Properties are reserved and cannot be set",
+ "gravitino.identifier");
+ }
+
+ @Test
+ public void testCreateAndLoadFileset() {
+ Namespace filesetNs = Namespace.of(metalake, catalog, "schema91");
+ Map<String, String> props = ImmutableMap.of("k1", "v1", "location", "schema91");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
+
+ NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset11");
+ Fileset fileset1 =
+ filesetOperationDispatcher.createFileset(
+ filesetIdent1, "comment", Fileset.Type.MANAGED, null, props);
+ Assertions.assertEquals("fileset11", fileset1.name());
+ Assertions.assertEquals("comment", fileset1.comment());
+ testProperties(props, fileset1.properties());
+ Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
+ Assertions.assertNull(fileset1.storageLocation());
+
+ Fileset loadedFileset1 = filesetOperationDispatcher.loadFileset(filesetIdent1);
+ Assertions.assertEquals(fileset1.name(), loadedFileset1.name());
+ Assertions.assertEquals(fileset1.comment(), loadedFileset1.comment());
+ testProperties(props, loadedFileset1.properties());
+ Assertions.assertEquals(fileset1.type(), loadedFileset1.type());
+ Assertions.assertEquals(fileset1.storageLocation(), loadedFileset1.storageLocation());
+ }
+
+ @Test
+ public void testCreateAndAlterFileset() {
+ Namespace filesetNs = Namespace.of(metalake, catalog, "schema101");
+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
+
+ NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset21");
+ Fileset fileset1 =
+ filesetOperationDispatcher.createFileset(
+ filesetIdent1, "comment", Fileset.Type.MANAGED, "fileset21", props);
+ Assertions.assertEquals("fileset21", fileset1.name());
+ Assertions.assertEquals("comment", fileset1.comment());
+ testProperties(props, fileset1.properties());
+ Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
+ Assertions.assertEquals("fileset21", fileset1.storageLocation());
+
+ FilesetChange[] changes =
+ new FilesetChange[] {
+ FilesetChange.setProperty("k3", "v3"), FilesetChange.removeProperty("k1")
+ };
+
+ Fileset alteredFileset = filesetOperationDispatcher.alterFileset(filesetIdent1, changes);
+ Assertions.assertEquals(fileset1.name(), alteredFileset.name());
+ Assertions.assertEquals(fileset1.comment(), alteredFileset.comment());
+ Map<String, String> expectedProps = ImmutableMap.of("k2", "v2", "k3", "v3");
+ testProperties(expectedProps, alteredFileset.properties());
+
+ // Test immutable fileset properties
+ FilesetChange[] illegalChange =
+ new FilesetChange[] {FilesetChange.setProperty(GRAVITINO_MANAGED_ENTITY, "test")};
+ testPropertyException(
+ () -> filesetOperationDispatcher.alterFileset(filesetIdent1, illegalChange),
+ "Property gravitino.managed.entity is immutable or reserved, cannot be set");
+ }
+
+ @Test
+ public void testCreateAndDropFileset() {
+ Namespace filesetNs = Namespace.of(metalake, catalog, "schema111");
+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(filesetNs.levels()), "comment", props);
+
+ NameIdentifier filesetIdent1 = NameIdentifier.of(filesetNs, "fileset31");
+ Fileset fileset1 =
+ filesetOperationDispatcher.createFileset(
+ filesetIdent1, "comment", Fileset.Type.MANAGED, "fileset31", props);
+ Assertions.assertEquals("fileset31", fileset1.name());
+ Assertions.assertEquals("comment", fileset1.comment());
+ testProperties(props, fileset1.properties());
+ Assertions.assertEquals(Fileset.Type.MANAGED, fileset1.type());
+ Assertions.assertEquals("fileset31", fileset1.storageLocation());
+
+ boolean dropped = filesetOperationDispatcher.dropFileset(filesetIdent1);
+ Assertions.assertTrue(dropped);
+ }
+}
diff --git a/core/src/test/java/com/datastrato/gravitino/catalog/TestOperationDispatcher.java b/core/src/test/java/com/datastrato/gravitino/catalog/TestOperationDispatcher.java
new file mode 100644
index 0000000000..f2f57ac141
--- /dev/null
+++ b/core/src/test/java/com/datastrato/gravitino/catalog/TestOperationDispatcher.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2023 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.TestFilesetPropertiesMetadata.TEST_FILESET_HIDDEN_KEY;
+import static com.datastrato.gravitino.connector.BasePropertiesMetadata.GRAVITINO_MANAGED_ENTITY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+
+import com.datastrato.gravitino.Catalog;
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.Configs;
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.StringIdentifier;
+import com.datastrato.gravitino.exceptions.IllegalNamespaceException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.BaseMetalake;
+import com.datastrato.gravitino.meta.SchemaVersion;
+import com.datastrato.gravitino.storage.IdGenerator;
+import com.datastrato.gravitino.storage.RandomIdGenerator;
+import com.datastrato.gravitino.storage.memory.TestMemoryEntityStore;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Map;
+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;
+import org.junit.jupiter.api.function.Executable;
+
+public abstract class TestOperationDispatcher {
+
+ protected static EntityStore entityStore;
+
+ protected static final IdGenerator idGenerator = new RandomIdGenerator();
+
+ protected static final String metalake = "metalake";
+
+ protected static final String catalog = "catalog";
+
+ protected static CatalogManager catalogManager;
+
+ private static Config config;
+
+ @BeforeAll
+ public static void setUp() throws IOException {
+ config = new Config(false) {};
+ config.set(Configs.CATALOG_LOAD_ISOLATED, false);
+
+ entityStore = spy(new TestMemoryEntityStore.InMemoryEntityStore());
+ entityStore.initialize(config);
+ entityStore.setSerDe(null);
+
+ BaseMetalake metalakeEntity =
+ BaseMetalake.builder()
+ .withId(1L)
+ .withName(metalake)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .withVersion(SchemaVersion.V_0_1)
+ .build();
+ entityStore.put(metalakeEntity, true);
+
+ catalogManager = new CatalogManager(config, entityStore, idGenerator);
+
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog);
+ Map<String, String> props = ImmutableMap.of();
+ catalogManager.createCatalog(ident, Catalog.Type.RELATIONAL, "test", "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 testGetCatalogIdentifier() {
+ OperationDispatcher dispatcher = new OperationDispatcher(null, null, null) {};
+
+ NameIdentifier id1 = NameIdentifier.of("a");
+ assertThrows(IllegalNamespaceException.class, () -> dispatcher.getCatalogIdentifier(id1));
+
+ NameIdentifier id2 = NameIdentifier.of("a", "b");
+ assertEquals(dispatcher.getCatalogIdentifier(id2), NameIdentifier.of("a", "b"));
+
+ NameIdentifier id3 = NameIdentifier.of("a", "b", "c");
+ assertEquals(dispatcher.getCatalogIdentifier(id3), NameIdentifier.of("a", "b"));
+
+ NameIdentifier id4 = NameIdentifier.of("a", "b", "c", "d");
+ assertEquals(dispatcher.getCatalogIdentifier(id4), NameIdentifier.of("a", "b"));
+
+ NameIdentifier id5 = NameIdentifier.of("a", "b", "c", "d", "e");
+ assertEquals(dispatcher.getCatalogIdentifier(id5), NameIdentifier.of("a", "b"));
+ }
+
+ void testProperties(Map<String, String> expectedProps, Map<String, String> testProps) {
+ expectedProps.forEach(
+ (k, v) -> {
+ Assertions.assertEquals(v, testProps.get(k));
+ });
+ Assertions.assertFalse(testProps.containsKey(StringIdentifier.ID_KEY));
+ Assertions.assertFalse(testProps.containsKey(GRAVITINO_MANAGED_ENTITY));
+ Assertions.assertFalse(testProps.containsKey(TEST_FILESET_HIDDEN_KEY));
+ }
+
+ void testPropertyException(Executable operation, String... errorMessage) {
+ IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, operation);
+ for (String msg : errorMessage) {
+ Assertions.assertTrue(exception.getMessage().contains(msg));
+ }
+ }
+}
diff --git a/core/src/test/java/com/datastrato/gravitino/catalog/TestSchemaOperationDispatcher.java b/core/src/test/java/com/datastrato/gravitino/catalog/TestSchemaOperationDispatcher.java
new file mode 100644
index 0000000000..d44295364a
--- /dev/null
+++ b/core/src/test/java/com/datastrato/gravitino/catalog/TestSchemaOperationDispatcher.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.Entity.EntityType.SCHEMA;
+import static com.datastrato.gravitino.StringIdentifier.ID_KEY;
+import static com.datastrato.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;
+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 com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.auth.AuthConstants;
+import com.datastrato.gravitino.exceptions.NoSuchEntityException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.SchemaEntity;
+import com.datastrato.gravitino.rel.Schema;
+import com.datastrato.gravitino.rel.SchemaChange;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
+
+ private static SchemaOperationDispatcher dispatcher;
+
+ @BeforeAll
+ public static void initialize() throws IOException {
+ dispatcher = new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator);
+ }
+
+ @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());
+
+ // Test required table properties exception
+ Map<String, String> illegalTableProperties =
+ new HashMap<String, String>() {
+ {
+ put("k2", "v2");
+ }
+ };
+
+ testPropertyException(
+ () -> dispatcher.createSchema(schemaIdent, "comment", illegalTableProperties),
+ "Properties are required and must be set");
+
+ // Test reserved table properties exception
+ illegalTableProperties.put(COMMENT_KEY, "table comment");
+ illegalTableProperties.put(ID_KEY, "gravitino.v1.uidfdsafdsa");
+ testPropertyException(
+ () -> dispatcher.createSchema(schemaIdent, "comment", illegalTableProperties),
+ "Properties are reserved and cannot be set",
+ "comment",
+ "gravitino.identifier");
+
+ // 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());
+ Assertions.assertNotNull(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 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);
+
+ // Test immutable schema properties
+ SchemaChange[] illegalChange =
+ new SchemaChange[] {SchemaChange.setProperty(COMMENT_KEY, "new comment")};
+ testPropertyException(
+ () -> dispatcher.alterSchema(schemaIdent, illegalChange),
+ "Property comment is immutable or reserved, cannot be set");
+
+ 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 gravitino entity store.
+ Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, alteredSchema.auditInfo().creator());
+ Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, 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 =
+ SchemaEntity.builder()
+ .withId(1L)
+ .withName("schema21")
+ .withNamespace(Namespace.of(metalake, catalog))
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(AuthConstants.ANONYMOUS_USER)
+ .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");
+
+ 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));
+ }
+}
diff --git a/core/src/test/java/com/datastrato/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/com/datastrato/gravitino/catalog/TestTableOperationDispatcher.java
new file mode 100644
index 0000000000..4dc1edab7e
--- /dev/null
+++ b/core/src/test/java/com/datastrato/gravitino/catalog/TestTableOperationDispatcher.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.catalog;
+
+import static com.datastrato.gravitino.Entity.EntityType.TABLE;
+import static com.datastrato.gravitino.StringIdentifier.ID_KEY;
+import static com.datastrato.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;
+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 com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.TestColumn;
+import com.datastrato.gravitino.auth.AuthConstants;
+import com.datastrato.gravitino.exceptions.NoSuchEntityException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.TableEntity;
+import com.datastrato.gravitino.rel.Column;
+import com.datastrato.gravitino.rel.Table;
+import com.datastrato.gravitino.rel.TableChange;
+import com.datastrato.gravitino.rel.expressions.transforms.Transform;
+import com.datastrato.gravitino.rel.types.Types;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestTableOperationDispatcher extends TestOperationDispatcher {
+ private static TableOperationDispatcher tableOperationDispatcher;
+ private static SchemaOperationDispatcher schemaOperationDispatcher;
+
+ @BeforeAll
+ public static void initialize() throws IOException {
+ schemaOperationDispatcher =
+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator);
+ tableOperationDispatcher =
+ new TableOperationDispatcher(catalogManager, entityStore, idGenerator);
+ }
+
+ @Test
+ public void testCreateAndListTables() throws IOException {
+ Namespace tableNs = Namespace.of(metalake, catalog, "schema41");
+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);
+
+ NameIdentifier tableIdent1 = NameIdentifier.of(tableNs, "table1");
+ Column[] columns =
+ new Column[] {
+ TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
+ TestColumn.builder().withName("col2").withType(Types.StringType.get()).build()
+ };
+
+ Table table1 =
+ tableOperationDispatcher.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());
+
+ // Test required table properties exception
+ Map<String, String> illegalTableProperties =
+ new HashMap<String, String>() {
+ {
+ put("k2", "v2");
+ }
+ };
+ testPropertyException(
+ () ->
+ tableOperationDispatcher.createTable(
+ tableIdent1, columns, "comment", illegalTableProperties, new Transform[0]),
+ "Properties are required and must be set");
+
+ // Test reserved table properties exception
+ illegalTableProperties.put(COMMENT_KEY, "table comment");
+ illegalTableProperties.put(ID_KEY, "gravitino.v1.uidfdsafdsa");
+ testPropertyException(
+ () ->
+ tableOperationDispatcher.createTable(
+ tableIdent1, columns, "comment", illegalTableProperties, new Transform[0]),
+ "Properties are reserved and cannot be set",
+ "comment",
+ "gravitino.identifier");
+
+ // 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());
+
+ Assertions.assertFalse(table1.properties().containsKey(ID_KEY));
+
+ Optional<NameIdentifier> ident1 =
+ Arrays.stream(tableOperationDispatcher.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 =
+ tableOperationDispatcher.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");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);
+
+ NameIdentifier tableIdent1 = NameIdentifier.of(tableNs, "table11");
+ Column[] columns =
+ new Column[] {
+ TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
+ TestColumn.builder().withName("col2").withType(Types.StringType.get()).build()
+ };
+
+ Table table1 =
+ tableOperationDispatcher.createTable(
+ tableIdent1, columns, "comment", props, new Transform[0]);
+ Table loadedTable1 = tableOperationDispatcher.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(AuthConstants.ANONYMOUS_USER, 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 = tableOperationDispatcher.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 = tableOperationDispatcher.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 =
+ TableEntity.builder()
+ .withId(1L)
+ .withName("table11")
+ .withNamespace(tableNs)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("gravitino").withCreateTime(Instant.now()).build())
+ .build();
+ doReturn(tableEntity).when(entityStore).get(any(), any(), any());
+ Table loadedTable4 = tableOperationDispatcher.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");
+ schemaOperationDispatcher.createSchema(NameIdentifier.of(tableNs.levels()), "comment", props);
+
+ NameIdentifier tableIdent = NameIdentifier.of(tableNs, "table21");
+ Column[] columns =
+ new Column[] {
+ TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
+ TestColumn.builder().withName("col2").withType(Types.StringType.get()).build()
+ };
+
+ Table table =
+ tableOperationDispatcher.createTable(
+ tableIdent, columns, "comment", props, new Transform[0]);
+
+ // Test immutable table properties
+ TableChange[] illegalChange =
+ new TableChange[] {TableChange.setProperty(COMMENT_KEY, "new comment")};
+ testPropertyException(
+ () -> tableOperationDispatcher.alterTable(tableIdent, illegalChange),
+ "Property comment is immutable or reserved, cannot be set");
+
+ TableChange[] changes =
+ new TableChange[] {TableChange.setProperty("k3", "v3"), TableChange.removeProperty("k1")};
+
+ Table alteredTable = tableOperationDispatcher.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 gravitino entity store
+ Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, alteredTable.auditInfo().creator());
+ Assertions.assertEquals(AuthConstants.ANONYMOUS_USER, 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 = tableOperationDispatcher.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 = tableOperationDispatcher.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 =
+ TableEntity.builder()
+ .withId(1L)
+ .withName("table21")
+ .withNamespace(tableNs)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("gravitino").withCreateTime(Instant.now()).build())
+ .build();
+ doReturn(unmatchedEntity).when(entityStore).update(any(), any(), any(), any());
+ Table alteredTable4 = tableOperationDispatcher.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[] {
+ TestColumn.builder().withName("col1").withType(Types.StringType.get()).build(),
+ TestColumn.builder().withName("col2").withType(Types.StringType.get()).build()
+ };
+
+ tableOperationDispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);
+
+ boolean dropped = tableOperationDispatcher.dropTable(tableIdent);
+ Assertions.assertTrue(dropped);
+
+ // Test if the entity store is failed to drop the table entity
+ tableOperationDispatcher.createTable(tableIdent, columns, "comment", props, new Transform[0]);
+ reset(entityStore);
+ doThrow(new IOException()).when(entityStore).delete(any(), any(), anyBoolean());
+ Assertions.assertThrows(
+ RuntimeException.class, () -> tableOperationDispatcher.dropTable(tableIdent));
+ }
+}
diff --git a/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java b/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java
index 1651f493f6..83533364a0 100644
--- a/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java
+++ b/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java
@@ -6,7 +6,9 @@ package com.datastrato.gravitino.server;
import com.datastrato.gravitino.GravitinoEnv;
import com.datastrato.gravitino.catalog.CatalogManager;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.FilesetOperationDispatcher;
+import com.datastrato.gravitino.catalog.SchemaOperationDispatcher;
+import com.datastrato.gravitino.catalog.TableOperationDispatcher;
import com.datastrato.gravitino.metalake.MetalakeManager;
import com.datastrato.gravitino.metrics.MetricsSystem;
import com.datastrato.gravitino.metrics.source.MetricsSource;
@@ -73,8 +75,14 @@ public class GravitinoServer extends ResourceConfig {
protected void configure() {
bind(gravitinoEnv.metalakesManager()).to(MetalakeManager.class).ranked(1);
bind(gravitinoEnv.catalogManager()).to(CatalogManager.class).ranked(1);
- bind(gravitinoEnv.catalogOperationDispatcher())
- .to(CatalogOperationDispatcher.class)
+ bind(gravitinoEnv.schemaOperationDispatcher())
+ .to(SchemaOperationDispatcher.class)
+ .ranked(1);
+ bind(gravitinoEnv.tableOperationDispatcher())
+ .to(TableOperationDispatcher.class)
+ .ranked(1);
+ bind(gravitinoEnv.filesetOperationDispatcher())
+ .to(FilesetOperationDispatcher.class)
.ranked(1);
}
});
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/FilesetOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/FilesetOperations.java
index 8e2b52e8cd..1e24834e48 100644
--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/FilesetOperations.java
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/FilesetOperations.java
@@ -8,7 +8,7 @@ import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
import com.datastrato.gravitino.NameIdentifier;
import com.datastrato.gravitino.Namespace;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.FilesetOperationDispatcher;
import com.datastrato.gravitino.dto.requests.FilesetCreateRequest;
import com.datastrato.gravitino.dto.requests.FilesetUpdateRequest;
import com.datastrato.gravitino.dto.requests.FilesetUpdatesRequest;
@@ -42,12 +42,12 @@ public class FilesetOperations {
private static final Logger LOG = LoggerFactory.getLogger(FilesetOperations.class);
- private final CatalogOperationDispatcher dispatcher;
+ private final FilesetOperationDispatcher dispatcher;
@Context private HttpServletRequest httpRequest;
@Inject
- public FilesetOperations(CatalogOperationDispatcher dispatcher) {
+ public FilesetOperations(FilesetOperationDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java
index 118d1e63a8..691ea2aafb 100644
--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java
@@ -10,7 +10,7 @@ import static com.datastrato.gravitino.dto.util.DTOConverters.toDTOs;
import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
import com.datastrato.gravitino.NameIdentifier;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.TableOperationDispatcher;
import com.datastrato.gravitino.dto.rel.partitions.PartitionDTO;
import com.datastrato.gravitino.dto.requests.AddPartitionsRequest;
import com.datastrato.gravitino.dto.responses.PartitionListResponse;
@@ -39,11 +39,11 @@ import javax.ws.rs.core.Response;
@Path("/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/tables/{table}/partitions")
public class PartitionOperations {
- private final CatalogOperationDispatcher dispatcher;
+ private final TableOperationDispatcher dispatcher;
@Context private HttpServletRequest httpRequest;
@Inject
- public PartitionOperations(CatalogOperationDispatcher dispatcher) {
+ public PartitionOperations(TableOperationDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/SchemaOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/SchemaOperations.java
index 399f6001a1..bc4dcc009d 100644
--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/SchemaOperations.java
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/SchemaOperations.java
@@ -8,7 +8,7 @@ import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
import com.datastrato.gravitino.NameIdentifier;
import com.datastrato.gravitino.Namespace;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.SchemaOperationDispatcher;
import com.datastrato.gravitino.dto.requests.SchemaCreateRequest;
import com.datastrato.gravitino.dto.requests.SchemaUpdateRequest;
import com.datastrato.gravitino.dto.requests.SchemaUpdatesRequest;
@@ -47,12 +47,12 @@ public class SchemaOperations {
private static final Logger LOG = LoggerFactory.getLogger(SchemaOperations.class);
- private final CatalogOperationDispatcher dispatcher;
+ private final SchemaOperationDispatcher dispatcher;
@Context private HttpServletRequest httpRequest;
@Inject
- public SchemaOperations(CatalogOperationDispatcher dispatcher) {
+ public SchemaOperations(SchemaOperationDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java
index f2bcd9026d..e499270087 100644
--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java
@@ -11,7 +11,7 @@ import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
import com.datastrato.gravitino.NameIdentifier;
import com.datastrato.gravitino.Namespace;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.TableOperationDispatcher;
import com.datastrato.gravitino.dto.requests.TableCreateRequest;
import com.datastrato.gravitino.dto.requests.TableUpdateRequest;
import com.datastrato.gravitino.dto.requests.TableUpdatesRequest;
@@ -46,12 +46,12 @@ public class TableOperations {
private static final Logger LOG = LoggerFactory.getLogger(TableOperations.class);
- private final CatalogOperationDispatcher dispatcher;
+ private final TableOperationDispatcher dispatcher;
@Context private HttpServletRequest httpRequest;
@Inject
- public TableOperations(CatalogOperationDispatcher dispatcher) {
+ public TableOperations(TableOperationDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestFilesetOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestFilesetOperations.java
index 728d8e2078..0d1112cda0 100644
--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestFilesetOperations.java
+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestFilesetOperations.java
@@ -16,7 +16,7 @@ import com.datastrato.gravitino.Audit;
import com.datastrato.gravitino.Config;
import com.datastrato.gravitino.GravitinoEnv;
import com.datastrato.gravitino.NameIdentifier;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.FilesetOperationDispatcher;
import com.datastrato.gravitino.dto.file.FilesetDTO;
import com.datastrato.gravitino.dto.requests.FilesetCreateRequest;
import com.datastrato.gravitino.dto.requests.FilesetUpdateRequest;
@@ -62,7 +62,7 @@ public class TestFilesetOperations extends JerseyTest {
}
}
- private CatalogOperationDispatcher dispatcher = mock(CatalogOperationDispatcher.class);
+ private FilesetOperationDispatcher dispatcher = mock(FilesetOperationDispatcher.class);
private final String metalake = "metalake1";
@@ -94,7 +94,7 @@ public class TestFilesetOperations extends JerseyTest {
new AbstractBinder() {
@Override
protected void configure() {
- bind(dispatcher).to(CatalogOperationDispatcher.class).ranked(2);
+ bind(dispatcher).to(FilesetOperationDispatcher.class).ranked(2);
bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
}
});
diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java
index 1a5803bb7c..1f5d990330 100644
--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java
+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java
@@ -16,7 +16,7 @@ import static org.mockito.Mockito.when;
import com.datastrato.gravitino.Config;
import com.datastrato.gravitino.GravitinoEnv;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.TableOperationDispatcher;
import com.datastrato.gravitino.dto.rel.partitions.PartitionDTO;
import com.datastrato.gravitino.dto.requests.AddPartitionsRequest;
import com.datastrato.gravitino.dto.responses.ErrorConstants;
@@ -86,7 +86,7 @@ public class TestPartitionOperations extends JerseyTest {
}
}
- private CatalogOperationDispatcher dispatcher = mock(CatalogOperationDispatcher.class);
+ private TableOperationDispatcher dispatcher = mock(TableOperationDispatcher.class);
private final String metalake = "metalake1";
private final String catalog = "catalog1";
private final String schema = "schema1";
@@ -116,7 +116,7 @@ public class TestPartitionOperations extends JerseyTest {
new AbstractBinder() {
@Override
protected void configure() {
- bind(dispatcher).to(CatalogOperationDispatcher.class).ranked(2);
+ bind(dispatcher).to(TableOperationDispatcher.class).ranked(2);
bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
}
});
diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestSchemaOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestSchemaOperations.java
index d2d5e3041e..90dec8989f 100644
--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestSchemaOperations.java
+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestSchemaOperations.java
@@ -17,7 +17,7 @@ import com.datastrato.gravitino.Audit;
import com.datastrato.gravitino.Config;
import com.datastrato.gravitino.GravitinoEnv;
import com.datastrato.gravitino.NameIdentifier;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.SchemaOperationDispatcher;
import com.datastrato.gravitino.dto.rel.SchemaDTO;
import com.datastrato.gravitino.dto.requests.SchemaCreateRequest;
import com.datastrato.gravitino.dto.requests.SchemaUpdateRequest;
@@ -63,7 +63,7 @@ public class TestSchemaOperations extends JerseyTest {
}
}
- private CatalogOperationDispatcher dispatcher = mock(CatalogOperationDispatcher.class);
+ private SchemaOperationDispatcher dispatcher = mock(SchemaOperationDispatcher.class);
private final String metalake = "metalake1";
@@ -93,7 +93,7 @@ public class TestSchemaOperations extends JerseyTest {
new AbstractBinder() {
@Override
protected void configure() {
- bind(dispatcher).to(CatalogOperationDispatcher.class).ranked(2);
+ bind(dispatcher).to(SchemaOperationDispatcher.class).ranked(2);
bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
}
});
diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java
index eccd92e3d3..185f40dc4b 100644
--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java
+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java
@@ -17,7 +17,7 @@ import com.datastrato.gravitino.Audit;
import com.datastrato.gravitino.Config;
import com.datastrato.gravitino.GravitinoEnv;
import com.datastrato.gravitino.NameIdentifier;
-import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
+import com.datastrato.gravitino.catalog.TableOperationDispatcher;
import com.datastrato.gravitino.dto.rel.ColumnDTO;
import com.datastrato.gravitino.dto.rel.DistributionDTO;
import com.datastrato.gravitino.dto.rel.SortOrderDTO;
@@ -87,7 +87,7 @@ public class TestTableOperations extends JerseyTest {
}
}
- private CatalogOperationDispatcher dispatcher = mock(CatalogOperationDispatcher.class);
+ private TableOperationDispatcher dispatcher = mock(TableOperationDispatcher.class);
private final String metalake = "metalake1";
@@ -119,7 +119,7 @@ public class TestTableOperations extends JerseyTest {
new AbstractBinder() {
@Override
protected void configure() {
- bind(dispatcher).to(CatalogOperationDispatcher.class).ranked(2);
+ bind(dispatcher).to(TableOperationDispatcher.class).ranked(2);
bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
}
});