World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#798]feat(common): Add JSON serde for new type system (#799)
mchades01a104fd71b8
diff --git a/api/src/main/java/com/datastrato/gravitino/rel/types/Types.java b/api/src/main/java/com/datastrato/gravitino/rel/types/Types.javaindex e5e0aca802..766690f75b 100644--- a/api/src/main/java/com/datastrato/gravitino/rel/types/Types.java+++ b/api/src/main/java/com/datastrato/gravitino/rel/types/Types.java@@ -602,11 +602,6 @@ public class Types {return of(name, type, true, comment);}- /** Returns a nullable {@link Field} with the given name, type and empty comment. */- public static Field of(String name, Type type) {- return of(name, type, true, null);- }-/** Returns a nullable {@link Field} with the given name, type and comment. */public static Field of(String name, Type type, boolean nullable, String comment) {return new Field(name, type, nullable, comment);diff --git a/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java b/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.javaindex 0ca1fd0e5a..b1a09e10d7 100644--- a/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java+++ b/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java@@ -27,6 +27,8 @@ import com.datastrato.gravitino.rel.TableChange;import com.datastrato.gravitino.rel.expressions.distributions.Strategy;import com.datastrato.gravitino.rel.expressions.sorts.NullOrdering;import com.datastrato.gravitino.rel.expressions.sorts.SortDirection;+import com.datastrato.gravitino.rel.types.Type;+import com.datastrato.gravitino.rel.types.Types;import com.fasterxml.jackson.core.JacksonException;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonParser;@@ -43,14 +45,17 @@ import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableList;+import com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;+import com.google.common.collect.Maps;import io.substrait.type.StringTypeVisitor;-import io.substrait.type.Type;import io.substrait.type.parser.ParseToPojo;import io.substrait.type.parser.TypeStringParser;import java.io.IOException;import java.util.Iterator;import java.util.List;+import java.util.regex.Matcher;+import java.util.regex.Pattern;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -76,6 +81,46 @@ public class JsonUtils {private static final String DIRECTION = "direction";private static final String NULL_ORDERING = "nullOrdering";private static final String NUMBER = "number";+ private static final String TYPE = "type";+ private static final String STRUCT = "struct";+ private static final String LIST = "list";+ private static final String MAP = "map";+ private static final String UNION = "union";+ private static final String FIELDS = "fields";+ private static final String UNION_TYPES = "types";+ private static final String STRUCT_FIELD_NAME = "name";+ private static final String STRUCT_FIELD_NULLABLE = "nullable";+ private static final String STRUCT_FIELD_COMMENT = "comment";+ private static final String LIST_ELEMENT_NULLABLE = "containsNull";+ private static final String LIST_ELEMENT_TYPE = "elementType";+ private static final String MAP_KEY_TYPE = "keyType";+ private static final String MAP_VALUE_TYPE = "valueType";+ private static final String MAP_VALUE_NULLABLE = "valueContainsNull";+ private static final ImmutableMap<String, Type.PrimitiveType> TYPES =+ Maps.uniqueIndex(+ ImmutableList.of(+ Types.BooleanType.get(),+ Types.ByteType.get(),+ Types.ShortType.get(),+ Types.IntegerType.get(),+ Types.LongType.get(),+ Types.FloatType.get(),+ Types.DoubleType.get(),+ Types.DateType.get(),+ Types.TimeType.get(),+ Types.TimestampType.withTimeZone(),+ Types.TimestampType.withoutTimeZone(),+ Types.StringType.get(),+ Types.UUIDType.get(),+ Types.BinaryType.get(),+ Types.IntervalYearType.get(),+ Types.IntervalDayType.get()),+ Type.PrimitiveType::simpleString);+ private static final Pattern FIXED = Pattern.compile("fixed\\(\\s*(\\d+)\\s*\\)");+ private static final Pattern FIXEDCHAR = Pattern.compile("char\\(\\s*(\\d+)\\s*\\)");+ private static final Pattern VARCHAR = Pattern.compile("varchar\\(\\s*(\\d+)\\s*\\)");+ private static final Pattern DECIMAL =+ Pattern.compile("decimal\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");/*** Abstract iterator class for iterating over elements of a JSON array.@@ -227,7 +272,8 @@ public class JsonUtils {node.has(LITERAL_VALUE),"Cannot parse literal arg from missing literal value: %s",node);- Type dataType = TypeStringParser.parse(getString(DATA_TYPE, node), ParseToPojo::type);+ io.substrait.type.Type dataType =+ TypeStringParser.parse(getString(DATA_TYPE, node), ParseToPojo::type);String value = getString(LITERAL_VALUE, node);return new LiteralDTO.Builder().withDataType(dataType).withValue(value).build();case FIELD:@@ -308,15 +354,286 @@ public class JsonUtils {return pNode.asText();}+ /**+ * Write Gravitino Type to JSON node property. Usd for Gravity Type JSON serialization.+ *+ * @param dataType Gravitino Type+ * @param gen JSON generator used to write the type+ * @throws IOException if the type cannot be written+ */+ private static void writeDataType(Type dataType, JsonGenerator gen) throws IOException {+ switch (dataType.name()) {+ case BOOLEAN:+ case BYTE:+ case SHORT:+ case INTEGER:+ case LONG:+ case FLOAT:+ case DOUBLE:+ case DECIMAL:+ case DATE:+ case TIME:+ case TIMESTAMP:+ case STRING:+ case FIXEDCHAR:+ case VARCHAR:+ case INTERVAL_DAY:+ case INTERVAL_YEAR:+ case UUID:+ case FIXED:+ case BINARY:+ // Primitive types are serialized as string+ gen.writeString(dataType.simpleString());+ break;+ case STRUCT:+ writeStructType((Types.StructType) dataType, gen);+ break;+ case LIST:+ writeListType((Types.ListType) dataType, gen);+ break;+ case MAP:+ writeMapType((Types.MapType) dataType, gen);+ break;+ case UNION:+ writeUnionType((Types.UnionType) dataType, gen);+ break;+ default:+ throw new IOException("Cannot serialize unknown type: " + dataType);+ }+ }++ /**+ * Read Gravitino Type from JSON node property. Used for Gravity Type JSON deserialization.+ *+ * @param node JSON node containing the type+ * @return Gravitino Type+ */+ private static Type readDataType(JsonNode node) {+ Preconditions.checkArgument(+ node != null && !node.isNull(), "Cannot parse type from invalid JSON: %s", node);++ if (node.isTextual()) {+ return fromPrimitiveTypeString(node.asText().toLowerCase());+ }++ if (node.isObject() && node.get(TYPE) != null) {+ JsonNode typeField = node.get(TYPE);+ String type = typeField.asText();++ if (STRUCT.equals(type)) {+ return readStructType(node);+ }++ if (LIST.equals(type)) {+ return readListType(node);+ }++ if (MAP.equals(type)) {+ return readMapType(node);+ }++ if (UNION.equals(type)) {+ return readUnionType(node);+ }+ }++ throw new IllegalArgumentException("Cannot parse type from JSON: " + node);+ }++ private static void writeUnionType(Types.UnionType unionType, JsonGenerator gen)+ throws IOException {+ gen.writeStartObject();++ gen.writeStringField(TYPE, UNION);+ gen.writeArrayFieldStart(UNION_TYPES);+ for (Type type : unionType.types()) {+ writeDataType(type, gen);+ }+ gen.writeEndArray();++ gen.writeEndObject();+ }++ private static void writeMapType(Types.MapType mapType, JsonGenerator gen) throws IOException {+ gen.writeStartObject();++ gen.writeStringField(TYPE, MAP);+ gen.writeBooleanField(MAP_VALUE_NULLABLE, mapType.valueNullable());+ gen.writeFieldName(MAP_KEY_TYPE);+ writeDataType(mapType.keyType(), gen);+ gen.writeFieldName(MAP_VALUE_TYPE);+ writeDataType(mapType.valueType(), gen);++ gen.writeEndObject();+ }++ private static void writeListType(Types.ListType listType, JsonGenerator gen) throws IOException {+ gen.writeStartObject();++ gen.writeStringField(TYPE, LIST);+ gen.writeBooleanField(LIST_ELEMENT_NULLABLE, listType.elementNullable());+ gen.writeFieldName(LIST_ELEMENT_TYPE);+ writeDataType(listType.elementType(), gen);++ gen.writeEndObject();+ }++ private static void writeStructType(Types.StructType structType, JsonGenerator gen)+ throws IOException {+ gen.writeStartObject();++ gen.writeStringField(TYPE, STRUCT);+ gen.writeArrayFieldStart(FIELDS);+ for (Types.StructType.Field field : structType.fields()) {+ writeStructField(field, gen);+ }+ gen.writeEndArray();++ gen.writeEndObject();+ }++ private static void writeStructField(Types.StructType.Field field, JsonGenerator gen)+ throws IOException {+ gen.writeStartObject();+ gen.writeStringField(STRUCT_FIELD_NAME, field.name());+ gen.writeFieldName(TYPE);+ writeDataType(field.type(), gen);+ gen.writeBooleanField(STRUCT_FIELD_NULLABLE, field.nullable());+ if (field.comment() != null) {+ gen.writeStringField(STRUCT_FIELD_COMMENT, field.comment());+ }+ gen.writeEndObject();+ }++ private static Type.PrimitiveType fromPrimitiveTypeString(String typeString) {+ Type.PrimitiveType primitiveType = TYPES.get(typeString);+ if (primitiveType != null) {+ return primitiveType;+ }++ Matcher fixed = FIXED.matcher(typeString);+ if (fixed.matches()) {+ return Types.FixedType.of(Integer.parseInt(fixed.group(1)));+ }++ Matcher fixedChar = FIXEDCHAR.matcher(typeString);+ if (fixedChar.matches()) {+ return Types.FixedCharType.of(Integer.parseInt(fixedChar.group(1)));+ }++ Matcher varchar = VARCHAR.matcher(typeString);+ if (varchar.matches()) {+ return Types.VarCharType.of(Integer.parseInt(varchar.group(1)));+ }++ Matcher decimal = DECIMAL.matcher(typeString);+ if (decimal.matches()) {+ return Types.DecimalType.of(+ Integer.parseInt(decimal.group(1)), Integer.parseInt(decimal.group(2)));+ }++ throw new IllegalArgumentException("Cannot parse type string to primitiveType: " + typeString);+ }++ private static Types.StructType readStructType(JsonNode node) {+ JsonNode fields = node.get(FIELDS);+ Preconditions.checkArgument(+ fields != null && fields.isArray(),+ "Cannot parse struct fields from non-array: %s",+ fields);++ List<Types.StructType.Field> structFields = Lists.newArrayListWithExpectedSize(fields.size());+ for (JsonNode field : fields) {+ structFields.add(readStructField(field));+ }+ return Types.StructType.of(structFields.toArray(new Types.StructType.Field[0]));+ }++ private static Types.ListType readListType(JsonNode node) {+ Preconditions.checkArgument(+ node.has(LIST_ELEMENT_TYPE), "Cannot parse list type from missing element type: %s", node);++ Type elementType = readDataType(node.get(LIST_ELEMENT_TYPE));+ // use true as default value for nullable+ boolean nullable =+ node.has(LIST_ELEMENT_NULLABLE) ? node.get(LIST_ELEMENT_NULLABLE).asBoolean() : true;+ return Types.ListType.of(elementType, nullable);+ }++ private static Types.MapType readMapType(JsonNode node) {+ Preconditions.checkArgument(+ node.has(MAP_KEY_TYPE), "Cannot parse map type from missing key type: %s", node);+ Preconditions.checkArgument(+ node.has(MAP_VALUE_TYPE), "Cannot parse map type from missing value type: %s", node);++ Type keyType = readDataType(node.get(MAP_KEY_TYPE));+ Type valueType = readDataType(node.get(MAP_VALUE_TYPE));+ boolean nullable =+ node.has(MAP_VALUE_NULLABLE) ? node.get(MAP_VALUE_NULLABLE).asBoolean() : true;+ return Types.MapType.of(keyType, valueType, nullable);+ }++ private static Types.UnionType readUnionType(JsonNode node) {+ Preconditions.checkArgument(+ node.has(UNION_TYPES), "Cannot parse union type from missing types: %s", node);++ JsonNode types = node.get(UNION_TYPES);+ Preconditions.checkArgument(+ types != null && types.isArray(), "Cannot parse union types from non-array: %s", types);++ List<Type> unionTypes = Lists.newArrayListWithExpectedSize(types.size());+ for (JsonNode type : types) {+ unionTypes.add(readDataType(type));+ }+ return Types.UnionType.of(unionTypes.toArray(new Type[0]));+ }++ private static Types.StructType.Field readStructField(JsonNode node) {+ Preconditions.checkArgument(+ node != null && !node.isNull() && node.isObject(),+ "Cannot parse struct field from invalid JSON: %s",+ node);+ Preconditions.checkArgument(+ node.has(STRUCT_FIELD_NAME), "Cannot parse struct field from missing name: %s", node);+ Preconditions.checkArgument(+ node.has(TYPE), "Cannot parse struct field from missing type: %s", node);++ String name = getString(STRUCT_FIELD_NAME, node);+ Type type = readDataType(node.get(TYPE));+ // use true as default value for nullable+ boolean nullable =+ node.has(STRUCT_FIELD_NULLABLE) ? node.get(STRUCT_FIELD_NULLABLE).asBoolean() : true;+ String comment = node.has(STRUCT_FIELD_COMMENT) ? getString(STRUCT_FIELD_COMMENT, node) : null;+ return Types.StructType.Field.of(name, type, nullable, comment);+ }+// Nested classes for custom serialization and deserialization- /** Custom JSON serializer for Substrait Type objects. */+ /** Custom JSON serializer for Gravitino Type objects. */+ public static class GravitinoTypeSerializer extends JsonSerializer<Type> {+ @Override+ public void serialize(Type value, JsonGenerator gen, SerializerProvider serializers)+ throws IOException {+ writeDataType(value, gen);+ }+ }++ /** Custom JSON deserializer for Gravitino Type objects. */+ public static class GravitinoTypeDeserializer extends JsonDeserializer<Type> {++ @Override+ public Type deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {+ return readDataType(p.getCodec().readTree(p));+ }+ }+public static class TypeSerializer extends JsonSerializer<io.substrait.type.Type> {private final StringTypeVisitor visitor = new StringTypeVisitor();@Override- public void serialize(Type value, JsonGenerator gen, SerializerProvider serializers)+ public void serialize(+ io.substrait.type.Type value, JsonGenerator gen, SerializerProvider serializers)throws IOException {try {gen.writeString(value.accept(visitor));@@ -331,7 +648,8 @@ public class JsonUtils {public static class TypeDeserializer extends JsonDeserializer<io.substrait.type.Type> {@Override- public Type deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {+ public io.substrait.type.Type deserialize(JsonParser p, DeserializationContext ctxt)+ throws IOException {String s = p.getValueAsString();try {return TypeStringParser.parse(s, ParseToPojo::type);diff --git a/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java b/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.javaindex 91009813cf..6e0b9f61c9 100644--- a/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java+++ b/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java@@ -8,19 +8,28 @@ import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;+import com.datastrato.gravitino.rel.types.Type;+import com.datastrato.gravitino.rel.types.Types;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.module.SimpleModule;import java.util.List;-import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;public class TestJsonUtils {- private ObjectMapper objectMapper;+ private static ObjectMapper objectMapper;- @BeforeEach- void setUp() {+ @BeforeAll+ static void setUp() {objectMapper = JsonUtils.objectMapper();+ // TODO(minghuang): remove this once the old type serializer/deserializer is replaced.+ SimpleModule module = new SimpleModule();+ module.addSerializer(Type.class, new JsonUtils.GravitinoTypeSerializer());+ module.addDeserializer(Type.class, new JsonUtils.GravitinoTypeDeserializer());+ objectMapper.registerModule(module);}@Test@@ -49,4 +58,94 @@ public class TestJsonUtils {result = JsonUtils.getStringListOrNull("unknown", node);assertNull(result);}++ @Test+ public void testTypeSerDe() throws Exception {+ Type type = Types.BooleanType.get();+ String jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ String expected = "\"boolean\"";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.TimestampType.withTimeZone();+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected = "\"timestamp_tz\"";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.FixedType.of(10);+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected = "\"fixed(10)\"";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.FixedCharType.of(20);+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected = "\"char(20)\"";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.VarCharType.of(30);+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected = "\"varchar(30)\"";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.DecimalType.of(10, 2);+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected = "\"decimal(10,2)\"";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type =+ Types.StructType.of(+ Types.StructType.Field.nullableField("name", Types.StringType.get(), "name field"),+ Types.StructType.Field.notNullField("id", Types.IntegerType.get()));+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected =+ "{\n"+ + " \"type\": \"struct\",\n"+ + " \"fields\": [\n"+ + " {\n"+ + " \"name\": \"name\",\n"+ + " \"type\": \"string\",\n"+ + " \"nullable\": true,\n"+ + " \"comment\": \"name field\"\n"+ + " },\n"+ + " {\n"+ + " \"name\": \"id\",\n"+ + " \"type\": \"integer\",\n"+ + " \"nullable\": false\n"+ + " }\n"+ + " ]\n"+ + "}";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.ListType.notNull(Types.FloatType.get());+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected =+ "{\n"+ + " \"type\": \"list\",\n"+ + " \"containsNull\": false,\n"+ + " \"elementType\": \"float\"\n"+ + "}";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.MapType.valueNullable(Types.ShortType.get(), Types.DateType.get());+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected =+ "{\n"+ + " \"type\": \"map\",\n"+ + " \"keyType\": \"short\",\n"+ + " \"valueType\": \"date\",\n"+ + " \"valueContainsNull\": true\n"+ + "}";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));++ type = Types.UnionType.of(Types.DecimalType.of(20, 8), Types.VarCharType.of(10));+ jsonValue = JsonUtils.objectMapper().writeValueAsString(type);+ expected =+ "{\n"+ + " \"type\": \"union\",\n"+ + " \"types\": [\n"+ + " \"decimal(20,8)\",\n"+ + " \"varchar(10)\"\n"+ + " ]\n"+ + "}";+ Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));+ }}