Skip to content

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

[#305][#306] improvement(core): Adjust id name mapping to support true deletion and modification of entities (#309)

Qi Yub01bc3a716f1
diff --git a/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptyEntityException.java b/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptyEntityException.java
new file mode 100644
index 0000000000..01ab5ca32f
--- /dev/null
+++ b/api/src/main/java/com/datastrato/graviton/exceptions/NonEmptyEntityException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.exceptions;
+
+public class NonEmptyEntityException extends GravitonRuntimeException {
+
+ public NonEmptyEntityException(String message) {
+ super(message);
+ }
+
+ public NonEmptyEntityException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java
index 5905938a0e..ab5929425d 100644
--- a/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java
+++ b/catalog-hive/src/main/java/com/datastrato/graviton/catalog/hive/HiveCatalogOperations.java
@@ -428,10 +428,10 @@ public class HiveCatalogOperations implements CatalogOperations, SupportsSchemas
try {
store.executeInTransaction(
() -> {
- store.delete(ident, SCHEMA);
for (BaseTable t : tables) {
store.delete(NameIdentifier.of(schemaNamespace, t.name()), TABLE);
}
+ store.delete(ident, SCHEMA, true);
clientPool.run(
client -> {
client.dropDatabase(ident.name(), false, false, cascade);
diff --git a/core/src/main/java/com/datastrato/graviton/EntityStore.java b/core/src/main/java/com/datastrato/graviton/EntityStore.java
index 3979d5e6a1..b39559251a 100644
--- a/core/src/main/java/com/datastrato/graviton/EntityStore.java
+++ b/core/src/main/java/com/datastrato/graviton/EntityStore.java
@@ -5,6 +5,7 @@
package com.datastrato.graviton;
import com.datastrato.graviton.Entity.EntityType;
+import com.datastrato.graviton.exceptions.AlreadyExistsException;
import com.datastrato.graviton.exceptions.NoSuchEntityException;
import com.datastrato.graviton.utils.Executable;
import java.io.Closeable;
@@ -105,10 +106,11 @@ public interface EntityStore extends Closeable {
* @return E the updated entity
* @throws IOException if the store operation fails
* @throws NoSuchEntityException if the entity does not exist
+ * @throws AlreadyExistsException if the updated entity already exitsed.
*/
<E extends Entity & HasIdentifier> E update(
NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)
- throws IOException, NoSuchEntityException;
+ throws IOException, NoSuchEntityException, AlreadyExistsException;
/**
* Get the entity from the underlying storage.
@@ -128,10 +130,24 @@ public interface EntityStore extends Closeable {
* Delete the entity from the underlying storage by the specified {@link NameIdentifier}.
*
* @param ident the name identifier of the entity
+ * @param entityType the type of the entity to be deleted
* @return true if the entity is deleted, false otherwise
* @throws IOException if the delete operation fails
*/
- boolean delete(NameIdentifier ident, EntityType entityType) throws IOException;
+ default boolean delete(NameIdentifier ident, EntityType entityType) throws IOException {
+ return delete(ident, entityType, false);
+ }
+
+ /**
+ * Delete the entity from the underlying storage by the specified {@link NameIdentifier}.
+ *
+ * @param ident the name identifier of the entity
+ * @param entityType the type of the entity to be deleted
+ * @param cascade support cacade detele or not
+ * @return true if the entity is deleted, false otherwise
+ * @throws IOException if the delete operation fails
+ */
+ boolean delete(NameIdentifier ident, EntityType entityType, boolean cascade) throws IOException;
/**
* Execute the specified {@link Executable} in a transaction.
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
index f51fbd801e..c4b6b48deb 100644
--- a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java
+++ b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseSchema.java
@@ -11,16 +11,15 @@ import com.datastrato.graviton.HasIdentifier;
import com.datastrato.graviton.Namespace;
import com.datastrato.graviton.meta.AuditInfo;
import com.datastrato.graviton.rel.Schema;
+import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
-import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
/** An abstract class representing a base schema in a relational database. */
-@EqualsAndHashCode
@ToString
public class BaseSchema implements Schema, Entity, HasIdentifier {
@@ -127,6 +126,28 @@ public class BaseSchema implements Schema, Entity, HasIdentifier {
return EntityType.SCHEMA;
}
+ // Ignore field namespace and comment
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ BaseSchema schema = (BaseSchema) o;
+ return Objects.equal(id, schema.id)
+ && Objects.equal(catalogId, schema.catalogId)
+ && Objects.equal(name, schema.name)
+ && Objects.equal(properties, schema.properties)
+ && Objects.equal(auditInfo, schema.auditInfo);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(id, catalogId, name, properties, auditInfo);
+ }
+
/**
* Builder interface for creating instances of {@link BaseSchema}.
*
diff --git a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java
index c72a5858d2..c6311955c7 100644
--- a/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java
+++ b/core/src/main/java/com/datastrato/graviton/meta/rel/BaseTable.java
@@ -12,15 +12,14 @@ import com.datastrato.graviton.Namespace;
import com.datastrato.graviton.meta.AuditInfo;
import com.datastrato.graviton.rel.Column;
import com.datastrato.graviton.rel.Table;
+import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import java.util.Map;
import javax.annotation.Nullable;
-import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
/** An abstract class representing a base table in a relational database. */
-@EqualsAndHashCode
@ToString
public class BaseTable implements Table, Entity, HasIdentifier {
@@ -145,6 +144,29 @@ public class BaseTable implements Table, Entity, HasIdentifier {
return EntityType.TABLE;
}
+ // Ignore field namespace, columns and comment
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ BaseTable baseTable = (BaseTable) o;
+ return Objects.equal(id, baseTable.id)
+ && Objects.equal(schemaId, baseTable.schemaId)
+ && Objects.equal(name, baseTable.name)
+ && Objects.equal(properties, baseTable.properties)
+ && Objects.equal(auditInfo, baseTable.auditInfo);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(id, schemaId, name, properties, auditInfo);
+ }
+
/**
* Builder interface for creating instances of {@link BaseTable}.
*
diff --git a/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java
index 3ff96188f3..50340d4bd5 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java
@@ -20,6 +20,15 @@ public interface EntityKeyEncoder<T> {
* @throws IOException, Exception if error occurs
*/
default T encode(NameIdentifier ident, EntityType type) throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ return encode(ident, type, false);
}
+
+ /**
+ * Construct the key for key-value store from the entity NameIdentifier and EntityType.
+ *
+ * @param nullIfMissing return null if the specific entity no found
+ * @return encoded key for key-value stored
+ * @throws IOException, Exception if error occurs
+ */
+ T encode(NameIdentifier ident, EntityType type, boolean nullIfMissing) throws IOException;
}
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java
index d506bad4f3..c987318083 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java
@@ -16,10 +16,15 @@ import com.datastrato.graviton.storage.NameMappingService;
import com.datastrato.graviton.utils.ByteUtils;
import com.datastrato.graviton.utils.Bytes;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
+import java.util.Arrays;
import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,17 +52,20 @@ import org.slf4j.LoggerFactory;
public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
public static final Logger LOG = LoggerFactory.getLogger(BinaryEntityKeyEncoder.class);
- @VisibleForTesting static final byte[] NAMESPACE_SEPARATOR = "_".getBytes();
+ public static final String NAMESPACE_SEPARATOR = "/";
- @VisibleForTesting static final String WILD_CARD = "*";
+ @VisibleForTesting
+ static final byte[] BYTABLE_NAMESPACE_SEPARATOR = NAMESPACE_SEPARATOR.getBytes();
+
+ static final String WILD_CARD = "*";
// Key format template. Please the comment of the class for more details.
public static final Map<EntityType, String[]> ENTITY_TYPE_TO_NAME_IDENTIFIER =
ImmutableMap.of(
- METALAKE, new String[] {METALAKE.getShortName() + "_"},
- CATALOG, new String[] {CATALOG.getShortName() + "_", "_"},
- SCHEMA, new String[] {SCHEMA.getShortName() + "_", "_", "_"},
- TABLE, new String[] {TABLE.getShortName() + "_", "_", "_", "_"});
+ METALAKE, new String[] {METALAKE.getShortName() + "/"},
+ CATALOG, new String[] {CATALOG.getShortName() + "/", "/"},
+ SCHEMA, new String[] {SCHEMA.getShortName() + "/", "/", "/"},
+ TABLE, new String[] {TABLE.getShortName() + "/", "/", "/", "/"});
@VisibleForTesting final NameMappingService nameMappingService;
@@ -65,19 +73,35 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
this.nameMappingService = nameMappingService;
}
+ private String generateMappingKey(long[] namespaceIds, String name) {
+ String context =
+ Joiner.on(NAMESPACE_SEPARATOR)
+ .join(
+ Arrays.stream(namespaceIds).mapToObj(String::valueOf).collect(Collectors.toList()));
+ return StringUtils.isBlank(context) ? name : context + NAMESPACE_SEPARATOR + name;
+ }
+
/**
* Encode entity key for KV backend, e.g., RocksDB. The key is used to store the entity in the
* backend.
*
* @param identifier NameIdentifier of the entity
* @param entityType the entity identifier to encode
- * @return the encoded key for key-value storage
+ * @param nullIfMissing reutrn null if name-id mapping does not contain the mapping of identifier
+ * @return the encoded key for key-value storage. null if returnIfEntityNotFound is true and the
+ * entity the identifier represents does not exist;
*/
- private byte[] encodeEntity(NameIdentifier identifier, EntityType entityType) throws IOException {
+ private byte[] encodeEntity(
+ NameIdentifier identifier, EntityType entityType, boolean nullIfMissing) throws IOException {
String[] nameSpace = identifier.namespace().levels();
long[] namespaceIds = new long[nameSpace.length];
for (int i = 0; i < nameSpace.length; i++) {
- namespaceIds[i] = nameMappingService.getOrCreateIdFromName(nameSpace[i]);
+ String nameKey = generateMappingKey(ArrayUtils.subarray(namespaceIds, 0, i), nameSpace[i]);
+ if (nullIfMissing && null == nameMappingService.getIdByName(nameKey)) {
+ return null;
+ }
+
+ namespaceIds[i] = nameMappingService.getOrCreateIdFromName(nameKey);
}
// If the name is a wildcard, We only need to encode the namespace.
@@ -92,8 +116,12 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
// This is for point query and need to use specific name
long[] namespaceAndNameIds = new long[namespaceIds.length + 1];
System.arraycopy(namespaceIds, 0, namespaceAndNameIds, 0, namespaceIds.length);
- namespaceAndNameIds[namespaceIds.length] =
- nameMappingService.getOrCreateIdFromName(identifier.name());
+ String nameKey = generateMappingKey(namespaceIds, identifier.name());
+ if (nullIfMissing && null == nameMappingService.getIdByName(nameKey)) {
+ return null;
+ }
+
+ namespaceAndNameIds[namespaceIds.length] = nameMappingService.getOrCreateIdFromName(nameKey);
String[] nameIdentifierTemplate = ENTITY_TYPE_TO_NAME_IDENTIFIER.get(entityType);
if (nameIdentifierTemplate == null) {
@@ -104,7 +132,7 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
/**
* Format the name space template to a byte array. For example, if the name space template is
- * "ca_{}_" and the ids are [1], the result is "ca_1_" which means we want to get all catalogs in
+ * "ca/{}/" and the ids are [1], the result is "ca/1/" which means we want to get all catalogs in
* metalake '1'
*
* @param namespaceTemplate the name space template, please see {@link
@@ -128,7 +156,7 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
/**
* Format the name identifier to a byte array. For example, if the name space template is
- * "ca_{}_{}" and the ids is [1, 2], the result is "ca_1_2" which means we want to get the
+ * "ca/{}/{}" and the ids is [1, 2], the result is "ca/1/2" which means we want to get the
* specific catalog '2'
*
* @param nameIdentifierTemplate the name space template, please see {@link
@@ -151,10 +179,12 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
*
* @param ident NameIdentifier of the entity
* @param type the entity identifier to encode
+ * @param nullIfMissing return null if the entity with the name 'ident' not found
* @return The byte array representing the encoded key.
*/
@Override
- public byte[] encode(NameIdentifier ident, EntityType type) throws IOException {
- return encodeEntity(ident, type);
+ public byte[] encode(NameIdentifier ident, EntityType type, boolean nullIfMissing)
+ throws IOException {
+ return encodeEntity(ident, type, nullIfMissing);
}
}
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java
index 0deb496604..c12e7905d7 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java
@@ -55,6 +55,15 @@ public interface KvBackend extends Closeable {
return false;
}
+ /**
+ * Delete the key-value pair associated with the given {@link KvRangeScan}
+ *
+ * @param kvRangeScan kv range to to delete
+ * @return True if the key-value pair was successfully deleted.
+ * @throws IOException If an I/O exception occurs during deletion.
+ */
+ boolean deleteRange(KvRangeScan kvRangeScan) throws IOException;
+
/**
* Scans the specified range using the provided KvRangeScan and returns a list of key-value pairs.
*
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java
index edbaa1a299..4206144152 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java
@@ -6,6 +6,11 @@
package com.datastrato.graviton.storage.kv;
import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;
+import static com.datastrato.graviton.Entity.EntityType.CATALOG;
+import static com.datastrato.graviton.Entity.EntityType.SCHEMA;
+import static com.datastrato.graviton.Entity.EntityType.TABLE;
+import static com.datastrato.graviton.storage.kv.BinaryEntityKeyEncoder.LOG;
+import static com.datastrato.graviton.storage.kv.BinaryEntityKeyEncoder.NAMESPACE_SEPARATOR;
import com.datastrato.graviton.Config;
import com.datastrato.graviton.Entity;
@@ -16,25 +21,34 @@ import com.datastrato.graviton.EntityStore;
import com.datastrato.graviton.HasIdentifier;
import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.exceptions.AlreadyExistsException;
import com.datastrato.graviton.exceptions.NoSuchEntityException;
+import com.datastrato.graviton.exceptions.NonEmptyEntityException;
import com.datastrato.graviton.storage.EntityKeyEncoder;
import com.datastrato.graviton.storage.NameMappingService;
import com.datastrato.graviton.utils.Bytes;
import com.datastrato.graviton.utils.Executable;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
+import java.util.stream.Collectors;
import lombok.Getter;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * KV store to store entities. This means we can store entities in a key value store. I.e. RocksDB,
+ * KV store to store entities. This means we can store entities in a key value store. I.e., RocksDB,
* Cassandra, etc. If you want to use a different backend, you can implement the {@link KvBackend}
* interface
*/
@@ -45,6 +59,7 @@ public class KvEntityStore implements EntityStore {
@Getter @VisibleForTesting private KvBackend backend;
private EntityKeyEncoder<byte[]> entityKeyEncoder;
+ private NameMappingService nameMappingService;
private EntitySerDe serDe;
@Override
@@ -52,7 +67,7 @@ public class KvEntityStore implements EntityStore {
this.backend = createKvEntityBackend(config);
// TODO(yuqi) Currently, KvNameMappingSerivice and KvEntityStore shares the same backend
// instance, We should make it configurable in the future.
- NameMappingService nameMappingService = new KvNameMappingService(backend);
+ this.nameMappingService = new KvNameMappingService(backend);
this.entityKeyEncoder = new BinaryEntityKeyEncoder(nameMappingService);
}
@@ -65,8 +80,13 @@ public class KvEntityStore implements EntityStore {
public <E extends Entity & HasIdentifier> List<E> list(
Namespace namespace, Class<E> e, EntityType type) throws IOException {
// Star means it's a wildcard
- NameIdentifier identifier = NameIdentifier.of(namespace, "*");
- byte[] startKey = entityKeyEncoder.encode(identifier, type);
+ List<E> entities = Lists.newArrayList();
+ NameIdentifier identifier = NameIdentifier.of(namespace, BinaryEntityKeyEncoder.WILD_CARD);
+ byte[] startKey = entityKeyEncoder.encode(identifier, type, true);
+ if (startKey == null) {
+ return entities;
+ }
+
byte[] endKey = Bytes.increment(Bytes.wrap(startKey)).get();
List<Pair<byte[], byte[]>> kvs =
backend.scan(
@@ -78,7 +98,6 @@ public class KvEntityStore implements EntityStore {
.limit(Integer.MAX_VALUE)
.build());
- List<E> entities = Lists.newArrayList();
for (Pair<byte[], byte[]> pairs : kvs) {
entities.add(serDe.deserialize(pairs.getRight(), e));
}
@@ -88,7 +107,12 @@ public class KvEntityStore implements EntityStore {
@Override
public boolean exists(NameIdentifier ident, EntityType entityType) throws IOException {
- return backend.get(entityKeyEncoder.encode(ident, entityType)) != null;
+ byte[] key = entityKeyEncoder.encode(ident, entityType, true);
+ if (key == null) {
+ return false;
+ }
+
+ return backend.get(key) != null;
}
@Override
@@ -102,7 +126,7 @@ public class KvEntityStore implements EntityStore {
@Override
public <E extends Entity & HasIdentifier> E update(
NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)
- throws IOException, NoSuchEntityException {
+ throws IOException, NoSuchEntityException, AlreadyExistsException {
byte[] key = entityKeyEncoder.encode(ident, entityType);
return executeInTransaction(
() -> {
@@ -113,20 +137,96 @@ public class KvEntityStore implements EntityStore {
E e = serDe.deserialize(value, type);
E updatedE = updater.apply(e);
- if (!updatedE.nameIdentifier().equals(ident)) {
- delete(ident, entityType);
+ if (updatedE.nameIdentifier().equals(ident)) {
+ backend.put(key, serDe.serialize(updatedE), true);
+ return updatedE;
}
- put(updatedE, true /* overwritten */);
+ // If we have changed the name of the entity, We would do the following steps:
+ // Check whether the new entities already exitsed
+ boolean newEntityExist = exists(updatedE.nameIdentifier(), entityType);
+ if (newEntityExist) {
+ throw new AlreadyExistsException(
+ String.format(
+ "Entity %s already exist, please check again", updatedE.nameIdentifier()));
+ }
+
+ // Update the name mapping
+ nameMappingService.updateName(
+ generateKeyForMapping(ident), generateKeyForMapping(updatedE.nameIdentifier()));
+
+ // Update the entity to store
+ backend.put(key, serDe.serialize(updatedE), true);
return updatedE;
});
}
+ private String concatIdAndName(long[] namespaceIds, String name) {
+ String context =
+ Joiner.on(NAMESPACE_SEPARATOR)
+ .join(
+ Arrays.stream(namespaceIds).mapToObj(String::valueOf).collect(Collectors.toList()));
+ return StringUtils.isBlank(context) ? name : context + NAMESPACE_SEPARATOR + name;
+ }
+
+ /**
+ * Generate the key for name to id mapping. Currently, the mapping is as following.
+ *
+ * <pre>
+ * Assume we have the following entities:
+ * metalake: a1 ----> 1
+ * catalog : a1.b1 ----> 2
+ * schema : a1.b1.c ----> 3
+ *
+ * metalake: a2 ----> 4
+ * catalog : a2.b2 ----> 5
+ * schema : a2.b2.c ----> 6
+ * schema : a2.b2.c1 ----> 7
+ *
+ * metalake: a1 ----> 1 means the name of metalake is a1 and the corresponding id is 1
+ * </pre>
+ *
+ * Then we will store the name to id mapping as follows
+ *
+ * <pre>
+ * a1 --> 1
+ * 1/b1 --> 2
+ * 1/2/c --> 3
+ * a2 --> 4
+ * 4/b2 --> 5
+ * 4/5/c --> 6
+ * 4/5/c1 --> 7
+ * </pre>
+ *
+ * @param nameIdentifier name of a specific entity
+ * @return key that maps to the id of a specific entity. See above, The key maybe like '4/5/c1'
+ */
+ public String generateKeyForMapping(NameIdentifier nameIdentifier) throws IOException {
+ if (nameIdentifier.namespace().isEmpty()) {
+ return nameIdentifier.name();
+ }
+ Namespace namespace = nameIdentifier.namespace();
+ String name = nameIdentifier.name();
+
+ long[] ids = new long[namespace.length()];
+ for (int i = 0; i < ids.length; i++) {
+ ids[i] =
+ nameMappingService.getIdByName(
+ concatIdAndName(ArrayUtils.subarray(ids, 0, i), namespace.level(i)));
+ }
+
+ return concatIdAndName(ids, name);
+ }
+
@Override
public <E extends Entity & HasIdentifier> E get(
NameIdentifier ident, EntityType entityType, Class<E> e)
throws NoSuchEntityException, IOException {
- byte[] key = entityKeyEncoder.encode(ident, entityType);
+ byte[] key = entityKeyEncoder.encode(ident, entityType, true);
+ if (key == null) {
+ throw new NoSuchEntityException(ident.toString());
+ }
+
byte[] value = backend.get(key);
if (value == null) {
throw new NoSuchEntityException(ident.toString());
@@ -134,9 +234,101 @@ public class KvEntityStore implements EntityStore {
return serDe.deserialize(value, e);
}
+ /**
+ * Get key prefix of all sub-entities under a specific entities. For example, as a metalake will
+ * start with `ml_{metalake_id}`, sub-entities under this metalake will have the prefix
+ *
+ * <pre>
+ * catalog: ca_{metalake_id}
+ * schema: sc_{metalake_id}
+ * table: ta_{metalake_id}
+ * </pre>
+ *
+ * Why the sub-entities under this metalake start with those prefixes, please see {@link
+ * KvEntityStore} java class doc.
+ *
+ * @param ident identifier of an entity
+ * @param type type of entity
+ * @return list of sub-entities prefix
+ * @throws IOException if error occurs
+ */
+ private List<byte[]> getSubEntitiesPrefix(NameIdentifier ident, EntityType type)
+ throws IOException {
+ List<byte[]> prefixs = Lists.newArrayList();
+ byte[] encode = entityKeyEncoder.encode(ident, type, true);
+ switch (type) {
+ case METALAKE:
+ prefixs.add(replacePrefixTypeInfo(encode, CATALOG.getShortName()));
+ prefixs.add(replacePrefixTypeInfo(encode, SCHEMA.getShortName()));
+ prefixs.add(replacePrefixTypeInfo(encode, TABLE.getShortName()));
+ break;
+ case CATALOG:
+ prefixs.add(replacePrefixTypeInfo(encode, SCHEMA.getShortName()));
+ prefixs.add(replacePrefixTypeInfo(encode, TABLE.getShortName()));
+ break;
+ case SCHEMA:
+ prefixs.add(replacePrefixTypeInfo(encode, TABLE.getShortName()));
+ break;
+ case TABLE:
+ break;
+ default:
+ LOG.warn("Currently unknow type: {}, please check it", type);
+ }
+ Collections.reverse(prefixs);
+ return prefixs;
+ }
+
+ private byte[] replacePrefixTypeInfo(byte[] encode, String subTypePrefix) {
+ byte[] result = new byte[encode.length];
+ System.arraycopy(encode, 0, result, 0, encode.length);
+ byte[] bytes = subTypePrefix.getBytes();
+ result[0] = bytes[0];
+ result[1] = bytes[1];
+
+ return result;
+ }
+
@Override
- public boolean delete(NameIdentifier ident, EntityType entityType) throws IOException {
- return backend.delete(entityKeyEncoder.encode(ident, entityType));
+ public boolean delete(NameIdentifier ident, EntityType entityType, boolean cascade)
+ throws IOException {
+ byte[] dataKey = entityKeyEncoder.encode(ident, entityType, true);
+ if (dataKey == null) {
+ return true;
+ }
+
+ List<byte[]> subEntityPrefix = getSubEntitiesPrefix(ident, entityType);
+ if (subEntityPrefix.isEmpty()) {
+ // has no sub-entities
+ return backend.delete(dataKey);
+ }
+
+ byte[] directChild = Iterables.getLast(subEntityPrefix);
+ byte[] endKey = Bytes.increment(Bytes.wrap(directChild)).get();
+ List<Pair<byte[], byte[]>> kvs =
+ backend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start(directChild)
+ .end(endKey)
+ .startInclusive(true)
+ .endInclusive(false)
+ .limit(1)
+ .build());
+
+ if (!cascade && !kvs.isEmpty()) {
+ throw new NonEmptyEntityException(
+ String.format("Entity %s has sub-entities, you should remove sub-entities first", ident));
+ }
+
+ for (byte[] prefix : subEntityPrefix) {
+ backend.deleteRange(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start(prefix)
+ .startInclusive(true)
+ .end(Bytes.increment(Bytes.wrap(prefix)).get())
+ .build());
+ }
+
+ return backend.delete(dataKey);
}
@Override
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java b/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java
index a5c2421666..8d25305783 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java
@@ -189,7 +189,6 @@ public class RocksDBKvBackend implements KvBackend {
TX_LOCAL.get().delete(key);
return true;
}
-
db.delete(key);
return true;
} catch (RocksDBException e) {
@@ -197,6 +196,39 @@ public class RocksDBKvBackend implements KvBackend {
}
}
+ @Override
+ public boolean deleteRange(KvRangeScan deleteRange) throws IOException {
+ Transaction tx = TX_LOCAL.get();
+ RocksIterator rocksIterator = tx == null ? db.newIterator() : tx.getIterator(new ReadOptions());
+ rocksIterator.seek(deleteRange.getStart());
+
+ while (rocksIterator.isValid()) {
+ byte[] key = rocksIterator.key();
+ // Break if the key is out of the scan range
+ if (Bytes.wrap(key).compareTo(deleteRange.getEnd()) > 0) {
+ break;
+ }
+
+ if (Bytes.wrap(key).compareTo(deleteRange.getStart()) == 0) {
+ if (deleteRange.isStartInclusive()) {
+ delete(key);
+ }
+ } else if (Bytes.wrap(key).compareTo(deleteRange.getEnd()) == 0) {
+ if (deleteRange.isEndInclusive()) {
+ delete(key);
+ }
+ break;
+ } else {
+ delete(key);
+ }
+
+ rocksIterator.next();
+ }
+
+ rocksIterator.close();
+ return true;
+ }
+
@Override
public void close() throws IOException {
db.close();
@@ -205,7 +237,14 @@ public class RocksDBKvBackend implements KvBackend {
@Override
public <R, E extends Exception> R executeInTransaction(Executable<R, E> executable)
throws E, IOException {
- Transaction tx = db.beginTransaction(new WriteOptions());
+ // TODO (yuqi) Name mapping service and storage should use separtately backend, or we should
+ // handle nested transaction
+ Transaction tx = TX_LOCAL.get();
+ if (tx != null) {
+ return executable.execute();
+ }
+
+ tx = db.beginTransaction(new WriteOptions());
LOGGER.info("Starting transaction: id: '{}'", tx.getID());
TX_LOCAL.set(tx);
try {
diff --git a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java b/core/src/test/java/com/datastrato/graviton/TestEntityStore.java
index b108233ec5..6baa794aa9 100644
--- a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java
+++ b/core/src/test/java/com/datastrato/graviton/TestEntityStore.java
@@ -115,7 +115,8 @@ public class TestEntityStore {
}
@Override
- public boolean delete(NameIdentifier ident, EntityType entityType) throws IOException {
+ public boolean delete(NameIdentifier ident, EntityType entityType, boolean cascade)
+ throws IOException {
Entity prev = entityMap.remove(ident);
return prev != null;
}
diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java
index 501a0297cb..51d2a220b3 100644
--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java
+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java
@@ -9,7 +9,7 @@ import static com.datastrato.graviton.Configs.DEFUALT_ENTITY_KV_STORE;
import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;
import static com.datastrato.graviton.Configs.ENTITY_STORE;
import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
-import static com.datastrato.graviton.storage.kv.BinaryEntityKeyEncoder.NAMESPACE_SEPARATOR;
+import static com.datastrato.graviton.storage.kv.BinaryEntityKeyEncoder.BYTABLE_NAMESPACE_SEPARATOR;
import static com.datastrato.graviton.storage.kv.BinaryEntityKeyEncoder.WILD_CARD;
import com.datastrato.graviton.Config;
@@ -111,7 +111,7 @@ public class TestEntityKeyEncoding {
byte[] expenctKey =
Bytes.concat(
EntityType.METALAKE.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L));
Assertions.assertArrayEquals(expenctKey, realKey);
@@ -133,9 +133,9 @@ public class TestEntityKeyEncoding {
expenctKey =
Bytes.concat(
EntityType.CATALOG.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(1L + i));
Assertions.assertArrayEquals(expenctKey, realKey);
}
@@ -158,11 +158,11 @@ public class TestEntityKeyEncoding {
expenctKey =
Bytes.concat(
EntityType.SCHEMA.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(2L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(4L + i));
Assertions.assertArrayEquals(expenctKey, realKey);
}
@@ -185,13 +185,13 @@ public class TestEntityKeyEncoding {
expenctKey =
Bytes.concat(
EntityType.TABLE.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(2L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(6L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(i + 7L));
Assertions.assertArrayEquals(expenctKey, realKey);
}
@@ -219,7 +219,7 @@ public class TestEntityKeyEncoding {
NameIdentifier metalakeIdentifier = NameIdentifier.of(namespace, WILD_CARD);
byte[] realKey = ENCODER.encode(metalakeIdentifier, EntityType.METALAKE);
byte[] expenctKey =
- Bytes.concat(EntityType.METALAKE.getShortName().getBytes(), NAMESPACE_SEPARATOR);
+ Bytes.concat(EntityType.METALAKE.getShortName().getBytes(), BYTABLE_NAMESPACE_SEPARATOR);
Assertions.assertArrayEquals(expenctKey, realKey);
// Scan all catalog in metalake1
@@ -231,9 +231,9 @@ public class TestEntityKeyEncoding {
expenctKey =
Bytes.concat(
EntityType.CATALOG.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L),
- NAMESPACE_SEPARATOR);
+ BYTABLE_NAMESPACE_SEPARATOR);
Assertions.assertArrayEquals(expenctKey, realKey);
// Scan all sc in metalake1.catalog2
@@ -245,11 +245,11 @@ public class TestEntityKeyEncoding {
expenctKey =
Bytes.concat(
EntityType.SCHEMA.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(1L),
- NAMESPACE_SEPARATOR);
+ BYTABLE_NAMESPACE_SEPARATOR);
Assertions.assertArrayEquals(expenctKey, realKey);
// Scan all table in metalake1.catalog2.schema3
@@ -261,13 +261,13 @@ public class TestEntityKeyEncoding {
expenctKey =
Bytes.concat(
EntityType.TABLE.getShortName().getBytes(),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(0L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(1L),
- NAMESPACE_SEPARATOR,
+ BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(2L),
- NAMESPACE_SEPARATOR);
+ BYTABLE_NAMESPACE_SEPARATOR);
Assertions.assertArrayEquals(expenctKey, realKey);
Mockito.doReturn(3L).when(mockIdGenerator).nextId();
diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java
deleted file mode 100644
index 24dc305623..0000000000
--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Copyright 2023 Datastrato.
- * This software is licensed under the Apache License version 2.
- */
-
-package com.datastrato.graviton.storage.kv;
-
-import static com.datastrato.graviton.Configs.DEFUALT_ENTITY_KV_STORE;
-import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;
-import static com.datastrato.graviton.Configs.ENTITY_STORE;
-import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
-
-import com.datastrato.graviton.Catalog.Type;
-import com.datastrato.graviton.Config;
-import com.datastrato.graviton.Configs;
-import com.datastrato.graviton.Entity.EntityType;
-import com.datastrato.graviton.EntityAlreadyExistsException;
-import com.datastrato.graviton.EntitySerDeFactory;
-import com.datastrato.graviton.EntityStore;
-import com.datastrato.graviton.EntityStoreFactory;
-import com.datastrato.graviton.Metalake;
-import com.datastrato.graviton.Namespace;
-import com.datastrato.graviton.exceptions.NoSuchEntityException;
-import com.datastrato.graviton.meta.AuditInfo;
-import com.datastrato.graviton.meta.BaseMetalake;
-import com.datastrato.graviton.meta.CatalogEntity;
-import com.datastrato.graviton.meta.SchemaVersion;
-import java.time.Instant;
-import java.util.List;
-import org.apache.commons.io.FileUtils;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-
-public class TestEntityStorageBackend {
- public static final String ROCKS_DB_STORE_PATH = "/tmp/graviton";
-
- @BeforeEach
- @AfterEach
- public void cleanEnv() {
- try {
- FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));
- } catch (Exception e) {
- // Ignore
- }
- }
-
- @Test
- public void testCreateKvEntityStore() {
- Config config = Mockito.mock(Config.class);
- Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
- Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFUALT_ENTITY_KV_STORE);
- Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
- Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/graviton");
-
- try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
- store.initialize(config);
- Assertions.assertTrue(store instanceof KvEntityStore);
- store.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));
-
- AuditInfo auditInfo =
- new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
-
- BaseMetalake metalake =
- new BaseMetalake.Builder()
- .withId(1L)
- .withName("metalake")
- .withAuditInfo(auditInfo)
- .withVersion(SchemaVersion.V_0_1)
- .build();
-
- BaseMetalake metalakeCopy =
- new BaseMetalake.Builder()
- .withId(1L)
- .withName("metalakeCopy")
- .withAuditInfo(auditInfo)
- .withVersion(SchemaVersion.V_0_1)
- .build();
-
- CatalogEntity catalog =
- new CatalogEntity.Builder()
- .withId(1L)
- .withName("catalog")
- .withNamespace(Namespace.of("metalake"))
- .withType(Type.RELATIONAL)
- .withMetalakeId(1L)
- .withAuditInfo(auditInfo)
- .build();
-
- CatalogEntity catalogCopy =
- new CatalogEntity.Builder()
- .withId(1L)
- .withName("catalogCopy")
- .withNamespace(Namespace.of("metalake"))
- .withType(Type.RELATIONAL)
- .withMetalakeId(1L)
- .withAuditInfo(auditInfo)
- .build();
- CatalogEntity catalogCopyAgain =
- new CatalogEntity.Builder()
- .withId(1L)
- .withName("catalogCopyAgain")
- .withNamespace(Namespace.of("metalake"))
- .withType(Type.RELATIONAL)
- .withMetalakeId(1L)
- .withAuditInfo(auditInfo)
- .build();
-
- // First, we try to test transactional is OK
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
- try {
- store.executeInTransaction(
- () -> {
- store.put(metalake);
- // Try to mock an exception
- double a = 1 / 0;
- store.put(catalog);
- return null;
- });
- } catch (Exception e) {
- Assertions.assertTrue(e instanceof ArithmeticException);
- }
-
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
-
- store.executeInTransaction(
- () -> {
- store.put(metalake);
- store.put(catalog);
- store.put(metalakeCopy);
- store.put(catalogCopy);
- store.put(catalogCopyAgain);
- return null;
- });
-
- Metalake retrievedMetalake =
- store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);
- Assertions.assertEquals(metalake, retrievedMetalake);
- CatalogEntity retrievedCatalog =
- store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);
- Assertions.assertEquals(catalog, retrievedCatalog);
- Metalake retrievedMetalakeCopy =
- store.get(metalakeCopy.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);
- Assertions.assertEquals(metalakeCopy, retrievedMetalakeCopy);
- CatalogEntity retrievedCatalogCopy =
- store.get(catalogCopy.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);
- Assertions.assertEquals(catalogCopy, retrievedCatalogCopy);
-
- // Test scan and store list interface
- List<CatalogEntity> catalogEntityList =
- store.list(catalog.namespace(), CatalogEntity.class, EntityType.CATALOG);
- Assertions.assertEquals(3, catalogEntityList.size());
- Assertions.assertTrue(catalogEntityList.contains(catalog));
- Assertions.assertTrue(catalogEntityList.contains(catalogCopy));
- Assertions.assertTrue(catalogEntityList.contains(catalogCopyAgain));
-
- store.delete(metalake.nameIdentifier(), EntityType.METALAKE);
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
-
- Assertions.assertThrows(EntityAlreadyExistsException.class, () -> store.put(catalog, false));
- store.delete(catalog.nameIdentifier(), EntityType.CATALOG);
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () -> store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));
-
- // Test update
- BaseMetalake updatedMetalake =
- new BaseMetalake.Builder()
- .withId(metalake.getId())
- .withName("updatedMetalake")
- .withAuditInfo(auditInfo)
- .withVersion(SchemaVersion.V_0_1)
- .build();
- store.put(metalake);
- store.update(
- metalake.nameIdentifier(), BaseMetalake.class, EntityType.METALAKE, l -> updatedMetalake);
- Assertions.assertEquals(
- updatedMetalake,
- store.get(updatedMetalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
- Assertions.assertThrows(
- NoSuchEntityException.class,
- () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
-
- // Add new updateMetaLake.
- // 'updatedMetalake2' is a new name, which will trigger id allocation
- BaseMetalake updatedMetalake2 =
- new BaseMetalake.Builder()
- .withId(metalake.getId())
- .withName("updatedMetalake2")
- .withAuditInfo(auditInfo)
- .withVersion(SchemaVersion.V_0_1)
- .build();
- store.put(updatedMetalake2);
- } catch (Exception e) {
- Assertions.fail(e.getMessage());
- }
- }
-}
diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.java
new file mode 100644
index 0000000000..f41a1888a1
--- /dev/null
+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvEntityStorage.java
@@ -0,0 +1,725 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.storage.kv;
+
+import static com.datastrato.graviton.Configs.DEFUALT_ENTITY_KV_STORE;
+import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;
+import static com.datastrato.graviton.Configs.ENTITY_STORE;
+import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
+
+import com.datastrato.graviton.Catalog.Type;
+import com.datastrato.graviton.Config;
+import com.datastrato.graviton.Configs;
+import com.datastrato.graviton.Entity.EntityType;
+import com.datastrato.graviton.EntityAlreadyExistsException;
+import com.datastrato.graviton.EntitySerDeFactory;
+import com.datastrato.graviton.EntityStore;
+import com.datastrato.graviton.EntityStoreFactory;
+import com.datastrato.graviton.Metalake;
+import com.datastrato.graviton.NameIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.exceptions.AlreadyExistsException;
+import com.datastrato.graviton.exceptions.NoSuchEntityException;
+import com.datastrato.graviton.exceptions.NonEmptyEntityException;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.meta.BaseMetalake;
+import com.datastrato.graviton.meta.CatalogEntity;
+import com.datastrato.graviton.meta.SchemaVersion;
+import com.datastrato.graviton.meta.rel.BaseSchema;
+import com.datastrato.graviton.meta.rel.BaseTable;
+import com.datastrato.graviton.rel.Column;
+import io.substrait.type.TypeCreator;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.time.Instant;
+import java.util.List;
+import org.apache.commons.io.FileUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class TestKvEntityStorage {
+ public static final String ROCKS_DB_STORE_PATH = "/tmp/graviton";
+
+ @BeforeEach
+ @AfterEach
+ public void cleanEnv() {
+ try {
+ FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));
+ } catch (Exception e) {
+ // Ignore
+ }
+ }
+
+ static class MockSchemaBuilder
+ extends BaseSchema.BaseSchemaBuilder<MockSchemaBuilder, BaseSchema> {
+ @Override
+ protected BaseSchema internalBuild() {
+ BaseSchema baseSchema = new BaseSchema();
+ try {
+ setField(baseSchema, "id", id);
+ setField(baseSchema, "catalogId", catalogId);
+ setField(baseSchema, "namespace", namespace);
+ setField(baseSchema, "name", name);
+ setField(baseSchema, "comment", comment);
+ setField(baseSchema, "properties", properties);
+ setField(baseSchema, "auditInfo", auditInfo);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return baseSchema;
+ }
+
+ private void setField(BaseSchema object, String fieldName, Object value)
+ throws NoSuchFieldException, IllegalAccessException {
+ Field field = object.getClass().getDeclaredField(fieldName);
+ field.setAccessible(true);
+ field.set(object, value);
+ }
+ }
+
+ static class MockTableBuilder extends BaseTable.BaseTableBuilder<MockTableBuilder, BaseTable> {
+
+ @Override
+ protected BaseTable internalBuild() {
+ BaseTable baseTable = new BaseTable();
+ try {
+ setField(baseTable, "id", id);
+ setField(baseTable, "schemaId", schemaId);
+ setField(baseTable, "namespace", namespace);
+ setField(baseTable, "name", name);
+ setField(baseTable, "comment", comment);
+ setField(baseTable, "properties", properties);
+ setField(baseTable, "auditInfo", auditInfo);
+ setField(baseTable, "columns", columns);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return baseTable;
+ }
+
+ private void setField(BaseTable object, String fieldName, Object value)
+ throws NoSuchFieldException, IllegalAccessException {
+ Field field = object.getClass().getDeclaredField(fieldName);
+ field.setAccessible(true);
+ field.set(object, value);
+ }
+ }
+
+ public BaseMetalake createBaseMakeLake(String name, AuditInfo auditInfo) {
+ return new BaseMetalake.Builder()
+ .withId(1L)
+ .withName(name)
+ .withAuditInfo(auditInfo)
+ .withVersion(SchemaVersion.V_0_1)
+ .build();
+ }
+
+ public CatalogEntity createCatalog(Namespace namespace, String name, AuditInfo auditInfo) {
+ return new CatalogEntity.Builder()
+ .withId(1L)
+ .withName(name)
+ .withNamespace(namespace)
+ .withType(Type.RELATIONAL)
+ .withMetalakeId(1L)
+ .withAuditInfo(auditInfo)
+ .build();
+ }
+
+ public BaseSchema createBaseschema(Namespace namespace, String name, AuditInfo auditInfo) {
+ return new MockSchemaBuilder()
+ .withId(1L)
+ .withName(name)
+ .withCatalogId(1L)
+ .withNamespace(namespace)
+ .withAuditInfo(auditInfo)
+ .withComment("a schmea")
+ .build();
+ }
+
+ public BaseTable createBaseTable(Namespace namespace, String name, AuditInfo auditInfo) {
+ return new MockTableBuilder()
+ .withId(1L)
+ .withSchemaId(1L)
+ .withName(name)
+ .withNameSpace(namespace)
+ .withAuditInfo(auditInfo)
+ .withComment("a table")
+ .withColumns(
+ new Column[] {
+ new Column() {
+ @Override
+ public String name() {
+ return "test";
+ }
+
+ @Override
+ public io.substrait.type.Type dataType() {
+ return TypeCreator.NULLABLE.I32;
+ }
+
+ @Override
+ public String comment() {
+ return "test";
+ }
+ }
+ })
+ .build();
+ }
+
+ @Test
+ void testEntityUpdate() throws Exception {
+ Config config = Mockito.mock(Config.class);
+ Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
+ Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFUALT_ENTITY_KV_STORE);
+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/graviton");
+
+ AuditInfo auditInfo =
+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ store.initialize(config);
+ Assertions.assertTrue(store instanceof KvEntityStore);
+ store.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));
+
+ BaseMetalake metalake = createBaseMakeLake("metalake", auditInfo);
+ CatalogEntity catalog = createCatalog(Namespace.of("metalake"), "catalog", auditInfo);
+ CatalogEntity catalogCopy = createCatalog(Namespace.of("metalake"), "catalogCopy", auditInfo);
+ BaseSchema schema1 =
+ createBaseschema(Namespace.of("metalake", "catalog"), "schema1", auditInfo);
+ BaseTable table1 =
+ createBaseTable(Namespace.of("metalake", "catalog", "schema1"), "table1", auditInfo);
+
+ BaseSchema schema2 =
+ createBaseschema(Namespace.of("metalake", "catalog"), "schema2", auditInfo);
+ BaseTable table1InSchema2 =
+ createBaseTable(Namespace.of("metalake", "catalog", "schema2"), "table1", auditInfo);
+
+ // Store all entities
+ store.put(metalake);
+ store.put(catalog);
+ store.put(catalogCopy);
+ store.put(schema1);
+ store.put(schema2);
+ store.put(table1);
+ store.put(table1InSchema2);
+
+ // Try to check an update option is what exepct
+ store.update(
+ metalake.nameIdentifier(),
+ BaseMetalake.class,
+ EntityType.METALAKE,
+ e -> {
+ AuditInfo auditInfo1 =
+ new AuditInfo.Builder()
+ .withCreator("creator1")
+ .withCreateTime(Instant.now())
+ .build();
+ return createBaseMakeLake("metalakeChanged", auditInfo1);
+ });
+
+ // Check metalake entity and subenties are already changed.
+ BaseMetalake updatedMetalake =
+ store.get(NameIdentifier.of("metalakeChanged"), EntityType.METALAKE, BaseMetalake.class);
+ Assertions.assertEquals("creator1", updatedMetalake.auditInfo().creator());
+
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () -> store.get(NameIdentifier.of("metalake"), EntityType.METALAKE, BaseMetalake.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalog"),
+ EntityType.CATALOG,
+ CatalogEntity.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalog", "schema1"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalog", "schema1", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalog", "schema2"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalog", "schema1", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+
+ // Check catalog entitis and sub-entities are already changed.
+ store.update(
+ NameIdentifier.of("metalakeChanged", "catalog"),
+ CatalogEntity.class,
+ EntityType.CATALOG,
+ e -> {
+ AuditInfo auditInfo1 =
+ new AuditInfo.Builder()
+ .withCreator("creator2")
+ .withCreateTime(Instant.now())
+ .build();
+ return createCatalog(Namespace.of("metalakeChanged"), "catalogChanged", auditInfo1);
+ });
+ CatalogEntity updatedCatalog =
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged"),
+ EntityType.CATALOG,
+ CatalogEntity.class);
+ Assertions.assertEquals("creator2", updatedCatalog.auditInfo().creator());
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () ->
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalog"),
+ EntityType.CATALOG,
+ CatalogEntity.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+
+ // Check schema entitis and sub-entities are already changed.
+ store.update(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1"),
+ BaseSchema.class,
+ EntityType.SCHEMA,
+ e -> {
+ AuditInfo auditInfo1 =
+ new AuditInfo.Builder()
+ .withCreator("creator3")
+ .withCreateTime(Instant.now())
+ .build();
+ return createBaseschema(
+ Namespace.of("metalakeChanged", "catalogChanged"), "schemaChanged", auditInfo1);
+ });
+
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () ->
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ BaseSchema updatedSchema =
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged"),
+ EntityType.SCHEMA,
+ BaseSchema.class);
+ Assertions.assertEquals("creator3", updatedSchema.auditInfo().creator());
+
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),
+ EntityType.SCHEMA,
+ BaseSchema.class));
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+
+ // Check table entities
+ store.update(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schemaChanged", "table1"),
+ BaseTable.class,
+ EntityType.TABLE,
+ e -> {
+ AuditInfo auditInfo1 =
+ new AuditInfo.Builder()
+ .withCreator("creator4")
+ .withCreateTime(Instant.now())
+ .build();
+ return createBaseTable(
+ Namespace.of("metalakeChanged", "catalogChanged", "schemaChanged"),
+ "tableChanged",
+ auditInfo1);
+ });
+
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () ->
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema1", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+ BaseTable updatedTable =
+ store.get(
+ NameIdentifier.of(
+ "metalakeChanged", "catalogChanged", "schemaChanged", "tableChanged"),
+ EntityType.TABLE,
+ BaseTable.class);
+ Assertions.assertEquals("creator4", updatedTable.auditInfo().creator());
+
+ Assertions.assertNotNull(
+ store.get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),
+ EntityType.TABLE,
+ BaseTable.class));
+
+ store.delete(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),
+ EntityType.TABLE);
+ // Update a deleted entities
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () ->
+ store.update(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2", "table1"),
+ BaseTable.class,
+ EntityType.TABLE,
+ (e) -> e));
+ // The updated entities already existed, should throw exception
+ Assertions.assertThrowsExactly(
+ AlreadyExistsException.class,
+ () ->
+ store.update(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),
+ BaseSchema.class,
+ EntityType.SCHEMA,
+ e -> {
+ AuditInfo auditInfo1 =
+ new AuditInfo.Builder()
+ .withCreator("creator5")
+ .withCreateTime(Instant.now())
+ .build();
+ return createBaseschema(
+ Namespace.of("metalakeChanged", "catalogChanged"),
+ "schemaChanged",
+ auditInfo1);
+ }));
+ // Update operations do not conatin any changes in name
+ store.update(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),
+ BaseSchema.class,
+ EntityType.SCHEMA,
+ e -> {
+ AuditInfo auditInfo1 =
+ new AuditInfo.Builder()
+ .withCreator("creator6")
+ .withCreateTime(Instant.now())
+ .build();
+ return createBaseschema(
+ Namespace.of("metalakeChanged", "catalogChanged"), "schema2", auditInfo1);
+ });
+ Assertions.assertEquals(
+ "creator6",
+ store
+ .get(
+ NameIdentifier.of("metalakeChanged", "catalogChanged", "schema2"),
+ EntityType.SCHEMA,
+ BaseSchema.class)
+ .auditInfo()
+ .creator());
+ }
+ }
+
+ @Test
+ void testEntityDelete() throws IOException {
+ // TODO
+ Config config = Mockito.mock(Config.class);
+ Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
+ Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFUALT_ENTITY_KV_STORE);
+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/graviton");
+
+ AuditInfo auditInfo =
+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ store.initialize(config);
+ Assertions.assertTrue(store instanceof KvEntityStore);
+ store.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));
+
+ BaseMetalake metalake = createBaseMakeLake("metalake", auditInfo);
+ CatalogEntity catalog = createCatalog(Namespace.of("metalake"), "catalog", auditInfo);
+ CatalogEntity catalogCopy = createCatalog(Namespace.of("metalake"), "catalogCopy", auditInfo);
+
+ BaseSchema schema1 =
+ createBaseschema(Namespace.of("metalake", "catalog"), "schema1", auditInfo);
+ BaseTable table1 =
+ createBaseTable(Namespace.of("metalake", "catalog", "schema1"), "table1", auditInfo);
+
+ BaseSchema schema2 =
+ createBaseschema(Namespace.of("metalake", "catalog"), "schema2", auditInfo);
+ BaseTable table1InSchema2 =
+ createBaseTable(Namespace.of("metalake", "catalog", "schema2"), "table1", auditInfo);
+
+ // Store all entities
+ store.put(metalake);
+ store.put(catalog);
+ store.put(catalogCopy);
+ store.put(schema1);
+ store.put(schema2);
+ store.put(table1);
+ store.put(table1InSchema2);
+
+ // Now try to get
+ Assertions.assertEquals(
+ metalake, store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
+ Assertions.assertEquals(
+ catalog, store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));
+ Assertions.assertEquals(
+ catalogCopy,
+ store.get(catalogCopy.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));
+ Assertions.assertEquals(
+ schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));
+ Assertions.assertEquals(
+ schema2, store.get(schema2.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));
+ Assertions.assertEquals(
+ table1, store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class));
+ Assertions.assertEquals(
+ table1InSchema2,
+ store.get(table1InSchema2.nameIdentifier(), EntityType.TABLE, BaseTable.class));
+
+ // Delete the table 'metalake.catalog.schema2.table1'
+ store.delete(table1InSchema2.nameIdentifier(), EntityType.TABLE);
+ Assertions.assertFalse(store.exists(table1InSchema2.nameIdentifier(), EntityType.TABLE));
+ // Make sure table 'metalake.catalog.schema1.table1' still exist;
+ Assertions.assertEquals(
+ table1, store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class));
+ // Make sure schema 'metalake.catalog.schema2' still exist;
+ Assertions.assertEquals(
+ schema2, store.get(schema2.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));
+ // Re-insert table1Inschema2 and everything is OK
+ store.put(table1InSchema2);
+ Assertions.assertTrue(store.exists(table1InSchema2.nameIdentifier(), EntityType.TABLE));
+
+ // Delete the schema 'metalake.catalog.schema1' but failed, because it ha sub-entities;
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(schema1.nameIdentifier(), EntityType.SCHEMA));
+ // Make sure schema 'metalake.catalog.schema1' and table 'metalake.catalog.schema1.table1'
+ // has not been deleted yet;
+ Assertions.assertTrue(store.exists(schema1.nameIdentifier(), EntityType.SCHEMA));
+ Assertions.assertTrue(store.exists(table1.nameIdentifier(), EntityType.TABLE));
+
+ // Delete table1 and schema1
+ store.delete(table1.nameIdentifier(), EntityType.TABLE);
+ store.delete(schema1.nameIdentifier(), EntityType.SCHEMA);
+ // Make sure table1 in 'metalake.catalog.schema1' can't be access;
+ Assertions.assertFalse(store.exists(table1.nameIdentifier(), EntityType.TABLE));
+ Assertions.assertFalse(store.exists(schema1.nameIdentifier(), EntityType.SCHEMA));
+ // Now we re-insert table1 and schema1, and everything should be OK
+ store.put(schema1);
+ store.put(table1);
+ Assertions.assertEquals(
+ schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));
+ Assertions.assertEquals(
+ table1, store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class));
+
+ // Now try to delete all schemas under catalog;
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(catalog.nameIdentifier(), EntityType.CATALOG));
+ store.delete(table1.nameIdentifier(), EntityType.TABLE);
+ store.delete(schema1.nameIdentifier(), EntityType.SCHEMA);
+ store.delete(table1InSchema2.nameIdentifier(), EntityType.TABLE);
+ store.delete(schema2.nameIdentifier(), EntityType.SCHEMA);
+
+ store.delete(catalog.nameIdentifier(), EntityType.CATALOG);
+ Assertions.assertFalse(store.exists(catalog.nameIdentifier(), EntityType.CATALOG));
+
+ // Now delete catalog 'catalogCopy' and metalake
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(metalake.nameIdentifier(), EntityType.METALAKE));
+ store.delete(catalogCopy.nameIdentifier(), EntityType.CATALOG);
+ Assertions.assertFalse(store.exists(catalogCopy.nameIdentifier(), EntityType.CATALOG));
+
+ store.delete(metalake.nameIdentifier(), EntityType.METALAKE);
+ Assertions.assertFalse(store.exists(metalake.nameIdentifier(), EntityType.METALAKE));
+
+ // Store all entities again
+ store.put(metalake);
+ store.put(catalog);
+ store.put(catalogCopy);
+ store.put(schema1);
+ store.put(schema2);
+ store.put(table1);
+ store.put(table1InSchema2);
+
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(schema1.nameIdentifier(), EntityType.SCHEMA));
+
+ Assertions.assertEquals(
+ schema1, store.get(schema1.nameIdentifier(), EntityType.SCHEMA, BaseSchema.class));
+
+ // Test cascade delete
+ store.delete(schema1.nameIdentifier(), EntityType.SCHEMA, true);
+ try {
+ store.get(table1.nameIdentifier(), EntityType.TABLE, BaseTable.class);
+ } catch (Exception e) {
+ Assertions.assertTrue(e instanceof NoSuchEntityException);
+ Assertions.assertTrue(e.getMessage().contains("metalake.catalog.schema1"));
+ }
+
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(catalog.nameIdentifier(), EntityType.CATALOG));
+ store.delete(catalog.nameIdentifier(), EntityType.CATALOG, true);
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () -> store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));
+
+ Assertions.assertThrowsExactly(
+ NoSuchEntityException.class,
+ () -> store.get(schema2.nameIdentifier(), EntityType.SCHEMA, CatalogEntity.class));
+ }
+ }
+
+ @Test
+ void testCreateKvEntityStore() {
+ Config config = Mockito.mock(Config.class);
+ Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
+ Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFUALT_ENTITY_KV_STORE);
+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/graviton");
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ store.initialize(config);
+ Assertions.assertTrue(store instanceof KvEntityStore);
+ store.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));
+
+ AuditInfo auditInfo =
+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ BaseMetalake metalake = createBaseMakeLake("metalake", auditInfo);
+ BaseMetalake metalakeCopy = createBaseMakeLake("metalakeCopy", auditInfo);
+ CatalogEntity catalog = createCatalog(Namespace.of("metalake"), "catalog", auditInfo);
+ CatalogEntity catalogCopy = createCatalog(Namespace.of("metalake"), "catalogCopy", auditInfo);
+ CatalogEntity catalogCopyAgain =
+ createCatalog(Namespace.of("metalake"), "catalogCopyAgain", auditInfo);
+
+ // First, we try to test transactional is OK
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
+ try {
+ store.executeInTransaction(
+ () -> {
+ store.put(metalake);
+ // Try to mock an exception
+ double a = 1 / 0;
+ store.put(catalog);
+ return null;
+ });
+ } catch (Exception e) {
+ Assertions.assertTrue(e instanceof ArithmeticException);
+ }
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
+
+ store.executeInTransaction(
+ () -> {
+ store.put(metalake);
+ store.put(catalog);
+ store.put(metalakeCopy);
+ store.put(catalogCopy);
+ store.put(catalogCopyAgain);
+ return null;
+ });
+
+ Metalake retrievedMetalake =
+ store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);
+ Assertions.assertEquals(metalake, retrievedMetalake);
+ CatalogEntity retrievedCatalog =
+ store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);
+ Assertions.assertEquals(catalog, retrievedCatalog);
+ Metalake retrievedMetalakeCopy =
+ store.get(metalakeCopy.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);
+ Assertions.assertEquals(metalakeCopy, retrievedMetalakeCopy);
+ CatalogEntity retrievedCatalogCopy =
+ store.get(catalogCopy.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);
+ Assertions.assertEquals(catalogCopy, retrievedCatalogCopy);
+
+ // Test scan and store list interface
+ List<CatalogEntity> catalogEntityList =
+ store.list(catalog.namespace(), CatalogEntity.class, EntityType.CATALOG);
+ Assertions.assertEquals(3, catalogEntityList.size());
+ Assertions.assertTrue(catalogEntityList.contains(catalog));
+ Assertions.assertTrue(catalogEntityList.contains(catalogCopy));
+ Assertions.assertTrue(catalogEntityList.contains(catalogCopyAgain));
+
+ Assertions.assertThrows(EntityAlreadyExistsException.class, () -> store.put(catalog, false));
+ store.delete(catalog.nameIdentifier(), EntityType.CATALOG);
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));
+
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class, () -> store.put(catalogCopy, false));
+ store.delete(catalogCopy.nameIdentifier(), EntityType.CATALOG);
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(catalogCopy.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));
+
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(metalake.nameIdentifier(), EntityType.METALAKE));
+ store.delete(catalogCopyAgain.nameIdentifier(), EntityType.CATALOG);
+ Assertions.assertTrue(store.delete(metalake.nameIdentifier(), EntityType.METALAKE));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
+
+ // Test update
+ BaseMetalake updatedMetalake = createBaseMakeLake("updatedMetalake", auditInfo);
+ store.put(metalake);
+ store.update(
+ metalake.nameIdentifier(), BaseMetalake.class, EntityType.METALAKE, l -> updatedMetalake);
+ Assertions.assertEquals(
+ updatedMetalake,
+ store.get(updatedMetalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));
+
+ // Add new updateMetaLake.
+ // 'updatedMetalake2' is a new name, which will trigger id allocation
+ BaseMetalake updatedMetalake2 = createBaseMakeLake("updatedMetalake2", auditInfo);
+ store.put(updatedMetalake2);
+ } catch (Exception e) {
+ Assertions.fail(e.getMessage());
+ }
+ }
+}
diff --git a/rfc/rfc-2/Entity-key-encoding-for-kv-store.md b/rfc/rfc-2/Entity-key-encoding-for-kv-store.md
index 0d61adc109..c83fb37823 100644
--- a/rfc/rfc-2/Entity-key-encoding-for-kv-store.md
+++ b/rfc/rfc-2/Entity-key-encoding-for-kv-store.md
@@ -5,9 +5,10 @@
# RFC-1: Enity Key Encoding design for KV store
-| Revision | Owner |
-| :------- |-------|
-| v0.1 | Qi Yu |
+| Revision | Owner | Date |
+| :------- |-------| ------|
+| v0.1 | Qi Yu | 1/8/2023|
+| v0.2 | Qi Yu | 5/9/2023|
## Background
Currently, there will be many data to storage, for example,
@@ -33,26 +34,27 @@ According to the picture above, Metadata in graviton can be divided into multipl
### Target
We should design a key encoding method to encode the key of KV store that should satisfy the following requirements:
-- Support fast point query
-- Support efficient range query
+- Support fast point queries
+- Support efficient range queries
- Not very complicated
- Good expandability and compatibility
### Design
-Firstly, we introduce a global auto-increment ID that reprents the name of namespace. This ID is unique in the whole system.
-For example, if there exists a catalog named `catalog1` with namepace name `metalake1`, we will add the following key-value pair to KV store
+Firstly, we introduce a global auto-increment ID (or simply a UUID) that reprents the name of namespace. This ID is unique in the whole system.
+For example, if there exists a catalog named `catalog1` with namepace name `metalake1`, and a schema name `schema3` under `catalog2`, then we will add the following key-value pair to KV store
-| Key | Value | Description |
-|:----------|-----------|----------------------------------------------------------------|
-| metalake1 | 1 | name to id mapping |
-| catalog2 | 2 | name to id mapping |
-| 1 | metalake1 | id to name mapping |
-| 2 | catalog2 | id to name mapping |
- | current_max_id | 2 | Storage current max id, next avaiable id is current max id + 1 |
+| Key | Value | Description |
+|:------------|-------------|----------------------------------------------|
+| metalake1 | 1 | name to id mapping, |
+| 1/catalog2 | 2 | name to id mapping, 1 is the id of metalake1 |
+| 1/2/schema3 | 3 | name to id mapping, 2 is the id of catalog2 |
+| 1 | metalake1 | id to name mapping |
+| 2 | 1/catalog2 | id to name mapping |
+| 3 | 1/2/schema3 | id to name mapping |
-Attention, For `catalog` and `makelake`, Considering the global uniqueness, we will use a UUID instead of auto-increment ID.
+Note, for `catalog` and `makelake`, Considering the global uniqueness, we will use a UUID instead of auto-increment ID.
`schema`, `table` and other entities will use auto-increment ID.
@@ -63,21 +65,21 @@ Why we introduce this global auto-increment ID? Because we want to support the f
Then, The whole key of entity can be encoded as the following format
-| Key | Value | Description |
-|:-------------------------------------------------|---------------|---------------------------------|
-| ml_{ml_id} | matalake info | ml is a short name for metalake |
-| ml_{ml_id} | matalake info | ml is a short name for metalake |
-| ca_{ml_id}_{ca_id} | catalog_info | ca is a short name for catalog |
-| ca_{ml_id}_{ca_id} | catalog_info | ca is a short name for catalog |
-| sc_{ml_id}\_{ca_id}_{sc_id} | schema_info | sc is a short name for schema |
-| sc_{ml_id}\_{ca_id}_{sc_id} | schema_info | sc is a short name for schema |
-| br_{ml_id}\_{ca_id}_{br_id} | broker_info | br is a short name for broker |
-| br_{ml_id}\_{ca_id}_{br_id} | broker_info | br is a short name for broker |
-| ta_{ml_id}\_{catalog_id}\_{schema_id}_{table_id} | table_info | ta is a short name for table |
-| to_{ml_id}\_{catalog_id}\_{br_id}_{topic_id} | topic_info | to is a short name for topic |
+| Key | Value | Description |
+|:-----------------------------------------------|---------------|---------------------------------|
+| ml/{ml_id} | matalake info | ml is a short name for metalake |
+| ml/{ml_id} | matalake info | ml is a short name for metalake |
+| ca/{ml_id}/{ca_id} | catalog_info | ca is a short name for catalog |
+| ca/{ml_id}/{ca_id} | catalog_info | ca is a short name for catalog |
+| sc/{ml_id}/{ca_id}/{sc_id} | schema_info | sc is a short name for schema |
+| sc/{ml_id}/{ca_id}/{sc_id} | schema_info | sc is a short name for schema |
+| br/{ml_id}/{ca_id}/{br_id} | broker_info | br is a short name for broker |
+| br/{ml_id}/{ca_id}/{br_id} | broker_info | br is a short name for broker |
+| ta/{ml_id}/{catalog_id}/{schema_id}/{table_id} | table_info | ta is a short name for table |
+| to/{ml_id}/{catalog_id}/{br_id}/{topic_id} | topic_info | to is a short name for topic |
## Implementation
-Please see code ```CustomKeyEncoder```
+Please see code ```BinaryEntityKeyEncoder```