Skip to content

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

[#86] refactor(catalog): Change the `Namespace` semantics to `Schema` in catalog definition (#87)

Jerry Shaofe0aa5d2123a
diff --git a/api/src/main/java/com/datastrato/graviton/Catalog.java b/api/src/main/java/com/datastrato/graviton/Catalog.java
index 5400331cc0..82712921e4 100644
--- a/api/src/main/java/com/datastrato/graviton/Catalog.java
+++ b/api/src/main/java/com/datastrato/graviton/Catalog.java
@@ -1,5 +1,6 @@
package com.datastrato.graviton;
+import com.datastrato.graviton.rel.SupportsSchemas;
import com.datastrato.graviton.rel.TableCatalog;
import java.util.Map;
@@ -30,12 +31,12 @@ public interface Catalog extends Auditable {
Map<String, String> properties();
/**
- * Return the {@link SupportsNamespaces} if the catalog supports namespace operations.
+ * Return the {@link SupportsSchemas} if the catalog supports schema operations.
*
- * @throws UnsupportedOperationException if the catalog does not support namespace operations.
+ * @throws UnsupportedOperationException if the catalog does not support schema operations.
*/
- default SupportsNamespaces asNamespaces() throws UnsupportedOperationException {
- throw new UnsupportedOperationException("Catalog does not support namespace operations");
+ default SupportsSchemas asSchemas() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Catalog does not support schema operations");
}
/**
diff --git a/api/src/main/java/com/datastrato/graviton/SupportCatalogs.java b/api/src/main/java/com/datastrato/graviton/SupportCatalogs.java
index 783d08eed8..b2b9ac4d12 100644
--- a/api/src/main/java/com/datastrato/graviton/SupportCatalogs.java
+++ b/api/src/main/java/com/datastrato/graviton/SupportCatalogs.java
@@ -12,7 +12,7 @@ public interface SupportCatalogs {
*
* @param namespace The namespace to list the catalogs under it.
* @return The list of catalogs.
- * @throws NoSuchmetalakeException If the metalake with namespace does not exist.
+ * @throws NoSuchMetalakeException If the metalake with namespace does not exist.
*/
Catalog[] listCatalogs(Namespace namespace) throws NoSuchMetalakeException;
@@ -48,7 +48,7 @@ public interface SupportCatalogs {
* @param comment the comment of the catalog.
* @param properties the properties of the catalog.
* @return The created catalog.
- * @throws NoSuchmetalakeException If the metalake does not exist.
+ * @throws NoSuchMetalakeException If the metalake does not exist.
* @throws CatalogAlreadyExistsException If the catalog already exists.
*/
Catalog createCatalog(
diff --git a/api/src/main/java/com/datastrato/graviton/SupportsNamespaces.java b/api/src/main/java/com/datastrato/graviton/SupportsNamespaces.java
deleted file mode 100644
index 4b18fd48cb..0000000000
--- a/api/src/main/java/com/datastrato/graviton/SupportsNamespaces.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// Referred from Apache's connector/catalog implementation
-// sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/SupportNamespaces.java
-
-package com.datastrato.graviton;
-
-import com.datastrato.graviton.exceptions.NamespaceAlreadyExistsException;
-import com.datastrato.graviton.exceptions.NoSuchNamespaceException;
-import com.datastrato.graviton.exceptions.NonEmptyNamespaceException;
-import java.util.Map;
-
-/**
- * The Catalog interface to support namespace operations. If the implemented catalog has namespace
- * semantics, it should implement this interface.
- */
-public interface SupportsNamespaces {
-
- /**
- * List top-level namespaces from the catalog.
- *
- * <p>If an entity such as a table, view exists, its parent namespaces must also exist and must be
- * returned by this discovery method. For example, if table a.b.t exists, this method must return
- * ["a"] in the result array.
- *
- * @return an array of namespace
- * @throws NoSuchNamespaceException if there's no namespace in the catalog
- */
- Namespace[] listNamespaces() throws NoSuchNamespaceException;
-
- /**
- * List namespaces in a namespace.
- *
- * <p>If an entity such as a table, view exists, its parent namespaces must also exist and must be
- * returned by this discovery method. For example, if table a.b.t exists, this method invoked as
- * listNamespaces(a) must return [a.b] in the result array
- *
- * @param namespace the namespace to list
- * @return an array of namespace
- * @throws NoSuchNamespaceException if the namespace does not exist
- */
- Namespace[] listNamespaces(Namespace namespace) throws NoSuchNamespaceException;
-
- /**
- * Check if a namespace exists.
- *
- * <p>If an entity such as a table, view exists, its parent namespaces must also exist. For
- * example, if table a.b.t exists, this method invoked as namespaceExists(a) must return true.
- *
- * @param namespace the namespace to check
- * @return true if the namespace exists, false otherwise
- */
- boolean namespaceExists(Namespace namespace);
-
- /**
- * Create a namespace in the catalog.
- *
- * @param namespace the namespace to create
- * @param metadata the metadata of the namespace
- * @throws NamespaceAlreadyExistsException if the namespace already exists
- */
- void createNamespace(Namespace namespace, Map<String, String> metadata)
- throws NamespaceAlreadyExistsException;
-
- /**
- * Load metadata properties for a namespace.
- *
- * @param namespace a namespace. {@link Namespace}
- * @return a string map of properties for the given namespace
- * @throws NoSuchNamespaceException If the namespace does not exist (optional)
- */
- Map<String, String> loadNamespaceMetadata(Namespace namespace) throws NoSuchNamespaceException;
-
- /**
- * Apply the metadata change to a namespace in the catalog.
- *
- * @param namespace the namespace to alter
- * @param changes the metadata changes to apply
- * @throws NoSuchNamespaceException if the namespace does not exist
- */
- void alterNamespace(Namespace namespace, NamespaceChange... changes)
- throws NoSuchNamespaceException;
-
- /**
- * Drop a namespace from the catalog with cascade option, recursively dropping all objects within
- * the namespace if cascade is tur.
- *
- * <p>If the catalog implementation does not support this operation, it may throw {@link
- * UnsupportedOperationException}.
- *
- * @param namespace the namespace to drop
- * @param cascade if true, recursively drop all objects within the namespace
- * @return true if the namespace is dropped successfully, false otherwise
- * @throws NonEmptyNamespaceException if the namespace is not empty and cascade is false
- * @throws NoSuchNamespaceException if the namespace does not exist
- */
- boolean dropNamespace(Namespace namespace, boolean cascade)
- throws NonEmptyNamespaceException, NoSuchNamespaceException;
-}
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/NamespaceAlreadyExistsException.java b/api/src/main/java/com/datastrato/graviton/exceptions/NamespaceAlreadyExistsException.java
deleted file mode 100644
index 15b7c7ce65..0000000000
--- a/api/src/main/java/com/datastrato/graviton/exceptions/NamespaceAlreadyExistsException.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.datastrato.graviton.exceptions;
-
-/** Exception thrown when a namespace already exists. */
-public class NamespaceAlreadyExistsException extends AlreadyExistsException {
-
- public NamespaceAlreadyExistsException(String message) {
- super(message);
- }
-
- public NamespaceAlreadyExistsException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/NoSuchSchemaException.java b/api/src/main/java/com/datastrato/graviton/exceptions/NoSuchSchemaException.java
new file mode 100644
index 0000000000..1a2ce170bd
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/exceptions/NoSuchSchemaException.java
@@ -0,0 +1,12 @@
+package com.datastrato.graviton.exceptions;
+
+public class NoSuchSchemaException extends NotFoundException {
+
+ public NoSuchSchemaException(String message) {
+ super(message);
+ }
+
+ public NoSuchSchemaException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptyNamespaceException.java b/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptyNamespaceException.java
deleted file mode 100644
index 50775e43a9..0000000000
--- a/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptyNamespaceException.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.datastrato.graviton.exceptions;
-
-/** Exception thrown when a namespace is not empty. */
-public class NonEmptyNamespaceException extends GravitonRuntimeException {
-
- public NonEmptyNamespaceException(String message) {
- super(message);
- }
-
- public NonEmptyNamespaceException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptySchemaException.java b/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptySchemaException.java
new file mode 100644
index 0000000000..0aae3d9b37
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptySchemaException.java
@@ -0,0 +1,13 @@
+package com.datastrato.graviton.exceptions;
+
+/** Exception thrown when a namespace is not empty. */
+public class NonEmptySchemaException extends GravitonRuntimeException {
+
+ public NonEmptySchemaException(String message) {
+ super(message);
+ }
+
+ public NonEmptySchemaException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/SchemaAlreadyExistsException.java b/api/src/main/java/com/datastrato/graviton/exceptions/SchemaAlreadyExistsException.java
new file mode 100644
index 0000000000..fe99b1c8e9
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/exceptions/SchemaAlreadyExistsException.java
@@ -0,0 +1,12 @@
+package com.datastrato.graviton.exceptions;
+
+public class SchemaAlreadyExistsException extends AlreadyExistsException {
+
+ public SchemaAlreadyExistsException(String message) {
+ super(message);
+ }
+
+ public SchemaAlreadyExistsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/api/src/main/java/com/datastrato/graviton/rel/Schema.java b/api/src/main/java/com/datastrato/graviton/rel/Schema.java
new file mode 100644
index 0000000000..1e097176f3
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/rel/Schema.java
@@ -0,0 +1,31 @@
+package com.datastrato.graviton.rel;
+
+import com.datastrato.graviton.Auditable;
+import java.util.Collections;
+import java.util.Map;
+import javax.annotation.Nullable;
+
+/**
+ * An interface representing a schema in the {@link com.datastrato.graviton.Catalog}. Schema is a
+ * basic container of relational objects, like tables, views, etc. Schema can be self-nested, which
+ * means it can be schema1.schema2.table.
+ *
+ * <p>It defines basic properties of a schema. A catalog implementation with {@link SupportsSchemas}
+ * should implement it.
+ */
+public interface Schema extends Auditable {
+
+ /** return the name of the Schema. */
+ String name();
+
+ /** return the comment of the Schema. Null is returned if no comment is set. */
+ @Nullable
+ default String comment() {
+ return null;
+ }
+
+ /** return the properties of the Schema. Empty map is returned if no properties are set. */
+ default Map<String, String> properties() {
+ return Collections.emptyMap();
+ }
+}
diff --git a/api/src/main/java/com/datastrato/graviton/NamespaceChange.java b/api/src/main/java/com/datastrato/graviton/rel/SchemaChange.java
similarity index 75%
rename from api/src/main/java/com/datastrato/graviton/NamespaceChange.java
rename to api/src/main/java/com/datastrato/graviton/rel/SchemaChange.java
index 17b888c6e0..99dd70b613 100644
--- a/api/src/main/java/com/datastrato/graviton/NamespaceChange.java
+++ b/api/src/main/java/com/datastrato/graviton/rel/SchemaChange.java
@@ -18,37 +18,37 @@
// Referred from Apache's connector/catalog implementation
// sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/NamespaceChange.java
-package com.datastrato.graviton;
+package com.datastrato.graviton.rel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
-public interface NamespaceChange {
+public interface SchemaChange {
/**
- * NamespaceChange class to set the property and value for the namespace.
+ * SchemaChange class to set the property and value for the schema.
*
* @param property the property name to set
* @param value the property value to set
- * @return the NamespaceChange object
+ * @return the SchemaChange object
*/
- static NamespaceChange setProperty(String property, String value) {
+ static SchemaChange setProperty(String property, String value) {
return new SetProperty(property, value);
}
/**
- * NamespaceChange class to remove the property from the namespace.
+ * SchemaChange class to remove the property from the schema.
*
* @param property the property name to remove
- * @return the NamespaceChange object
+ * @return the SchemaChange object
*/
- static NamespaceChange removeProperty(String property) {
+ static SchemaChange removeProperty(String property) {
return new RemoveProperty(property);
}
@Getter
@EqualsAndHashCode
- final class SetProperty implements NamespaceChange {
+ final class SetProperty implements SchemaChange {
private final String property;
private final String value;
@@ -60,7 +60,7 @@ public interface NamespaceChange {
@Getter
@EqualsAndHashCode
- final class RemoveProperty implements NamespaceChange {
+ final class RemoveProperty implements SchemaChange {
private final String property;
private RemoveProperty(String property) {
diff --git a/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java b/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java
new file mode 100644
index 0000000000..99a0f24338
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/rel/SupportsSchemas.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Referred from Apache Spark's connector/catalog implementation
+// sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/SupportNamespaces.java
+
+package com.datastrato.graviton.rel;
+
+import com.datastrato.graviton.NameIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.exceptions.*;
+import java.util.Map;
+
+/**
+ * The Catalog interface to support schema operations. If the implemented catalog has schema
+ * semantics, it should implement this interface.
+ */
+public interface SupportsSchemas {
+
+ /**
+ * List schemas under a namespace.
+ *
+ * <p>If an entity such as a table, view exists, its parent schemas must also exist and must be
+ * returned by this discovery method. For example, if table a.b.t exists, this method invoked as
+ * listSchemas(a) must return [a.b] in the result array
+ *
+ * @param namespace the namespace to list
+ * @return an array of schema identifier under the namespace
+ * @throws NoSuchNamespaceException if the namespace does not exist
+ */
+ NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchNamespaceException;
+
+ /**
+ * Check if a schema exists.
+ *
+ * <p>If an entity such as a table, view exists, its parent namespaces must also exist. For
+ * example, if table a.b.t exists, this method invoked as schemaExists(a) must return true.
+ *
+ * @param ident the name identifier of the schema
+ * @return true if the schema exists, false otherwise
+ */
+ default boolean schemaExists(NameIdentifier ident) {
+ try {
+ loadSchema(ident);
+ return true;
+ } catch (NoSuchSchemaException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Create a schema in the catalog.
+ *
+ * @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 schema
+ * @throws SchemaAlreadyExistsException if the schema already exists
+ */
+ Schema createSchema(NameIdentifier ident, String comment, Map<String, String> metadata)
+ throws SchemaAlreadyExistsException;
+
+ /**
+ * Load metadata properties for a schema.
+ *
+ * @param ident the name identifier of the schema
+ * @return a schema
+ * @throws NoSuchSchemaException If the schema does not exist (optional)
+ */
+ Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException;
+
+ /**
+ * Apply the metadata change to a schema in the catalog.
+ *
+ * @param ident the name identifier of the schema
+ * @param changes the metadata changes to apply
+ * @return the altered schema
+ * @throws NoSuchSchemaException if the schema does not exist
+ */
+ Schema alterSchema(NameIdentifier ident, SchemaChange... changes) throws NoSuchSchemaException;
+
+ /**
+ * Drop a schema from the catalog with cascade option, recursively dropping all objects within the
+ * schema if cascade is tur.
+ *
+ * <p>If the catalog implementation does not support this operation, it may throw {@link
+ * UnsupportedOperationException}.
+ *
+ * @param ident the name identifier of the schema
+ * @param cascade if true, recursively drop all objects within the schema
+ * @return true if the schema is dropped successfully, false otherwise
+ * @throws NonEmptySchemaException if the schema is not empty and cascade is false
+ */
+ boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException;
+}
diff --git a/api/src/main/java/com/datastrato/graviton/rel/TableCatalog.java b/api/src/main/java/com/datastrato/graviton/rel/TableCatalog.java
index 6414c35995..939daa4e08 100644
--- a/api/src/main/java/com/datastrato/graviton/rel/TableCatalog.java
+++ b/api/src/main/java/com/datastrato/graviton/rel/TableCatalog.java
@@ -22,14 +22,14 @@ package com.datastrato.graviton.rel;
import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
-import com.datastrato.graviton.exceptions.NoSuchNamespaceException;
+import com.datastrato.graviton.exceptions.NoSuchSchemaException;
import com.datastrato.graviton.exceptions.NoSuchTableException;
import com.datastrato.graviton.exceptions.TableAlreadyExistsException;
import java.util.Map;
/**
- * The TableCatalog interface defines the public API for managing tables in a namespace. If the
- * catalog implementation supports tables, it must implement this interface.
+ * The TableCatalog interface defines the public API for managing tables in a schema. If the catalog
+ * implementation supports tables, it must implement this interface.
*/
public interface TableCatalog {
@@ -38,9 +38,9 @@ public interface TableCatalog {
*
* @param namespace a namespace
* @return an array of table identifiers in the namespace
- * @throws NoSuchNamespaceException if the namespace does not exist
+ * @throws NoSuchSchemaException if the schema does not exist
*/
- NameIdentifier[] listTables(Namespace namespace) throws NoSuchNamespaceException;
+ NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException;
/**
* Load table metadata by {@link NameIdentifier} from the catalog.
@@ -73,12 +73,12 @@ public interface TableCatalog {
* @param comment the table comment
* @param properties the table properties
* @return the created table metadata
- * @throws NoSuchNamespaceException if the namespace does not exist
+ * @throws NoSuchSchemaException if the schema does not exist
* @throws TableAlreadyExistsException if the table already exists
*/
Table createTable(
NameIdentifier ident, Column[] columns, String comment, Map<String, String> properties)
- throws NoSuchNamespaceException, TableAlreadyExistsException;
+ throws NoSuchSchemaException, TableAlreadyExistsException;
/**
* Apply the {@link TableChange change} to a table in the catalog.
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java
index 17d280a6b5..e11d1b45f8 100644
--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalog.java
@@ -1,22 +1,30 @@
package com.datastrato.graviton.catalog.hive;
import com.datastrato.graviton.*;
-import com.datastrato.graviton.catalog.hive.json.HiveDatabase;
-import com.datastrato.graviton.exceptions.NamespaceAlreadyExistsException;
+import com.datastrato.graviton.catalog.hive.rel.HiveSchema;
import com.datastrato.graviton.exceptions.NoSuchNamespaceException;
-import com.datastrato.graviton.exceptions.NonEmptyNamespaceException;
+import com.datastrato.graviton.exceptions.NoSuchSchemaException;
+import com.datastrato.graviton.exceptions.NonEmptySchemaException;
+import com.datastrato.graviton.exceptions.SchemaAlreadyExistsException;
+import com.datastrato.graviton.meta.AuditInfo;
import com.datastrato.graviton.meta.BaseCatalog;
+import com.datastrato.graviton.rel.SchemaChange;
+import com.datastrato.graviton.rel.SupportsSchemas;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.time.Instant;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.*;
+import org.apache.hadoop.security.UserGroupInformation;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class HiveCatalog extends BaseCatalog implements SupportsNamespaces {
+public class HiveCatalog extends BaseCatalog implements SupportsSchemas {
+
public static final Logger LOG = LoggerFactory.getLogger(HiveCatalog.class);
@VisibleForTesting HiveClientPool clientPool;
@@ -27,6 +35,7 @@ public class HiveCatalog extends BaseCatalog implements SupportsNamespaces {
public void close() {
if (clientPool != null) {
clientPool.close();
+ clientPool = null;
}
}
@@ -37,135 +46,166 @@ public class HiveCatalog extends BaseCatalog implements SupportsNamespaces {
}
@Override
- public Namespace[] listNamespaces() throws NoSuchNamespaceException {
- return listNamespaces(Namespace.of("metalake", this.name));
- }
-
- @Override
- public Namespace[] listNamespaces(Namespace namespace) throws NoSuchNamespaceException {
- // hive namespace expression is `metalake.catalog.db`
- if (namespace.levels().length != 2) {
- throw new NoSuchNamespaceException("Namespace does not exist: " + namespace);
+ public NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchNamespaceException {
+ if (!isValidNamespace(namespace)) {
+ throw new NoSuchNamespaceException("Namespace is invalid " + namespace);
}
try {
- Namespace[] namespaces =
- clientPool
- .run(
- client ->
- client.getAllDatabases().stream()
- .map(ns -> Namespace.of(namespace.level(0), namespace.level(1), ns)))
- .toArray(Namespace[]::new);
-
- LOG.debug("Listing namespace {} returned namespaces: {}", namespace, namespaces);
- return namespaces;
+ NameIdentifier[] schemas =
+ clientPool.run(
+ c ->
+ c.getAllDatabases().stream()
+ .map(db -> NameIdentifier.of(namespace, db))
+ .toArray(NameIdentifier[]::new));
+ return schemas;
+
} catch (TException e) {
throw new RuntimeException(
- "Failed to list all namespace: " + namespace + " in Hive Metastore", e);
+ "Failed to list all schemas (database) under namespace : "
+ + namespace
+ + " in Hive Metastore",
+ e);
+
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
- public boolean namespaceExists(Namespace namespace) {
- try {
- clientPool.run(client -> client.getDatabase(getDbNameFromNamespace(namespace)));
- } catch (TException | InterruptedException e) {
- return false;
- }
- return true;
- }
-
- @Override
- public void createNamespace(Namespace namespace, Map<String, String> metadata)
- throws NamespaceAlreadyExistsException {
+ public HiveSchema createSchema(NameIdentifier ident, String comment, Map<String, String> metadata)
+ throws SchemaAlreadyExistsException {
Preconditions.checkArgument(
- !namespace.isEmpty(),
- String.format("Cannot create namespace with invalid name: %s", namespace));
+ !ident.name().isEmpty(),
+ String.format("Cannot create schema with invalid name: %s", ident.name()));
Preconditions.checkArgument(
- isValidateNamespace(namespace),
- String.format("Cannot support multi part namespace in Hive Metastore: %s", namespace));
+ isValidNamespace(ident.namespace()),
+ String.format("Cannot support invalid namespace in Hive Metastore: %s", ident.namespace()));
try {
- HiveDatabase hiveDatabase =
- new HiveDatabase.Builder()
+ HiveSchema hiveSchema =
+ new HiveSchema.Builder()
+ .withId(1L /*TODO. Use ID generator*/)
+ .withCatalogId(getId())
+ .withName(ident.name())
+ .withNamespace(ident.namespace())
+ .withComment(comment)
+ .withProperties(metadata)
+ .withAuditInfo(
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .build())
.withConf(hiveConf)
- .withNamespace(namespace)
- .withMetadata(metadata)
.build();
clientPool.run(
client -> {
- client.createDatabase(hiveDatabase.getInnerDatabase());
+ client.createDatabase(hiveSchema.toInnerDB());
return null;
});
- LOG.info("Created namespace: {}", namespace);
+ // TODO. We should also store the customized HiveSchema entity fields into our own
+ // underlying storage, like id, auditInfo, etc.
+
+ LOG.info("Created Hive schema (database) {} in Hive Metastore", ident.name());
+
+ return hiveSchema;
+
} catch (AlreadyExistsException e) {
- throw new NamespaceAlreadyExistsException(
- String.format("Namespace '%s' already exists!", namespace));
+ throw new SchemaAlreadyExistsException(
+ String.format(
+ "Hive schema (database) '%s' already exists in Hive Metastore", ident.name()));
+
} catch (TException e) {
throw new RuntimeException(
- "Failed to create namespace " + namespace + " in Hive Metastore", e);
+ "Failed to create Hive schema (database) " + ident.name() + " in Hive Metastore", e);
+
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
- public Map<String, String> loadNamespaceMetadata(Namespace namespace)
- throws NoSuchNamespaceException {
- if (!isValidateNamespace(namespace)) {
- throw new NoSuchNamespaceException(String.format("Namespace does not exist: %s", namespace));
- }
+ public HiveSchema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {
+ Preconditions.checkArgument(
+ !ident.name().isEmpty(),
+ String.format("Cannot create schema with invalid name: %s", namespace));
+ Preconditions.checkArgument(
+ isValidNamespace(ident.namespace()),
+ String.format("Cannot support invalid namespace in Hive Metastore: %s", namespace));
try {
- Database database =
- clientPool.run(client -> client.getDatabase(getDbNameFromNamespace(namespace)));
- HiveDatabase hiveDatabase = new HiveDatabase.Builder().withHiveDatabase(database).build();
- Map<String, String> metadata = hiveDatabase.getMetadata();
+ Database database = clientPool.run(client -> client.getDatabase(ident.name()));
+ HiveSchema.Builder builder = new HiveSchema.Builder();
+
+ // TODO. We should also fetch the customized HiveSchema entity fields from our own
+ // underlying storage, like id, auditInfo, etc.
+
+ builder =
+ builder
+ .withId(1L /* TODO. Fetch id from underlying storage */)
+ .withCatalogId(getId())
+ .withNamespace(ident.namespace())
+ .withAuditInfo(
+ /* TODO. Fetch audit info from underlying storage */
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .build())
+ .withConf(hiveConf);
+ HiveSchema hiveSchema = HiveSchema.fromInnerDB(database, builder);
+
+ LOG.info("Loaded Hive schema (database) {} from Hive Metastore ", ident.name());
+
+ return hiveSchema;
- LOG.debug("Loaded metadata for namespace {} found {}", namespace, metadata.keySet());
- return metadata;
} catch (NoSuchObjectException | UnknownDBException e) {
- throw new NoSuchNamespaceException(
- String.format("Namespace does not exist: %s", namespace), e);
+ throw new NoSuchSchemaException(
+ String.format(
+ "Hive schema (database) does not exist: %s in Hive Metastore", ident.name()),
+ e);
+
+ // TODO. We should also delete Hive schema (database) from our own underlying storage
+
} catch (TException e) {
throw new RuntimeException(
- "Failed to list namespace under namespace: " + namespace + " in Hive Metastore", e);
+ "Failed to load Hive schema (database) " + ident.name() + " from Hive Metastore", e);
+
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
- public void alterNamespace(Namespace namespace, NamespaceChange... changes)
- throws NoSuchNamespaceException {
+ public HiveSchema alterSchema(NameIdentifier ident, SchemaChange... changes)
+ throws NoSuchSchemaException {
Preconditions.checkArgument(
- !namespace.isEmpty(),
- String.format("Cannot create namespace with invalid name: %s", namespace));
+ !ident.name().isEmpty(),
+ String.format("Cannot create schema with invalid name: %s", namespace));
Preconditions.checkArgument(
- isValidateNamespace(namespace),
- String.format("Cannot support multi part namespace in Hive Metastore: %s", namespace));
+ isValidNamespace(ident.namespace()),
+ String.format("Cannot support invalid namespace in Hive Metastore: %s", namespace));
try {
// load the database parameters
- Database database =
- clientPool.run(client -> client.getDatabase(getDbNameFromNamespace(namespace)));
- HiveDatabase hiveDatabase = new HiveDatabase.Builder().withHiveDatabase(database).build();
- Map<String, String> metadata = hiveDatabase.getMetadata();
- LOG.debug("Loaded metadata for namespace {} found {}", namespace, metadata.keySet());
-
- for (NamespaceChange change : changes) {
- if (change instanceof NamespaceChange.SetProperty) {
+ Database database = clientPool.run(client -> client.getDatabase(ident.name()));
+ Map<String, String> metadata = HiveSchema.convertToMetadata(database);
+ LOG.debug(
+ "Loaded metadata for Hive schema (database) {} found {}",
+ ident.name(),
+ metadata.keySet());
+
+ for (SchemaChange change : changes) {
+ if (change instanceof SchemaChange.SetProperty) {
metadata.put(
- ((NamespaceChange.SetProperty) change).getProperty(),
- ((NamespaceChange.SetProperty) change).getValue());
- } else if (change instanceof NamespaceChange.RemoveProperty) {
- metadata.remove(((NamespaceChange.RemoveProperty) change).getProperty());
+ ((SchemaChange.SetProperty) change).getProperty(),
+ ((SchemaChange.SetProperty) change).getValue());
+ } else if (change instanceof SchemaChange.RemoveProperty) {
+ metadata.remove(((SchemaChange.RemoveProperty) change).getProperty());
} else {
- throw new IllegalArgumentException("Unsupported namespace change type: " + change);
+ throw new IllegalArgumentException(
+ "Unsupported schema change type: " + change.getClass().getSimpleName());
}
}
@@ -175,50 +215,106 @@ public class HiveCatalog extends BaseCatalog implements SupportsNamespaces {
clientPool.run(
client -> {
- client.alterDatabase(getDbNameFromNamespace(namespace), alteredDatabase);
+ client.alterDatabase(ident.name(), alteredDatabase);
return null;
});
- LOG.info("Altered namespace: {}", alteredDatabase);
+ // TODO. We should also update the customized HiveSchema entity fields into our own if
+ // necessary
+ HiveSchema.Builder builder = new HiveSchema.Builder();
+ builder =
+ builder
+ .withId(1L /* TODO. Fetch id from underlying storage */)
+ .withCatalogId(getId())
+ .withNamespace(ident.namespace())
+ .withAuditInfo(
+ /* TODO. Fetch audit info from underlying storage */
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .withLastModifier(currentUser())
+ .withLastModifiedTime(Instant.now())
+ .build())
+ .withConf(hiveConf);
+ HiveSchema hiveSchema = HiveSchema.fromInnerDB(alteredDatabase, builder);
+
+ LOG.info("Altered Hive schema (database) {} in Hive Metastore", ident.name());
// todo(xun): hive dose not support renaming database name directly,
// perhaps we can use namespace to mapping the database names indirectly
+
+ return hiveSchema;
+
} catch (TException | InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
- public boolean dropNamespace(Namespace namespace, boolean cascade)
- throws NonEmptyNamespaceException, NoSuchNamespaceException {
- if (!isValidateNamespace(namespace)) {
+ public boolean dropSchema(NameIdentifier ident, boolean cascade) throws NonEmptySchemaException {
+ if (ident.name().isEmpty()) {
+ LOG.error("Cannot drop schema with invalid name: {}", ident.name());
+ return false;
+ }
+ if (!isValidNamespace(ident.namespace())) {
+ LOG.error("Cannot support invalid namespace in Hive Metastore: {}", ident.namespace());
return false;
}
try {
clientPool.run(
client -> {
- client.dropDatabase(getDbNameFromNamespace(namespace), false, false, cascade);
+ client.dropDatabase(ident.name(), false, false, cascade);
return null;
});
- LOG.info("Dropped namespace: {}", namespace);
+ // TODO. we should also delete the Hive schema (database) from our own underlying storage
+
+ LOG.info("Dropped Hive schema (database) {}", ident.name());
return true;
+
} catch (InvalidOperationException e) {
- throw new NonEmptyNamespaceException(
- String.format("Namespace %s is not empty. One or more tables exist.", namespace, e));
- } catch (NoSuchObjectException | InterruptedException e) {
+ throw new NonEmptySchemaException(
+ String.format(
+ "Hive schema (database) %s is not empty. One or more tables exist.",
+ ident.name(), e));
+
+ } catch (NoSuchObjectException e) {
+ LOG.warn("Hive schema (database) {} does not exist in Hive Metastore", ident.name());
return false;
+
} catch (TException e) {
- throw new RuntimeException("Failed to drop namespace " + namespace + " in Hive Metastore", e);
+ throw new RuntimeException(
+ "Failed to drop Hive schema (database) " + namespace + " in Hive Metastore", e);
+
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
}
}
- public static boolean isValidateNamespace(Namespace namespace) {
- return namespace.levels().length == 3;
+ @Override
+ public SupportsSchemas asSchemas() {
+ return this;
+ }
+
+ public boolean isValidNamespace(Namespace namespace) {
+ return namespace.levels().length == 2 && namespace.level(1).equals(name());
}
- private String getDbNameFromNamespace(Namespace namespace) {
- return namespace.level(2);
+ // TODO. We should figure out a better way to get the current user from servlet container.
+ private static String currentUser() {
+ String username = null;
+ try {
+ username = UserGroupInformation.getCurrentUser().getShortUserName();
+ } catch (IOException e) {
+ LOG.warn("Failed to get Hadoop user", e);
+ }
+
+ if (username != null) {
+ return username;
+ } else {
+ LOG.warn("Hadoop user is null, defaulting to user.name");
+ return System.getProperty("user.name");
+ }
}
public static class Builder extends BaseCatalog.BaseCatalogBuilder<Builder, HiveCatalog> {
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/json/HiveDatabase.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/json/HiveDatabase.java
deleted file mode 100644
index d8bba6d01a..0000000000
--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/json/HiveDatabase.java
+++ /dev/null
@@ -1,181 +0,0 @@
-package com.datastrato.graviton.catalog.hive.json;
-
-import static com.datastrato.graviton.catalog.hive.HiveCatalog.isValidateNamespace;
-
-import com.datastrato.graviton.Entity;
-import com.datastrato.graviton.Field;
-import com.datastrato.graviton.Namespace;
-import com.datastrato.graviton.exceptions.NoSuchNamespaceException;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.PrincipalType;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HiveDatabase implements Entity {
- public static final Logger LOG = LoggerFactory.getLogger(HiveDatabase.class);
- public static final Field METADATA =
- Field.optional("metadata", Map.class, "The metadata of the database");
- public static final Field NAMESPACE =
- Field.optional("namespace", Namespace.class, "The namespace of the database");
- public static final Field CONFIGURATION =
- Field.optional("conf", Configuration.class, "The configuration of the hive server");
-
- public static final String HMS_DB_OWNER = "hive.metastore.database.owner";
- public static final String HMS_DB_OWNER_TYPE = "hive.metastore.database.owner-type";
-
- private Namespace namespace;
-
- private Map<String, String> metadata;
- private Configuration conf;
-
- private Database innerDatabase;
-
- @Override
- public Map<Field, Object> fields() {
- Map<Field, Object> fields = new HashMap<>();
- fields.put(METADATA, metadata);
- fields.put(NAMESPACE, namespace);
- fields.put(CONFIGURATION, conf);
-
- return Collections.unmodifiableMap(fields);
- }
-
- private Database generateInnerDatabase() {
- if (!isValidateNamespace(namespace)) {
- throw new NoSuchNamespaceException("Namespace does not exist: " + namespace);
- }
-
- Database database = new Database();
- Map<String, String> parameter = Maps.newHashMap();
- String dbName = namespace.level(2);
- database.setName(dbName);
- database.setLocationUri(databaseLocation(namespace.level(2)));
-
- metadata.forEach(
- (key, value) -> {
- if (key.equals("comment")) {
- database.setDescription(value);
- } else if (key.equals("location")) {
- database.setLocationUri(value);
- } else if (key.equals(HMS_DB_OWNER)) {
- database.setOwnerName(value);
- } else if (key.equals(HMS_DB_OWNER_TYPE) && value != null) {
- database.setOwnerType(PrincipalType.valueOf(value));
- } else {
- if (value != null) {
- parameter.put(key, value);
- }
- }
- });
-
- if (database.getOwnerName() == null) {
- database.setOwnerName(currentUser());
- database.setOwnerType(PrincipalType.USER);
- }
-
- database.setParameters(parameter);
-
- return database;
- }
-
- public Map<String, String> getMetadata() {
- Map<String, String> meta = Maps.newHashMap();
-
- meta.putAll(innerDatabase.getParameters());
- meta.put("location", innerDatabase.getLocationUri());
- if (innerDatabase.getDescription() != null) {
- meta.put("comment", innerDatabase.getDescription());
- }
- if (innerDatabase.getOwnerName() != null) {
- meta.put(HMS_DB_OWNER, innerDatabase.getOwnerName());
- if (innerDatabase.getOwnerType() != null) {
- meta.put(HMS_DB_OWNER_TYPE, innerDatabase.getOwnerType().name());
- }
- }
-
- return meta;
- }
-
- private String databaseLocation(String databaseName) {
- String warehouseLocation = conf.get(HiveConf.ConfVars.METASTOREWAREHOUSE.varname);
- Preconditions.checkNotNull(
- warehouseLocation, "Warehouse location is not set: hive.metastore.warehouse.dir=null");
- warehouseLocation = stripTrailingSlash(warehouseLocation);
- return String.format("%s/%s.db", warehouseLocation, databaseName);
- }
-
- public static String stripTrailingSlash(String path) {
- Preconditions.checkArgument(
- path != null && path.length() > 0, "path must not be null or empty");
-
- String result = path;
- while (result.endsWith("/")) {
- result = result.substring(0, result.length() - 1);
- }
- return result;
- }
-
- private static String currentUser() {
- String username = null;
- try {
- username = UserGroupInformation.getCurrentUser().getShortUserName();
- } catch (IOException e) {
- LOG.warn("Failed to get Hadoop user", e);
- }
-
- if (username != null) {
- return username;
- } else {
- LOG.warn("Hadoop user is null, defaulting to user.name");
- return System.getProperty("user.name");
- }
- }
-
- public Database getInnerDatabase() {
- return innerDatabase;
- }
-
- public static class Builder {
- private final HiveDatabase hiveDatabase;
-
- public Builder() {
- this.hiveDatabase = new HiveDatabase();
- }
-
- public HiveDatabase.Builder withConf(Configuration conf) {
- this.hiveDatabase.conf = conf;
- return this;
- }
-
- public HiveDatabase.Builder withHiveDatabase(Database database) {
- this.hiveDatabase.innerDatabase = database;
- return this;
- }
-
- public HiveDatabase.Builder withNamespace(Namespace namespace) {
- this.hiveDatabase.namespace = namespace;
- return this;
- }
-
- public HiveDatabase.Builder withMetadata(Map<String, String> metadata) {
- this.hiveDatabase.metadata = metadata;
- return this;
- }
-
- public HiveDatabase build() {
- if (null == this.hiveDatabase.innerDatabase) {
- this.hiveDatabase.innerDatabase = hiveDatabase.generateInnerDatabase();
- }
- return hiveDatabase;
- }
- }
-}
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/rel/HiveSchema.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/rel/HiveSchema.java
new file mode 100644
index 0000000000..0fad1310da
--- /dev/null
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/rel/HiveSchema.java
@@ -0,0 +1,138 @@
+package com.datastrato.graviton.catalog.hive.rel;
+
+import com.datastrato.graviton.meta.rel.BaseSchema;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import lombok.ToString;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+
+/** A Hive Schema(Database) entity */
+@ToString
+public class HiveSchema extends BaseSchema {
+ private static final String HMS_DB_OWNER = "hive.metastore.database.owner";
+ private static final String HMS_DB_OWNER_TYPE = "hive.metastore.database.owner-type";
+
+ private Database innerDb;
+
+ private Configuration conf;
+
+ private HiveSchema() {}
+
+ public static HiveSchema fromInnerDB(Database db, Builder builder) {
+ Map<String, String> properties = convertToMetadata(db);
+
+ return builder
+ .withName(db.getName())
+ .withComment(db.getDescription())
+ .withProperties(properties)
+ .build();
+ }
+
+ public static Map<String, String> convertToMetadata(Database database) {
+ Map<String, String> meta = Maps.newHashMap();
+
+ meta.putAll(database.getParameters());
+ meta.put("location", database.getLocationUri());
+ if (database.getDescription() != null) {
+ meta.put("comment", database.getDescription());
+ }
+ if (database.getOwnerName() != null) {
+ meta.put(HMS_DB_OWNER, database.getOwnerName());
+ if (database.getOwnerType() != null) {
+ meta.put(HMS_DB_OWNER_TYPE, database.getOwnerType().name());
+ }
+ }
+
+ return meta;
+ }
+
+ public Database toInnerDB() {
+ if (innerDb != null) {
+ return innerDb;
+ }
+
+ innerDb = new Database();
+ Map<String, String> parameter = Maps.newHashMap();
+ innerDb.setName(name());
+ innerDb.setLocationUri(databaseLocation(name()));
+ if (comment() != null) {
+ innerDb.setDescription(comment());
+ }
+
+ Optional.ofNullable(properties)
+ .orElse(Collections.emptyMap())
+ .forEach(
+ (key, value) -> {
+ if (key.equals("location")) {
+ innerDb.setLocationUri(value);
+ } else if (key.equals(HMS_DB_OWNER)) {
+ innerDb.setOwnerName(value);
+ } else if (key.equals(HMS_DB_OWNER_TYPE) && value != null) {
+ innerDb.setOwnerType(PrincipalType.valueOf(value));
+ } else {
+ if (value != null) {
+ parameter.put(key, value);
+ }
+ }
+ });
+
+ if (innerDb.getOwnerName() == null) {
+ innerDb.setOwnerName(auditInfo().creator());
+ innerDb.setOwnerType(PrincipalType.USER);
+ }
+
+ innerDb.setParameters(parameter);
+
+ return innerDb;
+ }
+
+ private String databaseLocation(String databaseName) {
+ String warehouseLocation = conf.get(HiveConf.ConfVars.METASTOREWAREHOUSE.varname);
+ Preconditions.checkNotNull(
+ warehouseLocation, "Warehouse location is not set: hive.metastore.warehouse.dir=null");
+ warehouseLocation = stripTrailingSlash(warehouseLocation);
+ return String.format("%s/%s.db", warehouseLocation, databaseName);
+ }
+
+ private static String stripTrailingSlash(String path) {
+ Preconditions.checkArgument(
+ path != null && path.length() > 0, "path must not be null or empty");
+
+ String result = path;
+ while (result.endsWith("/")) {
+ result = result.substring(0, result.length() - 1);
+ }
+ return result;
+ }
+
+ public static class Builder extends BaseSchemaBuilder<Builder, HiveSchema> {
+
+ protected Configuration conf;
+
+ public Builder withConf(Configuration conf) {
+ this.conf = conf;
+ return this;
+ }
+
+ @Override
+ protected HiveSchema internalBuild() {
+ HiveSchema hiveSchema = new HiveSchema();
+ hiveSchema.id = id;
+ hiveSchema.catalogId = catalogId;
+ hiveSchema.name = name;
+ hiveSchema.namespace = namespace;
+ hiveSchema.comment = comment;
+ hiveSchema.properties = properties;
+ hiveSchema.auditInfo = auditInfo;
+ hiveSchema.conf = conf;
+
+ return hiveSchema;
+ }
+ }
+}
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveCatalogTest.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveCatalogTest.java
index 01b47025a4..be0c3a0001 100644
--- a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveCatalogTest.java
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveCatalogTest.java
@@ -5,6 +5,7 @@ import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;
import com.datastrato.graviton.meta.AuditInfo;
import java.time.Instant;
import java.util.List;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.thrift.TException;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
@@ -28,7 +29,7 @@ public class HiveCatalogTest extends MiniHiveMetastoreService {
hiveCatalog.initialize(null);
- List<String> dbs = hiveCatalog.clientPool.run(client -> client.getAllDatabases());
+ List<String> dbs = hiveCatalog.clientPool.run(IMetaStoreClient::getAllDatabases);
Assert.assertEquals(2, dbs.size());
Assert.assertTrue(dbs.contains("default"));
Assert.assertTrue(dbs.contains(DB_NAME));
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveNamespaceTest.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveNamespaceTest.java
deleted file mode 100644
index c5a05f3612..0000000000
--- a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveNamespaceTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-package com.datastrato.graviton.catalog.hive;
-
-import com.datastrato.graviton.Namespace;
-import com.datastrato.graviton.NamespaceChange;
-import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;
-import com.datastrato.graviton.meta.AuditInfo;
-import com.google.common.collect.Maps;
-import java.time.Instant;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.UUID;
-import org.junit.Assert;
-import org.junit.jupiter.api.Test;
-
-public class HiveNamespaceTest extends MiniHiveMetastoreService {
- HiveCatalog initHiveCatalog() {
- AuditInfo auditInfo =
- new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
-
- HiveCatalog hiveCatalog =
- new HiveCatalog.Builder()
- .withId(1L)
- .withName("catalog")
- .withNamespace(Namespace.of("metalake"))
- .withType(HiveCatalog.Type.RELATIONAL)
- .withMetalakeId(1L)
- .withAuditInfo(auditInfo)
- .withHiveConf(metastore.hiveConf())
- .build();
-
- hiveCatalog.initialize(null);
- return hiveCatalog;
- }
-
- @Test
- public void createNamespaces() {
- HiveCatalog hiveCatalog = initHiveCatalog();
-
- Namespace namespace = Namespace.of("metalake", hiveCatalog.name(), genRandomName());
- Map<String, String> properties = Maps.newHashMap();
- properties.put("key1", "val1");
- properties.put("key2", "val2");
- hiveCatalog.createNamespace(namespace, properties);
- Assert.assertTrue(hiveCatalog.namespaceExists(namespace));
-
- Namespace[] namespaces = hiveCatalog.listNamespaces();
- Arrays.asList(namespaces).contains(namespace);
- }
-
- @Test
- public void alterNamespaces() {
- HiveCatalog hiveCatalog = initHiveCatalog();
-
- Namespace namespace = Namespace.of("metalake", hiveCatalog.name(), genRandomName());
- Map<String, String> properties = Maps.newHashMap();
- properties.put("key1", "val1");
- properties.put("key2", "val2");
- hiveCatalog.createNamespace(namespace, properties);
- Assert.assertTrue(hiveCatalog.namespaceExists(namespace));
-
- Map<String, String> properties1 = hiveCatalog.loadNamespaceMetadata(namespace);
- Assert.assertTrue(properties1.get("key1").equals("val1"));
- Assert.assertTrue(properties1.get("key2").equals("val2"));
-
- hiveCatalog.alterNamespace(namespace, NamespaceChange.removeProperty("key1"));
- hiveCatalog.alterNamespace(namespace, NamespaceChange.setProperty("key2", "val2-alter"));
- Map<String, String> properties2 = hiveCatalog.loadNamespaceMetadata(namespace);
- Assert.assertFalse(properties2.containsKey("key1"));
- Assert.assertTrue(properties2.get("key2").equals("val2-alter"));
-
- hiveCatalog.alterNamespace(
- namespace,
- NamespaceChange.setProperty("key3", "val3"),
- NamespaceChange.setProperty("key4", "val4"));
- Map<String, String> properties3 = hiveCatalog.loadNamespaceMetadata(namespace);
- Assert.assertTrue(properties3.get("key3").equals("val3"));
- Assert.assertTrue(properties3.get("key4").equals("val4"));
- }
-
- @Test
- public void dropNamespaces() {
- HiveCatalog hiveCatalog = initHiveCatalog();
-
- Namespace namespace = Namespace.of("metalake", hiveCatalog.name(), genRandomName());
- Map<String, String> properties = Maps.newHashMap();
- properties.put("key1", "val1");
- properties.put("key2", "val2");
- hiveCatalog.createNamespace(namespace, properties);
-
- Assert.assertTrue(hiveCatalog.namespaceExists(namespace));
- hiveCatalog.dropNamespace(namespace, true);
- Assert.assertFalse(hiveCatalog.namespaceExists(namespace));
- }
-
- private static String genRandomName() {
- return UUID.randomUUID().toString().replace("-", "");
- }
-}
diff --git a/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java
new file mode 100644
index 0000000000..a437dae40c
--- /dev/null
+++ b/catalog-hive/src/test/java/com/datastrato/graviton/catalog/hive/HiveSchemaTest.java
@@ -0,0 +1,119 @@
+package com.datastrato.graviton.catalog.hive;
+
+import com.datastrato.graviton.NameIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.catalog.hive.miniHMS.MiniHiveMetastoreService;
+import com.datastrato.graviton.catalog.hive.rel.HiveSchema;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.rel.SchemaChange;
+import com.google.common.collect.Maps;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class HiveSchemaTest extends MiniHiveMetastoreService {
+ HiveCatalog initHiveCatalog() {
+ AuditInfo auditInfo =
+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ HiveCatalog hiveCatalog =
+ new HiveCatalog.Builder()
+ .withId(1L)
+ .withName("catalog")
+ .withNamespace(Namespace.of("metalake"))
+ .withType(HiveCatalog.Type.RELATIONAL)
+ .withMetalakeId(1L)
+ .withAuditInfo(auditInfo)
+ .withHiveConf(metastore.hiveConf())
+ .build();
+
+ hiveCatalog.initialize(null);
+ return hiveCatalog;
+ }
+
+ @Test
+ public void testCreateHiveSchema() {
+ HiveCatalog hiveCatalog = initHiveCatalog();
+
+ NameIdentifier ident = NameIdentifier.of("metalake", hiveCatalog.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+ String comment = "comment";
+
+ HiveSchema schema = hiveCatalog.createSchema(ident, comment, properties);
+ Assertions.assertEquals(ident.name(), schema.name());
+ Assertions.assertEquals(ident.namespace(), schema.namespace());
+ Assertions.assertEquals(comment, schema.comment());
+ Assertions.assertEquals(properties, schema.properties());
+
+ Assertions.assertTrue(hiveCatalog.schemaExists(ident));
+
+ NameIdentifier[] idents = hiveCatalog.listSchemas(ident.namespace());
+ Assertions.assertTrue(Arrays.asList(idents).contains(ident));
+
+ // Test illegal identifier
+ NameIdentifier ident1 = NameIdentifier.of("metalake", hiveCatalog.name());
+ Throwable exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ hiveCatalog.createSchema(ident1, comment, properties);
+ });
+ Assertions.assertTrue(
+ exception.getMessage().contains("Cannot support invalid namespace in Hive Metastore"));
+ }
+
+ @Test
+ public void testAlterSchema() {
+ HiveCatalog hiveCatalog = initHiveCatalog();
+
+ NameIdentifier ident = NameIdentifier.of("metalake", hiveCatalog.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+ String comment = "comment";
+
+ hiveCatalog.createSchema(ident, comment, properties);
+ Assertions.assertTrue(hiveCatalog.schemaExists(ident));
+
+ Map<String, String> properties1 = hiveCatalog.loadSchema(ident).properties();
+ Assertions.assertEquals("val1", properties1.get("key1"));
+ Assertions.assertEquals("val2", properties1.get("key2"));
+
+ hiveCatalog.alterSchema(
+ ident, SchemaChange.removeProperty("key1"), SchemaChange.setProperty("key2", "val2-alter"));
+ Map<String, String> properties2 = hiveCatalog.loadSchema(ident).properties();
+ Assertions.assertFalse(properties2.containsKey("key1"));
+ Assertions.assertEquals("val2-alter", properties2.get("key2"));
+
+ hiveCatalog.alterSchema(
+ ident, SchemaChange.setProperty("key3", "val3"), SchemaChange.setProperty("key4", "val4"));
+ Map<String, String> properties3 = hiveCatalog.loadSchema(ident).properties();
+ Assertions.assertEquals("val3", properties3.get("key3"));
+ Assertions.assertEquals("val4", properties3.get("key4"));
+ }
+
+ @Test
+ public void testDropSchema() {
+ HiveCatalog hiveCatalog = initHiveCatalog();
+
+ NameIdentifier ident = NameIdentifier.of("metalake", hiveCatalog.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+ String comment = "comment";
+
+ hiveCatalog.createSchema(ident, comment, properties);
+ Assertions.assertTrue(hiveCatalog.schemaExists(ident));
+ hiveCatalog.dropSchema(ident, true);
+ Assertions.assertFalse(hiveCatalog.schemaExists(ident));
+ }
+
+ private static String genRandomName() {
+ return UUID.randomUUID().toString().replace("-", "");
+ }
+}
diff --git a/common/src/main/java/com/datastrato/graviton/dto/rel/SchemaDTO.java b/common/src/main/java/com/datastrato/graviton/dto/rel/SchemaDTO.java
new file mode 100644
index 0000000000..dbedd3fef5
--- /dev/null
+++ b/common/src/main/java/com/datastrato/graviton/dto/rel/SchemaDTO.java
@@ -0,0 +1,87 @@
+package com.datastrato.graviton.dto.rel;
+
+import com.datastrato.graviton.dto.AuditDTO;
+import com.datastrato.graviton.rel.Schema;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Map;
+
+public class SchemaDTO implements Schema {
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("comment")
+ private String comment;
+
+ @JsonProperty("properties")
+ private Map<String, String> properties;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ private SchemaDTO() {}
+
+ private SchemaDTO(String name, String comment, Map<String, String> properties, AuditDTO audit) {
+ this.name = name;
+ this.comment = comment;
+ this.properties = properties;
+ this.audit = audit;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return properties;
+ }
+
+ @Override
+ public AuditDTO auditInfo() {
+ return audit;
+ }
+
+ public static class Builder<S extends Builder> {
+ protected String name;
+ protected String comment;
+ protected Map<String, String> properties;
+ protected AuditDTO audit;
+
+ public Builder() {}
+
+ public S withName(String name) {
+ this.name = name;
+ return (S) this;
+ }
+
+ public S withComment(String comment) {
+ this.comment = comment;
+ return (S) this;
+ }
+
+ public S withProperties(Map<String, String> properties) {
+ this.properties = properties;
+ return (S) this;
+ }
+
+ public S withAudit(AuditDTO audit) {
+ this.audit = audit;
+ return (S) this;
+ }
+
+ public SchemaDTO build() {
+ Preconditions.checkArgument(name != null && !name.isEmpty(), "name cannot be null or empty");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
+
+ return new SchemaDTO(name, comment, properties, audit);
+ }
+ }
+}
diff --git a/common/src/main/java/com/datastrato/graviton/dto/rel/TableDTO.java b/common/src/main/java/com/datastrato/graviton/dto/rel/TableDTO.java
index d8c56a75c9..66b9d98741 100644
--- a/common/src/main/java/com/datastrato/graviton/dto/rel/TableDTO.java
+++ b/common/src/main/java/com/datastrato/graviton/dto/rel/TableDTO.java
@@ -106,6 +106,7 @@ public class TableDTO implements Table {
Preconditions.checkArgument(name != null && !name.isEmpty(), "name cannot be null or empty");
Preconditions.checkArgument(
columns != null && columns.length > 0, "columns cannot be null or empty");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
return new TableDTO(name, comment, columns, properties, audit);
}
diff --git a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java
new file mode 100644
index 0000000000..0c96674a3a
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java
@@ -0,0 +1,168 @@
+package com.datastrato.graviton.meta.rel;
+
+import com.datastrato.graviton.Entity;
+import com.datastrato.graviton.Field;
+import com.datastrato.graviton.HasIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.rel.Schema;
+import com.google.common.collect.Maps;
+import java.util.Collections;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+
+@EqualsAndHashCode
+@ToString
+public abstract class BaseSchema implements Schema, Entity, HasIdentifier {
+
+ public static final Field ID =
+ Field.required("id", Long.class, "The unique identifier of the schema");
+ public static final Field CATALOG_ID =
+ Field.required("catalog_id", Long.class, "The unique identifier of the catalog");
+ public static final Field NAME = Field.required("name", String.class, "The name of the schema");
+ public static final Field COMMENT =
+ Field.optional("comment", String.class, "The comment of the schema");
+ public static final Field PROPERTIES =
+ Field.optional("properties", Map.class, "The properties of the schema");
+ public static final Field AUDIT_INFO =
+ Field.required("audit_info", AuditInfo.class, "The audit info of the schema");
+
+ protected Long id;
+
+ protected Long catalogId;
+
+ protected String name;
+
+ @Nullable protected String comment;
+
+ @Nullable protected Map<String, String> properties;
+
+ protected AuditInfo auditInfo;
+
+ protected Namespace namespace;
+
+ @Override
+ public Map<Field, Object> fields() {
+ Map<Field, Object> fields = Maps.newHashMap();
+ fields.put(ID, id);
+ fields.put(CATALOG_ID, catalogId);
+ fields.put(NAME, name);
+ fields.put(COMMENT, comment);
+ fields.put(PROPERTIES, properties);
+ fields.put(AUDIT_INFO, auditInfo);
+
+ return Collections.unmodifiableMap(fields);
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public Namespace namespace() {
+ return namespace;
+ }
+
+ @Override
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return properties;
+ }
+
+ @Override
+ public AuditInfo auditInfo() {
+ return auditInfo;
+ }
+
+ interface Builder<SELF extends Builder<SELF, T>, T extends BaseSchema> {
+ SELF withId(Long id);
+
+ SELF withCatalogId(Long catalogId);
+
+ SELF withName(String name);
+
+ SELF withNamespace(Namespace namespace);
+
+ SELF withComment(String comment);
+
+ SELF withProperties(Map<String, String> properties);
+
+ SELF withAuditInfo(AuditInfo auditInfo);
+
+ T build();
+ }
+
+ public abstract static class BaseSchemaBuilder<
+ SELF extends Builder<SELF, T>, T extends BaseSchema>
+ implements Builder<SELF, T> {
+ protected Long id;
+ protected Long catalogId;
+ protected String name;
+ protected Namespace namespace;
+ protected String comment;
+ protected Map<String, String> properties;
+ protected AuditInfo auditInfo;
+
+ @Override
+ public SELF withId(Long id) {
+ this.id = id;
+ return self();
+ }
+
+ @Override
+ public SELF withCatalogId(Long catalogId) {
+ this.catalogId = catalogId;
+ return self();
+ }
+
+ @Override
+ public SELF withName(String name) {
+ this.name = name;
+ return self();
+ }
+
+ @Override
+ public SELF withNamespace(Namespace namespace) {
+ this.namespace = namespace;
+ return self();
+ }
+
+ @Override
+ public SELF withComment(String comment) {
+ this.comment = comment;
+ return self();
+ }
+
+ @Override
+ public SELF withProperties(Map<String, String> properties) {
+ this.properties = properties;
+ return self();
+ }
+
+ @Override
+ public SELF withAuditInfo(AuditInfo auditInfo) {
+ this.auditInfo = auditInfo;
+ return self();
+ }
+
+ @Override
+ public T build() {
+ T t = internalBuild();
+ t.validate();
+ return t;
+ }
+
+ private SELF self() {
+ return (SELF) this;
+ }
+
+ protected abstract T internalBuild();
+ }
+}
diff --git a/core/src/test/java/com/datastrato/graviton/TestCatalog.java b/core/src/test/java/com/datastrato/graviton/TestCatalog.java
index 5b42200ed8..568ea8fd64 100644
--- a/core/src/test/java/com/datastrato/graviton/TestCatalog.java
+++ b/core/src/test/java/com/datastrato/graviton/TestCatalog.java
@@ -1,6 +1,6 @@
package com.datastrato.graviton;
-import com.datastrato.graviton.exceptions.NoSuchNamespaceException;
+import com.datastrato.graviton.exceptions.NoSuchSchemaException;
import com.datastrato.graviton.exceptions.NoSuchTableException;
import com.datastrato.graviton.exceptions.TableAlreadyExistsException;
import com.datastrato.graviton.meta.AuditInfo;
@@ -29,7 +29,7 @@ public class TestCatalog extends BaseCatalog implements TableCatalog {
public void close() throws IOException {}
@Override
- public NameIdentifier[] listTables(Namespace namespace) throws NoSuchNamespaceException {
+ public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
return tables.keySet().stream()
.filter(testTable -> testTable.namespace().equals(namespace))
.toArray(NameIdentifier[]::new);
@@ -47,7 +47,7 @@ public class TestCatalog extends BaseCatalog implements TableCatalog {
@Override
public Table createTable(
NameIdentifier ident, Column[] columns, String comment, Map<String, String> properties)
- throws NoSuchNamespaceException, TableAlreadyExistsException {
+ throws NoSuchSchemaException, TableAlreadyExistsException {
AuditInfo auditInfo =
new AuditInfo.Builder().withCreator("test").withCreateTime(Instant.now()).build();