World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#145][#146] feat(client): add client side schema/table manipulation support (#202)
Jerry Shao8f5f96bac091
diff --git a/client-java/src/main/java/com/datastrato/graviton/client/DTOConverters.java b/client-java/src/main/java/com/datastrato/graviton/client/DTOConverters.javaindex bf26345c22..cbf4dad50f 100644--- a/client-java/src/main/java/com/datastrato/graviton/client/DTOConverters.java+++ b/client-java/src/main/java/com/datastrato/graviton/client/DTOConverters.java@@ -12,6 +12,10 @@ import com.datastrato.graviton.dto.CatalogDTO;import com.datastrato.graviton.dto.MetalakeDTO;import com.datastrato.graviton.dto.requests.CatalogUpdateRequest;import com.datastrato.graviton.dto.requests.MetalakeUpdateRequest;+import com.datastrato.graviton.dto.requests.SchemaUpdateRequest;+import com.datastrato.graviton.dto.requests.TableUpdateRequest;+import com.datastrato.graviton.rel.SchemaChange;+import com.datastrato.graviton.rel.TableChange;class DTOConverters {private DTOConverters() {}@@ -92,4 +96,83 @@ class DTOConverters {"Unknown change type: " + change.getClass().getSimpleName());}}++ static SchemaUpdateRequest toSchemaUpdateRequest(SchemaChange change) {+ if (change instanceof SchemaChange.SetProperty) {+ return new SchemaUpdateRequest.SetSchemaPropertyRequest(+ ((SchemaChange.SetProperty) change).getProperty(),+ ((SchemaChange.SetProperty) change).getValue());++ } else if (change instanceof SchemaChange.RemoveProperty) {+ return new SchemaUpdateRequest.RemoveSchemaPropertyRequest(+ ((SchemaChange.RemoveProperty) change).getProperty());++ } else {+ throw new IllegalArgumentException(+ "Unknown change type: " + change.getClass().getSimpleName());+ }+ }++ static TableUpdateRequest toTableUpdateRequest(TableChange change) {+ if (change instanceof TableChange.RenameTable) {+ return new TableUpdateRequest.RenameTableRequest(+ ((TableChange.RenameTable) change).getNewName());++ } else if (change instanceof TableChange.UpdateComment) {+ return new TableUpdateRequest.UpdateTableCommentRequest(+ ((TableChange.UpdateComment) change).getNewComment());++ } else if (change instanceof TableChange.SetProperty) {+ return new TableUpdateRequest.SetTablePropertyRequest(+ ((TableChange.SetProperty) change).getProperty(),+ ((TableChange.SetProperty) change).getValue());++ } else if (change instanceof TableChange.RemoveProperty) {+ return new TableUpdateRequest.RemoveTablePropertyRequest(+ ((TableChange.RemoveProperty) change).getProperty());++ } else if (change instanceof TableChange.ColumnChange) {+ return toColumnUpdateRequest((TableChange.ColumnChange) change);++ } else {+ throw new IllegalArgumentException(+ "Unknown change type: " + change.getClass().getSimpleName());+ }+ }++ private static TableUpdateRequest toColumnUpdateRequest(TableChange.ColumnChange change) {+ if (change instanceof TableChange.AddColumn) {+ TableChange.AddColumn addColumn = (TableChange.AddColumn) change;+ return new TableUpdateRequest.AddTableColumnRequest(+ addColumn.fieldNames(),+ addColumn.getDataType(),+ addColumn.getComment(),+ addColumn.getPosition());++ } else if (change instanceof TableChange.RenameColumn) {+ TableChange.RenameColumn renameColumn = (TableChange.RenameColumn) change;+ return new TableUpdateRequest.RenameTableColumnRequest(+ renameColumn.fieldNames(), renameColumn.getNewName());++ } else if (change instanceof TableChange.UpdateColumnType) {+ return new TableUpdateRequest.UpdateTableColumnTypeRequest(+ change.fieldNames(), ((TableChange.UpdateColumnType) change).getNewDataType());++ } else if (change instanceof TableChange.UpdateColumnComment) {+ return new TableUpdateRequest.UpdateTableColumnCommentRequest(+ change.fieldNames(), ((TableChange.UpdateColumnComment) change).getNewComment());++ } else if (change instanceof TableChange.UpdateColumnPosition) {+ return new TableUpdateRequest.UpdateTableColumnPositionRequest(+ change.fieldNames(), ((TableChange.UpdateColumnPosition) change).getPosition());++ } else if (change instanceof TableChange.DeleteColumn) {+ return new TableUpdateRequest.DeleteTableColumnRequest(+ change.fieldNames(), ((TableChange.DeleteColumn) change).getIfExists());++ } else {+ throw new IllegalArgumentException(+ "Unknown column change type: " + change.getClass().getSimpleName());+ }+ }}diff --git a/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandler.java b/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandler.javaindex f1e29b5cae..598b72d105 100644--- a/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandler.java+++ b/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandler.java@@ -13,8 +13,6 @@ import java.util.function.Consumer;* The ErrorHandler class is an abstract class specialized for handling ErrorResponse objects.* Subclasses of ErrorHandler must implement the parseResponse method to provide custom parsing* logic for different types of errors.- *- * @param <ErrorResponse> The type of ErrorResponse that this ErrorHandler handles.*/public abstract class ErrorHandler implements Consumer<ErrorResponse> {diff --git a/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandlers.java b/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandlers.javaindex ccf7985e2c..4732d8f54d 100644--- a/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandlers.java+++ b/client-java/src/main/java/com/datastrato/graviton/client/ErrorHandlers.java@@ -10,8 +10,13 @@ import com.datastrato.graviton.exceptions.CatalogAlreadyExistsException;import com.datastrato.graviton.exceptions.MetalakeAlreadyExistsException;import com.datastrato.graviton.exceptions.NoSuchCatalogException;import com.datastrato.graviton.exceptions.NoSuchMetalakeException;+import com.datastrato.graviton.exceptions.NoSuchSchemaException;+import com.datastrato.graviton.exceptions.NoSuchTableException;+import com.datastrato.graviton.exceptions.NonEmptySchemaException;import com.datastrato.graviton.exceptions.NotFoundException;import com.datastrato.graviton.exceptions.RESTException;+import com.datastrato.graviton.exceptions.SchemaAlreadyExistsException;+import com.datastrato.graviton.exceptions.TableAlreadyExistsException;import com.fasterxml.jackson.databind.ObjectMapper;import com.google.common.base.Joiner;import java.util.List;@@ -41,6 +46,24 @@ public class ErrorHandlers {return CatalogErrorHandler.INSTANCE;}+ /**+ * Creates an error handler specific to Schema operations.+ *+ * @return A Consumer representing the Schema error handler.+ */+ public static Consumer<ErrorResponse> schemaErrorHandler() {+ return SchemaErrorHandler.INSTANCE;+ }++ /**+ * Creates an error handler specific to Table operations.+ *+ * @return A Consumer representing the Table error handler.+ */+ public static Consumer<ErrorResponse> tableErrorHandler() {+ return TableErrorHandler.INSTANCE;+ }+/*** Creates a generic error handler for REST requests.*@@ -83,30 +106,99 @@ public class ErrorHandlers {}}+ /** Error handler specific to Table operations. */+ private static class TableErrorHandler extends RestErrorHandler {+ private static final ErrorHandler INSTANCE = new TableErrorHandler();++ @Override+ public void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);++ switch (errorResponse.getCode()) {+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:+ throw new IllegalArgumentException(errorMessage);++ case ErrorConstants.NOT_FOUND_CODE:+ if (errorResponse.getType().equals(NoSuchSchemaException.class.getSimpleName())) {+ throw new NoSuchSchemaException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchTableException.class.getSimpleName())) {+ throw new NoSuchTableException(errorMessage);+ } else {+ throw new NotFoundException(errorMessage);+ }++ case ErrorConstants.ALREADY_EXISTS_CODE:+ throw new TableAlreadyExistsException(errorMessage);++ case ErrorConstants.INTERNAL_ERROR_CODE:+ throw new RuntimeException(errorMessage);+ }++ super.accept(errorResponse);+ }+ }++ /** Error handler specific to Schema operations. */+ private static class SchemaErrorHandler extends RestErrorHandler {+ private static final ErrorHandler INSTANCE = new SchemaErrorHandler();++ @Override+ public void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);++ switch (errorResponse.getCode()) {+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:+ throw new IllegalArgumentException(errorMessage);++ case ErrorConstants.NOT_FOUND_CODE:+ if (errorResponse.getType().equals(NoSuchCatalogException.class.getSimpleName())) {+ throw new NoSuchCatalogException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchSchemaException.class.getSimpleName())) {+ throw new NoSuchSchemaException(errorMessage);+ } else {+ throw new NotFoundException(errorMessage);+ }++ case ErrorConstants.ALREADY_EXISTS_CODE:+ throw new SchemaAlreadyExistsException(errorMessage);++ case ErrorConstants.NON_EMPTY_CODE:+ throw new NonEmptySchemaException(errorMessage);++ case ErrorConstants.INTERNAL_ERROR_CODE:+ throw new RuntimeException(errorMessage);+ }++ super.accept(errorResponse);+ }+ }+/** Error handler specific to Catalog operations. */private static class CatalogErrorHandler extends RestErrorHandler {private static final ErrorHandler INSTANCE = new CatalogErrorHandler();@Overridepublic void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);+switch (errorResponse.getCode()) {case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:- throw new IllegalArgumentException(formatErrorMessage(errorResponse));+ throw new IllegalArgumentException(errorMessage);case ErrorConstants.NOT_FOUND_CODE:if (errorResponse.getType().equals(NoSuchMetalakeException.class.getSimpleName())) {- throw new NoSuchMetalakeException(formatErrorMessage(errorResponse));+ throw new NoSuchMetalakeException(errorMessage);} else if (errorResponse.getType().equals(NoSuchCatalogException.class.getSimpleName())) {- throw new NoSuchCatalogException(formatErrorMessage(errorResponse));+ throw new NoSuchCatalogException(errorMessage);} else {- throw new NotFoundException(formatErrorMessage(errorResponse));+ throw new NotFoundException(errorMessage);}case ErrorConstants.ALREADY_EXISTS_CODE:- throw new CatalogAlreadyExistsException(formatErrorMessage(errorResponse));+ throw new CatalogAlreadyExistsException(errorMessage);case ErrorConstants.INTERNAL_ERROR_CODE:- throw new RuntimeException(formatErrorMessage(errorResponse));+ throw new RuntimeException(errorMessage);}super.accept(errorResponse);@@ -119,18 +211,20 @@ public class ErrorHandlers {@Overridepublic void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);+switch (errorResponse.getCode()) {case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:- throw new IllegalArgumentException(formatErrorMessage(errorResponse));+ throw new IllegalArgumentException(errorMessage);case ErrorConstants.NOT_FOUND_CODE:- throw new NoSuchMetalakeException(formatErrorMessage(errorResponse));+ throw new NoSuchMetalakeException(errorMessage);case ErrorConstants.ALREADY_EXISTS_CODE:- throw new MetalakeAlreadyExistsException(formatErrorMessage(errorResponse));+ throw new MetalakeAlreadyExistsException(errorMessage);case ErrorConstants.INTERNAL_ERROR_CODE:- throw new RuntimeException(formatErrorMessage(errorResponse));+ throw new RuntimeException(errorMessage);}super.accept(errorResponse);diff --git a/client-java/src/main/java/com/datastrato/graviton/client/GravitonMetaLake.java b/client-java/src/main/java/com/datastrato/graviton/client/GravitonMetaLake.javaindex d671a819dc..b4bc57e570 100644--- a/client-java/src/main/java/com/datastrato/graviton/client/GravitonMetaLake.java+++ b/client-java/src/main/java/com/datastrato/graviton/client/GravitonMetaLake.java@@ -30,6 +30,11 @@ import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;+/**+ * Graviton Metalake is the top-level metadata repository for users. It contains a list of catalogs+ * as sub-level metadata collections. With {@link GravitonMetaLake}, users can list, create, load,+ * alter and drop a catalog with specified identifier.+ */public class GravitonMetaLake extends MetalakeDTO implements SupportsCatalogs {private static final Logger LOG = LoggerFactory.getLogger(GravitonMetaLake.class);@@ -46,6 +51,13 @@ public class GravitonMetaLake extends MetalakeDTO implements SupportsCatalogs {this.restClient = restClient;}+ /**+ * List all the catalogs under this metalake with specified namespace.+ *+ * @param namespace The namespace to list the catalogs under it.+ * @return A list of {@link NameIdentifier} of the catalogs under the specified namespace.+ * @throws NoSuchMetalakeException if the metalake with specified namespace does not exist.+ */@Overridepublic NameIdentifier[] listCatalogs(Namespace namespace) throws NoSuchMetalakeException {validateCatalogNamespace(namespace);@@ -61,6 +73,13 @@ public class GravitonMetaLake extends MetalakeDTO implements SupportsCatalogs {return resp.identifiers();}+ /**+ * Load the catalog with specified identifier.+ *+ * @param ident The identifier of the catalog to load.+ * @return The {@link Catalog} with specified identifier.+ * @throws NoSuchCatalogException if the catalog with specified identifier does not exist.+ */@Overridepublic Catalog loadCatalog(NameIdentifier ident) throws NoSuchCatalogException {validateCatalogIdentifier(ident);@@ -76,6 +95,17 @@ public class GravitonMetaLake extends MetalakeDTO implements SupportsCatalogs {return DTOConverters.toCatalog(resp.getCatalog(), restClient);}+ /**+ * Create a new catalog with specified identifier, type, comment and properties.+ *+ * @param ident The identifier of the catalog.+ * @param type The type of the catalog.+ * @param comment The comment of the catalog.+ * @param properties The properties of the catalog.+ * @return The created {@link Catalog}.+ * @throws NoSuchMetalakeException if the metalake with specified namespace does not exist.+ * @throws CatalogAlreadyExistsException if the catalog with specified identifier already exists.+ */@Overridepublic Catalog createCatalog(NameIdentifier ident, Catalog.Type type, String comment, Map<String, String> properties)@@ -97,6 +127,15 @@ public class GravitonMetaLake extends MetalakeDTO implements SupportsCatalogs {return DTOConverters.toCatalog(resp.getCatalog(), restClient);}+ /**+ * Alter the catalog with specified identifier by applying the changes.+ *+ * @param ident the identifier of the catalog.+ * @param changes the changes to apply to the catalog.+ * @return the altered {@link Catalog}.+ * @throws NoSuchCatalogException if the catalog with specified identifier does not exist.+ * @throws IllegalArgumentException if the changes are invalid.+ */@Overridepublic Catalog alterCatalog(NameIdentifier ident, CatalogChange... changes)throws NoSuchCatalogException, IllegalArgumentException {@@ -121,6 +160,12 @@ public class GravitonMetaLake extends MetalakeDTO implements SupportsCatalogs {return DTOConverters.toCatalog(resp.getCatalog(), restClient);}+ /**+ * Drop the catalog with specified identifier.+ *+ * @param ident the identifier of the catalog.+ * @return true if the catalog is dropped successfully, false otherwise.+ */@Overridepublic boolean dropCatalog(NameIdentifier ident) {validateCatalogIdentifier(ident);diff --git a/client-java/src/main/java/com/datastrato/graviton/client/RESTClient.java b/client-java/src/main/java/com/datastrato/graviton/client/RESTClient.javaindex 745b4ec51e..b2903eef42 100644--- a/client-java/src/main/java/com/datastrato/graviton/client/RESTClient.java+++ b/client-java/src/main/java/com/datastrato/graviton/client/RESTClient.java@@ -69,8 +69,7 @@ public interface RESTClient extends Closeable {}/**- * Perform a DELETE request on the specified path with with given information and no query- * parameters.+ * Perform a DELETE request on the specified path with given information and no query parameters.** @param path The path to be requested.* @param responseType The class representing the type of the response.@@ -87,11 +86,23 @@ public interface RESTClient extends Closeable {return delete(path, ImmutableMap.of(), responseType, headers.get(), errorHandler);}- <T extends RESTResponse> T delete(+ /**+ * Perform a DELETE request on the specified path with given information.+ *+ * @param path The path to be requested.+ * @param responseType The class representing the type of the response.+ * @param headers The headers to be included in the request.+ * @param errorHandler The consumer for handling error responses.+ * @param <T> The type of the response.+ * @return The response of the DELETE request.+ */+ default <T extends RESTResponse> T delete(String path,Class<T> responseType,Map<String, String> headers,- Consumer<ErrorResponse> errorHandler);+ Consumer<ErrorResponse> errorHandler) {+ return delete(path, ImmutableMap.of(), responseType, headers, errorHandler);+ }/*** Perform a DELETE request on the specified path with given information.@@ -103,21 +114,13 @@ public interface RESTClient extends Closeable {* @param errorHandler The consumer for handling error responses.* @param <T> The type of the response.* @return The response of the DELETE request.- * @throws UnsupportedOperationException If query parameters are provided, as they are not- * supported for DELETE requests.*/- default <T extends RESTResponse> T delete(+ <T extends RESTResponse> T delete(String path,Map<String, String> queryParams,Class<T> responseType,Map<String, String> headers,- Consumer<ErrorResponse> errorHandler) {- if (null != queryParams && !queryParams.isEmpty()) {- throw new UnsupportedOperationException("Query params are not supported");- }-- return delete(path, responseType, headers, errorHandler);- }+ Consumer<ErrorResponse> errorHandler);/*** Perform a GET request on the specified path with given information and no query parameters.diff --git a/client-java/src/main/java/com/datastrato/graviton/client/RelationalCatalog.java b/client-java/src/main/java/com/datastrato/graviton/client/RelationalCatalog.javaindex 250424c835..46cc9da36b 100644--- a/client-java/src/main/java/com/datastrato/graviton/client/RelationalCatalog.java+++ b/client-java/src/main/java/com/datastrato/graviton/client/RelationalCatalog.java@@ -8,6 +8,17 @@ import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;import com.datastrato.graviton.dto.AuditDTO;import com.datastrato.graviton.dto.CatalogDTO;+import com.datastrato.graviton.dto.rel.ColumnDTO;+import com.datastrato.graviton.dto.requests.SchemaCreateRequest;+import com.datastrato.graviton.dto.requests.SchemaUpdateRequest;+import com.datastrato.graviton.dto.requests.SchemaUpdatesRequest;+import com.datastrato.graviton.dto.requests.TableCreateRequest;+import com.datastrato.graviton.dto.requests.TableUpdateRequest;+import com.datastrato.graviton.dto.requests.TableUpdatesRequest;+import com.datastrato.graviton.dto.responses.DropResponse;+import com.datastrato.graviton.dto.responses.EntityListResponse;+import com.datastrato.graviton.dto.responses.SchemaResponse;+import com.datastrato.graviton.dto.responses.TableResponse;import com.datastrato.graviton.exceptions.NoSuchCatalogException;import com.datastrato.graviton.exceptions.NoSuchSchemaException;import com.datastrato.graviton.exceptions.NoSuchTableException;@@ -21,11 +32,26 @@ import com.datastrato.graviton.rel.SupportsSchemas;import com.datastrato.graviton.rel.Table;import com.datastrato.graviton.rel.TableCatalog;import com.datastrato.graviton.rel.TableChange;+import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;import java.util.Map;+import java.util.stream.Collectors;+import org.apache.commons.lang3.StringUtils;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;+/**+ * Relational catalog is a catalog implementation that supports relational database like metadata+ * operations, for example, schemas and tables list, creation, update and deletion. A Relational+ * catalog is under the metalake.+ */public class RelationalCatalog extends CatalogDTO implements TableCatalog, SupportsSchemas {+ private static final Logger LOG = LoggerFactory.getLogger(RelationalCatalog.class);+private final RESTClient restClient;RelationalCatalog(@@ -49,59 +75,321 @@ public class RelationalCatalog extends CatalogDTO implements TableCatalog, Supporeturn this;}+ /**+ * List all the tables under the given Schema namespace.+ *+ * @param namespace The namespace to list the tables under it.+ * @return A list of {@link NameIdentifier} of the tables under the given namespace.+ * @throws NoSuchSchemaException if the schema with specified namespace does not exist.+ */@Override- public NameIdentifier[] listTables(Namespace namespace) throws NoSuchCatalogException {- throw new UnsupportedOperationException("Not implemented yet");+ public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {+ validateTableNamespace(namespace);++ EntityListResponse resp =+ restClient.get(+ formatTableRequestPath(namespace),+ EntityListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tableErrorHandler());+ resp.validate();++ return resp.identifiers();}+ /**+ * Load the table with specified identifier.+ *+ * @param ident The identifier of the table to load.+ * @return The {@link Table} with specified identifier.+ * @throws NoSuchTableException if the table with specified identifier does not exist.+ */@Overridepublic Table loadTable(NameIdentifier ident) throws NoSuchTableException {- throw new UnsupportedOperationException("Not implemented yet");+ validateTableIdentifier(ident);++ TableResponse resp =+ restClient.get(+ formatTableRequestPath(ident.namespace()) + "/" + ident.name(),+ TableResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tableErrorHandler());+ resp.validate();++ return resp.getTable();}+ /**+ * Create a new table with specified identifier, columns, comment and properties.+ *+ * @param ident The identifier of the table.+ * @param columns The columns of the table.+ * @param comment The comment of the table.+ * @param properties The properties of the table.+ * @return The created {@link Table}.+ * @throws NoSuchSchemaException if the schema with specified namespace does not exist.+ * @throws TableAlreadyExistsException if the table with specified identifier already exists.+ */@Overridepublic Table createTable(NameIdentifier ident, Column[] columns, String comment, Map<String, String> properties)throws NoSuchSchemaException, TableAlreadyExistsException {- throw new UnsupportedOperationException("Not implemented yet");+ validateTableIdentifier(ident);++ TableCreateRequest req =+ new TableCreateRequest(ident.name(), comment, (ColumnDTO[]) columns, properties);+ req.validate();++ TableResponse resp =+ restClient.post(+ formatTableRequestPath(ident.namespace()),+ req,+ TableResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tableErrorHandler());+ resp.validate();++ return resp.getTable();}+ /**+ * Alter the table with specified identifier by applying the changes.+ *+ * @param ident The identifier of the table.+ * @param changes Table changes to apply to the table.+ * @return The altered {@link Table}.+ * @throws NoSuchTableException if the table with specified identifier does not exist.+ * @throws IllegalArgumentException if the changes are invalid.+ */@Overridepublic Table alterTable(NameIdentifier ident, TableChange... changes)throws NoSuchTableException, IllegalArgumentException {- throw new UnsupportedOperationException("Not implemented yet");+ validateTableIdentifier(ident);++ List<TableUpdateRequest> reqs =+ Arrays.stream(changes)+ .map(DTOConverters::toTableUpdateRequest)+ .collect(Collectors.toList());+ TableUpdatesRequest updatesRequest = new TableUpdatesRequest(reqs);+ updatesRequest.validate();++ TableResponse resp =+ restClient.put(+ formatTableRequestPath(ident.namespace()) + "/" + ident.name(),+ updatesRequest,+ TableResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tableErrorHandler());+ resp.validate();++ return resp.getTable();}+ /**+ * Drop the table with specified identifier.+ *+ * @param ident The identifier of the table.+ * @return true if the table is dropped successfully, false otherwise.+ */@Overridepublic boolean dropTable(NameIdentifier ident) {- throw new UnsupportedOperationException("Not implemented yet");+ validateTableIdentifier(ident);++ try {+ DropResponse resp =+ restClient.delete(+ formatTableRequestPath(ident.namespace()) + "/" + ident.name(),+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.tableErrorHandler());+ resp.validate();+ return resp.dropped();++ } catch (Exception e) {+ LOG.warn("Failed to drop table {}", ident, e);+ return false;+ }}+ /**+ * List all the schemas under the given catalog namespace.+ *+ * @param namespace The namespace of the catalog.+ * @return A list of {@link NameIdentifier} of the schemas under the given catalog namespace.+ * @throws NoSuchCatalogException if the catalog with specified namespace does not exist.+ */@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {- throw new UnsupportedOperationException("Not implemented yet");+ validateSchemaNamespace(namespace);++ EntityListResponse resp =+ restClient.get(+ formatSchemaRequestPath(namespace),+ EntityListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.schemaErrorHandler());+ resp.validate();++ return resp.identifiers();}+ /**+ * Create a new schema with specified identifier, comment and metadata.+ *+ * @param ident The name identifier of the schema.+ * @param comment The comment of the schema.+ * @param metadata The metadata of the schema.+ * @return The created {@link Schema}.+ * @throws NoSuchCatalogException if the catalog with specified namespace does not exist.+ * @throws SchemaAlreadyExistsException if the schema with specified identifier already exists.+ */@Overridepublic Schema createSchema(NameIdentifier ident, String comment, Map<String, String> metadata)throws NoSuchCatalogException, SchemaAlreadyExistsException {- throw new UnsupportedOperationException("Not implemented yet");+ validateSchemaIdentifier(ident);++ SchemaCreateRequest req = new SchemaCreateRequest(ident.name(), comment, metadata);+ req.validate();++ SchemaResponse resp =+ restClient.post(+ formatSchemaRequestPath(ident.namespace()),+ req,+ SchemaResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.schemaErrorHandler());+ resp.validate();++ return resp.getSchema();}+ /**+ * Load the schema with specified identifier.+ *+ * @param ident The name identifier of the schema.+ * @return The {@link Schema} with specified identifier.+ * @throws NoSuchSchemaException if the schema with specified identifier does not exist.+ */@Overridepublic Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {- throw new UnsupportedOperationException("Not implemented yet");+ validateSchemaIdentifier(ident);++ SchemaResponse resp =+ restClient.get(+ formatSchemaRequestPath(ident.namespace()) + "/" + ident.name(),+ SchemaResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.schemaErrorHandler());+ resp.validate();++ return resp.getSchema();}+ /**+ * Alter the schema with specified identifier by applying the changes.+ *+ * @param ident The name identifier of the schema.+ * @param changes The metadata changes to apply.+ * @return The altered {@link Schema}.+ * @throws NoSuchSchemaException if the schema with specified identifier does not exist.+ */@Overridepublic Schema alterSchema(NameIdentifier ident, SchemaChange... changes)throws NoSuchSchemaException {- throw new UnsupportedOperationException("Not implemented yet");+ validateSchemaIdentifier(ident);++ List<SchemaUpdateRequest> reqs =+ Arrays.stream(changes)+ .map(DTOConverters::toSchemaUpdateRequest)+ .collect(Collectors.toList());+ SchemaUpdatesRequest updatesRequest = new SchemaUpdatesRequest(reqs);+ updatesRequest.validate();++ SchemaResponse resp =+ restClient.put(+ formatSchemaRequestPath(ident.namespace()) + "/" + ident.name(),+ updatesRequest,+ SchemaResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.schemaErrorHandler());+ resp.validate();++ return resp.getSchema();}+ /**+ * Drop the schema with specified identifier.+ *+ * @param ident The name identifier of the schema.+ * @param cascade Whether to drop all the tables under the schema.+ * @return true if the schema is dropped successfully, false otherwise.+ * @throws NonEmptySchemaException if the schema is not empty and cascade is false.+ */@Overridepublic boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {- throw new UnsupportedOperationException("Not implemented yet");+ validateSchemaIdentifier(ident);++ try {+ DropResponse resp =+ restClient.delete(+ formatSchemaRequestPath(ident.namespace()) + "/" + ident.name(),+ Collections.singletonMap("cascade", String.valueOf(cascade)),+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.schemaErrorHandler());+ resp.validate();+ return resp.dropped();++ } catch (NonEmptySchemaException e) {+ throw e;+ } catch (Exception e) {+ LOG.warn("Failed to drop schema {}", ident, e);+ return false;+ }+ }++ private static void validateSchemaNamespace(Namespace ns) {+ Preconditions.checkArgument(+ ns != null && ns.length() == 2,+ "Schema namespace must not be null and have exactly two level");+ }++ private static void validateSchemaIdentifier(NameIdentifier ident) {+ validateSchemaNamespace(ident.namespace());+ Preconditions.checkArgument(+ StringUtils.isNotBlank(ident.name()), "Schema name must not be null or empty");+ }++ private static void validateTableNamespace(Namespace ns) {+ validateSchemaIdentifier(NameIdentifier.of(ns.levels()));+ }++ private static void validateTableIdentifier(NameIdentifier ident) {+ validateTableNamespace(ident.namespace());+ Preconditions.checkArgument(+ StringUtils.isNotBlank(ident.name()), "Table name must not be null or empty");+ }++ @VisibleForTesting+ static String formatTableRequestPath(Namespace ns) {+ Namespace schemaNs = Namespace.of(ns.level(0), ns.level(1));+ return new StringBuilder()+ .append(formatSchemaRequestPath(schemaNs))+ .append("/")+ .append(ns.level(2))+ .append("/tables")+ .toString();+ }++ @VisibleForTesting+ static String formatSchemaRequestPath(Namespace ns) {+ return new StringBuilder()+ .append("api/metalakes/")+ .append(ns.level(0))+ .append("/catalogs/")+ .append(ns.level(1))+ .append("/schemas")+ .toString();}static class Builder extends CatalogDTO.Builder<Builder> {diff --git a/client-java/src/test/java/com/datastrato/graviton/client/TestBase.java b/client-java/src/test/java/com/datastrato/graviton/client/TestBase.javaindex c13e65833a..a8680e2cde 100644--- a/client-java/src/test/java/com/datastrato/graviton/client/TestBase.java+++ b/client-java/src/test/java/com/datastrato/graviton/client/TestBase.java@@ -7,6 +7,10 @@ package com.datastrato.graviton.client;import com.datastrato.graviton.json.JsonUtils;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;+import java.util.Collections;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;import org.apache.hc.core5.http.Method;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.BeforeAll;@@ -14,6 +18,7 @@ import org.mockserver.integration.ClientAndServer;import org.mockserver.matchers.Times;import org.mockserver.model.HttpRequest;import org.mockserver.model.HttpResponse;+import org.mockserver.model.Parameter;public abstract class TestBase {@@ -37,9 +42,20 @@ public abstract class TestBase {}protected static <T, R> void buildMockResource(- Method method, String path, T reqBody, R respBody, int statusCode)+ Method method,+ String path,+ Map<String, String> queryParams,+ T reqBody,+ R respBody,+ int statusCode)throws JsonProcessingException {- HttpRequest mockRequest = HttpRequest.request(path).withMethod(method.name());+ List<Parameter> parameters =+ queryParams.entrySet().stream()+ .map(kv -> new Parameter(kv.getKey(), kv.getValue()))+ .collect(Collectors.toList());++ HttpRequest mockRequest =+ HttpRequest.request(path).withMethod(method.name()).withQueryStringParameters(parameters);if (reqBody != null) {String reqJson = MAPPER.writeValueAsString(reqBody);mockRequest = mockRequest.withBody(reqJson);@@ -55,4 +71,10 @@ public abstract class TestBase {// responses for the same request and path.mockServer.when(mockRequest, Times.exactly(1)).respond(mockResponse);}++ protected static <T, R> void buildMockResource(+ Method method, String path, T reqBody, R respBody, int statusCode)+ throws JsonProcessingException {+ buildMockResource(method, path, Collections.emptyMap(), reqBody, respBody, statusCode);+ }}diff --git a/client-java/src/test/java/com/datastrato/graviton/client/TestGravitonMetalake.java b/client-java/src/test/java/com/datastrato/graviton/client/TestGravitonMetalake.javaindex 623a792198..d13bc4e9d6 100644--- a/client-java/src/test/java/com/datastrato/graviton/client/TestGravitonMetalake.java+++ b/client-java/src/test/java/com/datastrato/graviton/client/TestGravitonMetalake.java@@ -46,43 +46,13 @@ public class TestGravitonMetalake extends TestBase {public static void setUp() throws Exception {TestBase.setUp();- MetalakeDTO mockMetalake =- new MetalakeDTO.Builder()- .withName(metalakeName)- .withComment("comment")- .withAudit(- new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())- .build();- MetalakeCreateRequest req =- new MetalakeCreateRequest(metalakeName, "comment", Collections.emptyMap());- MetalakeResponse resp = new MetalakeResponse(mockMetalake);- buildMockResource(Method.POST, "/api/metalakes", req, resp, HttpStatus.SC_OK);-- metalake =- client.createMetalake(- NameIdentifier.parse(metalakeName), "comment", Collections.emptyMap());+ metalake = createMetalake(client, metalakeName);}@Testpublic void testListCatalogs() throws JsonProcessingException {String path = "/api/metalakes/" + metalakeName + "/catalogs";- CatalogDTO mockCatalog =- new CatalogDTO.Builder()- .withName("mock")- .withComment("comment")- .withType(Catalog.Type.RELATIONAL)- .withAudit(- new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())- .build();- CatalogDTO mockCatalog2 =- new CatalogDTO.Builder()- .withName("mock2")- .withComment("comment")- .withType(Catalog.Type.RELATIONAL)- .withAudit(- new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())- .build();NameIdentifier ident1 = NameIdentifier.of(metalakeName, "mock");NameIdentifier ident2 = NameIdentifier.of(metalakeName, "mock2");@@ -360,4 +330,22 @@ public class TestGravitonMetalake extends TestBase {boolean dropped1 = metalake.dropCatalog(NameIdentifier.of(metalakeName, catalogName));Assertions.assertFalse(dropped1);}++ static GravitonMetaLake createMetalake(GravitonClient client, String metalakeName)+ throws JsonProcessingException {+ MetalakeDTO mockMetalake =+ new MetalakeDTO.Builder()+ .withName(metalakeName)+ .withComment("comment")+ .withAudit(+ new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ MetalakeCreateRequest req =+ new MetalakeCreateRequest(metalakeName, "comment", Collections.emptyMap());+ MetalakeResponse resp = new MetalakeResponse(mockMetalake);+ buildMockResource(Method.POST, "/api/metalakes", req, resp, HttpStatus.SC_OK);++ return client.createMetalake(+ NameIdentifier.parse(metalakeName), "comment", Collections.emptyMap());+ }}diff --git a/client-java/src/test/java/com/datastrato/graviton/client/TestRelationalCatalog.java b/client-java/src/test/java/com/datastrato/graviton/client/TestRelationalCatalog.javanew file mode 100644index 0000000000..3976f0eb45--- /dev/null+++ b/client-java/src/test/java/com/datastrato/graviton/client/TestRelationalCatalog.java@@ -0,0 +1,641 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.graviton.client;++import static org.apache.hc.core5.http.HttpStatus.SC_BAD_REQUEST;+import static org.apache.hc.core5.http.HttpStatus.SC_CONFLICT;+import static org.apache.hc.core5.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;+import static org.apache.hc.core5.http.HttpStatus.SC_NOT_FOUND;+import static org.apache.hc.core5.http.HttpStatus.SC_OK;++import com.datastrato.graviton.Catalog;+import com.datastrato.graviton.NameIdentifier;+import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.dto.AuditDTO;+import com.datastrato.graviton.dto.CatalogDTO;+import com.datastrato.graviton.dto.rel.ColumnDTO;+import com.datastrato.graviton.dto.rel.SchemaDTO;+import com.datastrato.graviton.dto.rel.TableDTO;+import com.datastrato.graviton.dto.requests.CatalogCreateRequest;+import com.datastrato.graviton.dto.requests.SchemaCreateRequest;+import com.datastrato.graviton.dto.requests.SchemaUpdateRequest;+import com.datastrato.graviton.dto.requests.SchemaUpdatesRequest;+import com.datastrato.graviton.dto.requests.TableCreateRequest;+import com.datastrato.graviton.dto.requests.TableUpdateRequest;+import com.datastrato.graviton.dto.requests.TableUpdatesRequest;+import com.datastrato.graviton.dto.responses.CatalogResponse;+import com.datastrato.graviton.dto.responses.DropResponse;+import com.datastrato.graviton.dto.responses.EntityListResponse;+import com.datastrato.graviton.dto.responses.ErrorResponse;+import com.datastrato.graviton.dto.responses.SchemaResponse;+import com.datastrato.graviton.dto.responses.TableResponse;+import com.datastrato.graviton.exceptions.NoSuchCatalogException;+import com.datastrato.graviton.exceptions.NoSuchSchemaException;+import com.datastrato.graviton.exceptions.NoSuchTableException;+import com.datastrato.graviton.exceptions.NonEmptySchemaException;+import com.datastrato.graviton.exceptions.RESTException;+import com.datastrato.graviton.exceptions.SchemaAlreadyExistsException;+import com.datastrato.graviton.exceptions.TableAlreadyExistsException;+import com.datastrato.graviton.rel.Schema;+import com.datastrato.graviton.rel.Table;+import com.datastrato.graviton.rel.TableChange;+import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.collect.ImmutableList;+import com.google.common.collect.ImmutableMap;+import io.substrait.type.Type;+import io.substrait.type.TypeCreator;+import java.time.Instant;+import java.util.Collections;+import java.util.Map;+import org.apache.hc.core5.http.Method;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++public class TestRelationalCatalog extends TestBase {++ private static Catalog catalog;++ private static GravitonMetaLake metalake;++ private static final String metalakeName = "testMetalake";++ private static final String catalogName = "testCatalog";++ @BeforeAll+ public static void setUp() throws Exception {+ TestBase.setUp();++ metalake = TestGravitonMetalake.createMetalake(client, metalakeName);++ CatalogDTO mockCatalog =+ new CatalogDTO.Builder()+ .withName(catalogName)+ .withType(CatalogDTO.Type.RELATIONAL)+ .withComment("comment")+ .withProperties(ImmutableMap.of("k1", "k2"))+ .withAudit(+ new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();++ CatalogCreateRequest catalogCreateRequest =+ new CatalogCreateRequest(+ catalogName, CatalogDTO.Type.RELATIONAL, "comment", ImmutableMap.of("k1", "k2"));+ CatalogResponse catalogResponse = new CatalogResponse(mockCatalog);+ buildMockResource(+ Method.POST,+ "/api/metalakes/" + metalakeName + "/catalogs",+ catalogCreateRequest,+ catalogResponse,+ SC_OK);++ catalog =+ metalake.createCatalog(+ NameIdentifier.of(metalakeName, catalogName),+ CatalogDTO.Type.RELATIONAL,+ "comment",+ ImmutableMap.of("k1", "k2"));+ }++ @Test+ public void testListSchemas() throws JsonProcessingException {+ Namespace schemaNs = Namespace.of(metalakeName, catalogName);+ NameIdentifier schema1 = NameIdentifier.of(schemaNs, "schema1");+ NameIdentifier schema2 = NameIdentifier.of(schemaNs, "schema2");+ String schemaPath = withSlash(RelationalCatalog.formatSchemaRequestPath(schemaNs));++ EntityListResponse resp = new EntityListResponse(new NameIdentifier[] {schema1, schema2});+ buildMockResource(Method.GET, schemaPath, null, resp, SC_OK);+ NameIdentifier[] schemas = catalog.asSchemas().listSchemas(schemaNs);++ Assertions.assertEquals(2, schemas.length);+ Assertions.assertEquals(schema1, schemas[0]);+ Assertions.assertEquals(schema2, schemas[1]);++ // Test return empty schema list+ EntityListResponse emptyResp = new EntityListResponse(new NameIdentifier[] {});+ buildMockResource(Method.GET, schemaPath, null, emptyResp, SC_OK);+ NameIdentifier[] emptySchemas = catalog.asSchemas().listSchemas(schemaNs);+ Assertions.assertEquals(0, emptySchemas.length);++ // Test throw NoSuchCatalogException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchCatalogException.class.getSimpleName(), "catalog not found");+ buildMockResource(Method.GET, schemaPath, null, errorResp, SC_NOT_FOUND);+ Throwable ex =+ Assertions.assertThrows(+ NoSuchCatalogException.class, () -> catalog.asSchemas().listSchemas(schemaNs));+ Assertions.assertTrue(ex.getMessage().contains("catalog not found"));++ // Test throw RuntimeException+ ErrorResponse errorResp1 = ErrorResponse.internalError("internal error");+ buildMockResource(Method.GET, schemaPath, null, errorResp1, SC_INTERNAL_SERVER_ERROR);+ Throwable ex1 =+ Assertions.assertThrows(+ RuntimeException.class, () -> catalog.asSchemas().listSchemas(schemaNs));+ Assertions.assertTrue(ex1.getMessage().contains("internal error"));++ // Test throw unparsed system error+ buildMockResource(Method.GET, schemaPath, null, "unparsed error", SC_BAD_REQUEST);+ Throwable ex2 =+ Assertions.assertThrows(+ RESTException.class, () -> catalog.asSchemas().listSchemas(schemaNs));+ Assertions.assertTrue(ex2.getMessage().contains("unparsed error"));+ }++ @Test+ public void testCreateSchema() throws JsonProcessingException {+ NameIdentifier schemaId = NameIdentifier.of(metalakeName, catalogName, "schema1");+ String schemaPath = withSlash(RelationalCatalog.formatSchemaRequestPath(schemaId.namespace()));+ SchemaDTO schema = createMockSchema("schema1", "comment", Collections.emptyMap());++ SchemaCreateRequest req = new SchemaCreateRequest("schema1", "comment", Collections.emptyMap());+ SchemaResponse resp = new SchemaResponse(schema);+ buildMockResource(Method.POST, schemaPath, req, resp, SC_OK);++ Schema createdSchema =+ catalog.asSchemas().createSchema(schemaId, "comment", Collections.emptyMap());+ Assertions.assertEquals("schema1", createdSchema.name());+ Assertions.assertEquals("comment", createdSchema.comment());+ Assertions.assertEquals(Collections.emptyMap(), createdSchema.properties());++ // Test throw NoSuchCatalogException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchCatalogException.class.getSimpleName(), "catalog not found");+ buildMockResource(Method.POST, schemaPath, req, errorResp, SC_NOT_FOUND);++ Throwable ex =+ Assertions.assertThrows(+ NoSuchCatalogException.class,+ () -> catalog.asSchemas().createSchema(schemaId, "comment", Collections.emptyMap()));+ Assertions.assertTrue(ex.getMessage().contains("catalog not found"));++ // Test throw SchemaAlreadyExistsException+ ErrorResponse errorResp1 =+ ErrorResponse.alreadyExists(+ SchemaAlreadyExistsException.class.getSimpleName(), "schema already exists");+ buildMockResource(Method.POST, schemaPath, req, errorResp1, SC_CONFLICT);++ Throwable ex1 =+ Assertions.assertThrows(+ SchemaAlreadyExistsException.class,+ () -> catalog.asSchemas().createSchema(schemaId, "comment", Collections.emptyMap()));+ Assertions.assertTrue(ex1.getMessage().contains("schema already exists"));+ }++ @Test+ public void testLoadSchema() throws JsonProcessingException {+ NameIdentifier schemaId = NameIdentifier.of(metalakeName, catalogName, "schema1");+ String schemaPath =+ withSlash(+ RelationalCatalog.formatSchemaRequestPath(schemaId.namespace())+ + "/"+ + schemaId.name());+ SchemaDTO schema = createMockSchema("schema1", "comment", Collections.emptyMap());++ SchemaResponse resp = new SchemaResponse(schema);+ buildMockResource(Method.GET, schemaPath, null, resp, SC_OK);++ Schema loadedSchema = catalog.asSchemas().loadSchema(schemaId);+ Assertions.assertEquals("schema1", loadedSchema.name());+ Assertions.assertEquals("comment", loadedSchema.comment());+ Assertions.assertEquals(Collections.emptyMap(), loadedSchema.properties());++ // Test throw NoSuchSchemaException+ ErrorResponse errorResp1 =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.GET, schemaPath, null, errorResp1, SC_NOT_FOUND);++ Throwable ex1 =+ Assertions.assertThrows(+ NoSuchSchemaException.class, () -> catalog.asSchemas().loadSchema(schemaId));+ Assertions.assertTrue(ex1.getMessage().contains("schema not found"));+ }++ @Test+ public void testSetSchemaProperty() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(metalakeName, catalogName, "schema1");+ SchemaUpdateRequest.SetSchemaPropertyRequest req =+ new SchemaUpdateRequest.SetSchemaPropertyRequest("k1", "v1");+ SchemaDTO expectedSchema = createMockSchema("schema1", "comment", ImmutableMap.of("k1", "v1"));++ testAlterSchema(ident, req, expectedSchema);+ }++ @Test+ public void testRemoveSchemaProperty() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(metalakeName, catalogName, "schema1");+ SchemaUpdateRequest.RemoveSchemaPropertyRequest req =+ new SchemaUpdateRequest.RemoveSchemaPropertyRequest("k1");+ SchemaDTO expectedSchema = createMockSchema("schema1", "comment", Collections.emptyMap());++ testAlterSchema(ident, req, expectedSchema);+ }++ @Test+ public void testDropSchema() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(metalakeName, catalogName, "schema1");+ String schemaPath =+ withSlash(+ RelationalCatalog.formatSchemaRequestPath(ident.namespace()) + "/" + ident.name());+ DropResponse resp = new DropResponse(true);+ buildMockResource(Method.DELETE, schemaPath, null, resp, SC_OK);++ Assertions.assertTrue(catalog.asSchemas().dropSchema(ident, false));++ // Test with cascade to ture+ DropResponse resp1 = new DropResponse(true);+ buildMockResource(+ Method.DELETE, schemaPath, ImmutableMap.of("cascade", "true"), null, resp1, SC_OK);++ Assertions.assertTrue(catalog.asSchemas().dropSchema(ident, true));++ // Test throw NonEmptySchemaException+ ErrorResponse errorResp =+ ErrorResponse.nonEmpty(+ NonEmptySchemaException.class.getSimpleName(), "schema is not empty");+ buildMockResource(Method.DELETE, schemaPath, null, errorResp, SC_CONFLICT);++ Throwable ex =+ Assertions.assertThrows(+ NonEmptySchemaException.class, () -> catalog.asSchemas().dropSchema(ident, true));++ Assertions.assertTrue(ex.getMessage().contains("schema is not empty"));+ }++ @Test+ public void testListTables() throws JsonProcessingException {+ NameIdentifier table1 = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ NameIdentifier table2 = NameIdentifier.of(metalakeName, catalogName, "schema1", "table2");+ String tablePath = withSlash(RelationalCatalog.formatTableRequestPath(table1.namespace()));++ EntityListResponse resp = new EntityListResponse(new NameIdentifier[] {table1, table2});+ buildMockResource(Method.GET, tablePath, null, resp, SC_OK);+ NameIdentifier[] tables = catalog.asTableCatalog().listTables(table1.namespace());++ Assertions.assertEquals(2, tables.length);+ Assertions.assertEquals(table1, tables[0]);+ Assertions.assertEquals(table2, tables[1]);++ // Test throw NoSuchSchemaException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.GET, tablePath, null, errorResp, SC_NOT_FOUND);++ Throwable ex =+ Assertions.assertThrows(+ NoSuchSchemaException.class,+ () -> catalog.asTableCatalog().listTables(table1.namespace()));+ Assertions.assertTrue(ex.getMessage().contains("schema not found"));++ // Test throw RuntimeException+ ErrorResponse errorResp1 = ErrorResponse.internalError("runtime exception");+ buildMockResource(Method.GET, tablePath, null, errorResp1, SC_INTERNAL_SERVER_ERROR);++ Throwable ex1 =+ Assertions.assertThrows(+ RuntimeException.class, () -> catalog.asTableCatalog().listTables(table1.namespace()));+ Assertions.assertTrue(ex1.getMessage().contains("runtime exception"));++ // Test throw unparsed system error+ buildMockResource(Method.GET, tablePath, null, "unparsed error", SC_CONFLICT);+ Throwable ex2 =+ Assertions.assertThrows(+ RuntimeException.class, () -> catalog.asTableCatalog().listTables(table1.namespace()));+ Assertions.assertTrue(ex2.getMessage().contains("unparsed error"));+ }++ @Test+ public void testCreateTable() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ String tablePath = withSlash(RelationalCatalog.formatTableRequestPath(tableId.namespace()));++ ColumnDTO[] columns =+ new ColumnDTO[] {+ createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1"),+ createMockColumn("col2", TypeCreator.NULLABLE.STRING, "comment2")+ };+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());++ TableCreateRequest req =+ new TableCreateRequest(tableId.name(), "comment", columns, Collections.emptyMap());+ TableResponse resp = new TableResponse(expectedTable);+ buildMockResource(Method.POST, tablePath, req, resp, SC_OK);++ Table table =+ catalog.asTableCatalog().createTable(tableId, columns, "comment", Collections.emptyMap());+ Assertions.assertEquals(expectedTable.name(), table.name());+ Assertions.assertEquals(expectedTable.comment(), table.comment());+ Assertions.assertEquals(expectedTable.properties(), table.properties());++ Assertions.assertEquals(expectedTable.columns().length, table.columns().length);+ Assertions.assertEquals(expectedTable.columns()[0].name(), table.columns()[0].name());+ Assertions.assertEquals(expectedTable.columns()[0].dataType(), table.columns()[0].dataType());+ Assertions.assertEquals(expectedTable.columns()[0].comment(), table.columns()[0].comment());++ Assertions.assertEquals(expectedTable.columns()[1].name(), table.columns()[1].name());+ Assertions.assertEquals(expectedTable.columns()[1].dataType(), table.columns()[1].dataType());+ Assertions.assertEquals(expectedTable.columns()[1].comment(), table.columns()[1].comment());++ // Test throw NoSuchSchemaException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.POST, tablePath, req, errorResp, SC_NOT_FOUND);++ Throwable ex =+ Assertions.assertThrows(+ NoSuchSchemaException.class,+ () ->+ catalog+ .asTableCatalog()+ .createTable(tableId, columns, "comment", Collections.emptyMap()));+ Assertions.assertTrue(ex.getMessage().contains("schema not found"));++ // Test throw TableAlreadyExistsException+ ErrorResponse errorResp1 =+ ErrorResponse.alreadyExists(+ TableAlreadyExistsException.class.getSimpleName(), "table already exists");+ buildMockResource(Method.POST, tablePath, req, errorResp1, SC_CONFLICT);++ Throwable ex1 =+ Assertions.assertThrows(+ TableAlreadyExistsException.class,+ () ->+ catalog+ .asTableCatalog()+ .createTable(tableId, columns, "comment", Collections.emptyMap()));+ Assertions.assertTrue(ex1.getMessage().contains("table already exists"));+ }++ @Test+ public void testLoadTable() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ String tablePath =+ withSlash(+ RelationalCatalog.formatTableRequestPath(tableId.namespace()) + "/" + tableId.name());+ ColumnDTO[] columns =+ new ColumnDTO[] {+ createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1"),+ createMockColumn("col2", TypeCreator.NULLABLE.STRING, "comment2")+ };+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());++ TableResponse resp = new TableResponse(expectedTable);+ buildMockResource(Method.GET, tablePath, null, resp, SC_OK);++ Table table = catalog.asTableCatalog().loadTable(tableId);+ Assertions.assertEquals(expectedTable.name(), table.name());+ Assertions.assertEquals(expectedTable.comment(), table.comment());+ Assertions.assertEquals(expectedTable.properties(), table.properties());++ Assertions.assertEquals(expectedTable.columns().length, table.columns().length);+ Assertions.assertEquals(expectedTable.columns()[0].name(), table.columns()[0].name());+ Assertions.assertEquals(expectedTable.columns()[0].dataType(), table.columns()[0].dataType());+ Assertions.assertEquals(expectedTable.columns()[0].comment(), table.columns()[0].comment());++ Assertions.assertEquals(expectedTable.columns()[1].name(), table.columns()[1].name());+ Assertions.assertEquals(expectedTable.columns()[1].dataType(), table.columns()[1].dataType());+ Assertions.assertEquals(expectedTable.columns()[1].comment(), table.columns()[1].comment());++ // Test throw NoSuchTableException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchTableException.class.getSimpleName(), "table not found");+ buildMockResource(Method.GET, tablePath, null, errorResp, SC_NOT_FOUND);++ Throwable ex =+ Assertions.assertThrows(+ NoSuchTableException.class, () -> catalog.asTableCatalog().loadTable(tableId));+ Assertions.assertTrue(ex.getMessage().contains("table not found"));+ }++ @Test+ public void testRenameTable() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1")};+ TableDTO expectedTable = createMockTable("table2", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.RenameTableRequest req =+ new TableUpdateRequest.RenameTableRequest(expectedTable.name());++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testUpdateTableComment() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1")};+ TableDTO expectedTable = createMockTable("table1", columns, "comment2", Collections.emptyMap());+ TableUpdateRequest.UpdateTableCommentRequest req =+ new TableUpdateRequest.UpdateTableCommentRequest(expectedTable.comment());++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testSetTableProperty() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1")};+ Map<String, String> properties = ImmutableMap.of("k1", "v1");+ TableDTO expectedTable = createMockTable("table1", columns, "comment", properties);+ TableUpdateRequest.SetTablePropertyRequest req =+ new TableUpdateRequest.SetTablePropertyRequest("k1", "v1");++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testRemoveTableProperty() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1")};+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.RemoveTablePropertyRequest req =+ new TableUpdateRequest.RemoveTablePropertyRequest("k1");++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testAddTableColumn() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {+ createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1"),+ createMockColumn("col2", TypeCreator.NULLABLE.STRING, "comment2")+ };+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.AddTableColumnRequest req =+ new TableUpdateRequest.AddTableColumnRequest(+ new String[] {"col2"},+ TypeCreator.NULLABLE.STRING,+ "comment2",+ TableChange.ColumnPosition.after("col1"));++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testRenameTableColumn() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {+ createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1"),+ createMockColumn("col3", TypeCreator.NULLABLE.STRING, "comment2")+ };+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.RenameTableColumnRequest req =+ new TableUpdateRequest.RenameTableColumnRequest(new String[] {"col2"}, "col3");++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testUpdateTableColumnComment() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment2")};+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.UpdateTableColumnCommentRequest req =+ new TableUpdateRequest.UpdateTableColumnCommentRequest(new String[] {"col1"}, "comment2");++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testUpdateTableColumnDataType() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col1", TypeCreator.NULLABLE.STRING, "comment1")};+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.UpdateTableColumnTypeRequest req =+ new TableUpdateRequest.UpdateTableColumnTypeRequest(+ new String[] {"col1"}, TypeCreator.NULLABLE.STRING);++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testUpdateTableColumnPosition() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {+ createMockColumn("col1", TypeCreator.NULLABLE.I8, "comment1"),+ createMockColumn("col2", TypeCreator.NULLABLE.STRING, "comment2")+ };+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.UpdateTableColumnPositionRequest req =+ new TableUpdateRequest.UpdateTableColumnPositionRequest(+ new String[] {"col1"}, TableChange.ColumnPosition.first());++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testDeleteTableColumn() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ ColumnDTO[] columns =+ new ColumnDTO[] {createMockColumn("col2", TypeCreator.NULLABLE.STRING, "comment2")};+ TableDTO expectedTable = createMockTable("table1", columns, "comment", Collections.emptyMap());+ TableUpdateRequest.DeleteTableColumnRequest req =+ new TableUpdateRequest.DeleteTableColumnRequest(new String[] {"col1"}, true);++ testAlterTable(tableId, req, expectedTable);+ }++ @Test+ public void testDropTable() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of(metalakeName, catalogName, "schema1", "table1");+ String tablePath =+ withSlash(+ RelationalCatalog.formatTableRequestPath(tableId.namespace()) + "/" + tableId.name());+ DropResponse resp = new DropResponse(true);+ buildMockResource(Method.DELETE, tablePath, null, resp, SC_OK);++ Assertions.assertTrue(catalog.asTableCatalog().dropTable(tableId));++ // return false+ resp = new DropResponse(false);+ buildMockResource(Method.DELETE, tablePath, null, resp, SC_OK);+ Assertions.assertFalse(catalog.asTableCatalog().dropTable(tableId));++ // Test with exception+ ErrorResponse errorResp = ErrorResponse.internalError("internal error");+ buildMockResource(Method.DELETE, tablePath, null, errorResp, SC_INTERNAL_SERVER_ERROR);++ Assertions.assertFalse(catalog.asTableCatalog().dropTable(tableId));+ }++ private void testAlterTable(NameIdentifier ident, TableUpdateRequest req, TableDTO updatedTable)+ throws JsonProcessingException {+ String tablePath =+ withSlash(RelationalCatalog.formatTableRequestPath(ident.namespace()) + "/" + ident.name());+ TableUpdatesRequest updatesRequest = new TableUpdatesRequest(ImmutableList.of(req));+ TableResponse resp = new TableResponse(updatedTable);+ buildMockResource(Method.PUT, tablePath, updatesRequest, resp, SC_OK);++ Table alteredTable = catalog.asTableCatalog().alterTable(ident, req.tableChange());+ Assertions.assertEquals(updatedTable.name(), alteredTable.name());+ Assertions.assertEquals(updatedTable.comment(), alteredTable.comment());+ Assertions.assertEquals(updatedTable.properties(), alteredTable.properties());++ Assertions.assertEquals(updatedTable.columns().length, alteredTable.columns().length);+ for (int i = 0; i < updatedTable.columns().length; i++) {+ Assertions.assertEquals(updatedTable.columns()[i].name(), alteredTable.columns()[i].name());+ Assertions.assertEquals(+ updatedTable.columns()[i].dataType(), alteredTable.columns()[i].dataType());+ Assertions.assertEquals(+ updatedTable.columns()[i].comment(), alteredTable.columns()[i].comment());+ }+ }++ private void testAlterSchema(+ NameIdentifier ident, SchemaUpdateRequest req, SchemaDTO updatedSchema)+ throws JsonProcessingException {+ String schemaPath =+ withSlash(+ RelationalCatalog.formatSchemaRequestPath(ident.namespace()) + "/" + ident.name());+ SchemaUpdatesRequest updatesReq = new SchemaUpdatesRequest(ImmutableList.of(req));+ SchemaResponse resp = new SchemaResponse(updatedSchema);+ buildMockResource(Method.PUT, schemaPath, updatesReq, resp, SC_OK);++ Schema alteredSchema = catalog.asSchemas().alterSchema(ident, req.schemaChange());+ Assertions.assertEquals(updatedSchema.name(), alteredSchema.name());+ Assertions.assertEquals(updatedSchema.comment(), alteredSchema.comment());+ Assertions.assertEquals(updatedSchema.properties(), alteredSchema.properties());+ }++ private static String withSlash(String path) {+ return "/" + path;+ }++ private static SchemaDTO createMockSchema(+ String name, String comment, Map<String, String> props) {+ return new SchemaDTO.Builder()+ .withName(name)+ .withComment(comment)+ .withProperties(props)+ .withAudit(+ new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ }++ private static ColumnDTO createMockColumn(String name, Type type, String comment) {+ return new ColumnDTO.Builder().withName(name).withDataType(type).withComment(comment).build();+ }++ private static TableDTO createMockTable(+ String name, ColumnDTO[] columns, String comment, Map<String, String> properties) {+ return new TableDTO.Builder()+ .withName(name)+ .withColumns(columns)+ .withComment(comment)+ .withProperties(properties)+ .withAudit(+ new AuditDTO.Builder().withCreator("creator").withCreateTime(Instant.now()).build())+ .build();+ }+}diff --git a/server/src/test/java/com/datastrato/graviton/server/web/rest/TestSchemaOperations.java b/server/src/test/java/com/datastrato/graviton/server/web/rest/TestSchemaOperations.javaindex 33c9aeb550..d2082f371f 100644--- a/server/src/test/java/com/datastrato/graviton/server/web/rest/TestSchemaOperations.java+++ b/server/src/test/java/com/datastrato/graviton/server/web/rest/TestSchemaOperations.java@@ -410,6 +410,7 @@ public class TestSchemaOperations extends JerseyTest {DropResponse dropResp2 = resp3.readEntity(DropResponse.class);Assertions.assertEquals(0, dropResp2.getCode());+ Assertions.assertTrue(dropResp2.dropped());// Test throw RuntimeExceptiondoThrow(new RuntimeException("mock error")).when(dispatcher).dropSchema(any(), eq(false));