Skip to content

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

[#13338] fix(lance): Preserve Lance blob columns as readable external types (#13390)

FANNG14b0e7d818f5
diff --git a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java
index 4d9c3dceda..1ed701113b 100644
--- a/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/main/java/org/apache/gravitino/catalog/lakehouse/lance/LanceTableOperations.java
@@ -72,6 +72,7 @@ import org.apache.gravitino.utils.ExceptionMessages;
import org.apache.gravitino.utils.PrincipalUtils;
import org.lance.Dataset;
import org.lance.ReadOptions;
+import org.lance.WriteDatasetBuilder;
import org.lance.WriteParams;
import org.lance.index.DistanceType;
import org.lance.index.IndexOptions;
@@ -419,13 +420,7 @@ public class LanceTableOperations extends ManagedTableOperations {
Map<String, String> storageProps =
LancePropertiesUtils.resolveLanceStorageOptions(catalogProperties, properties);
- try (Dataset ignored =
- Dataset.write()
- .schema(convertColumnsToArrowSchema(columns))
- .uri(location)
- .mode(WriteParams.WriteMode.CREATE)
- .storageOptions(storageProps)
- .execute()) {
+ try (Dataset ignored = createDataset(location, columns, storageProps)) {
// Only create the table metadata in Gravitino after the Lance dataset is successfully
// created.
long datasetVersion = ignored.version();
@@ -461,6 +456,23 @@ public class LanceTableOperations extends ManagedTableOperations {
}
}
+ /**
+ * Creates an empty Lance dataset for the columns. The Lance file format version is chosen from
+ * the blob columns, because blob v2 and legacy blob each require a different version.
+ */
+ Dataset createDataset(String location, Column[] columns, Map<String, String> storageOptions) {
+ Schema schema = convertColumnsToArrowSchema(columns);
+ WriteDatasetBuilder builder =
+ Dataset.write()
+ .schema(schema)
+ .uri(location)
+ .mode(WriteParams.WriteMode.CREATE)
+ .storageOptions(storageOptions);
+ LanceDataTypeConverter.requiredFileFormatVersion(schema.getFields())
+ .ifPresent(builder::dataStorageVersion);
+ return builder.execute();
+ }
+
private Schema convertColumnsToArrowSchema(Column[] columns) {
List<Field> fields =
Arrays.stream(columns)
@@ -854,6 +866,7 @@ public class LanceTableOperations extends ManagedTableOperations {
Field field =
LanceDataTypeConverter.CONVERTER.toArrowField(
columnName, addColumn.getDataType(), true);
+ LanceDataTypeConverter.checkFileFormatVersion(field, dataset.getLanceFileFormatVersion());
dataset.addColumns(List.of(field));
} else if (change instanceof TableChange.DeleteColumn deleteColumn) {
dataset.dropColumns(List.of(String.join(".", deleteColumn.fieldName())));
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java
index 890c718a4d..6d688b0d7b 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/TestLanceTableOperations.java
@@ -50,6 +50,7 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.UserPrincipal;
import org.apache.gravitino.catalog.ManagedSchemaOperations;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.lance.common.ops.gravitino.LanceDataTypeConverter;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.ColumnEntity;
import org.apache.gravitino.meta.TableEntity;
@@ -68,6 +69,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.lance.Dataset;
import org.lance.Version;
@@ -898,6 +900,78 @@ public class TestLanceTableOperations {
Mockito.verify(dataset).getVersion();
}
+ @ParameterizedTest
+ @CsvSource({"lance.blob, 2.2", "lance.blob.legacy, 2.1"})
+ public void testCreateDatasetWithBlobColumnRoundTrips(String blobType, String fileFormatVersion) {
+ String location = tempDir.resolve("blob-" + fileFormatVersion).toString();
+ Column[] columns =
+ new Column[] {
+ Column.of("id", Types.IntegerType.get()),
+ Column.of("image", Types.ExternalType.of(blobType))
+ };
+
+ try (Dataset dataset = lanceTableOps.createDataset(location, columns, Map.of())) {
+ Assertions.assertEquals(fileFormatVersion, dataset.getLanceFileFormatVersion());
+ }
+ try (Dataset dataset = lanceTableOps.openDataset(location, Map.of())) {
+ Assertions.assertEquals(
+ Types.ExternalType.of(blobType),
+ LanceDataTypeConverter.CONVERTER.toGravitino(dataset.getSchema().findField("image")));
+ }
+ }
+
+ @Test
+ public void testCreateDatasetRejectsMixedBlobColumns() {
+ Column[] columns =
+ new Column[] {
+ Column.of("image", Types.ExternalType.of("lance.blob")),
+ Column.of("legacy_image", Types.ExternalType.of("lance.blob.legacy"))
+ };
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ lanceTableOps.createDataset(
+ tempDir.resolve("mixed-blob").toString(), columns, Map.of()));
+ }
+
+ @Test
+ public void testAddBlobColumnChecksFileFormatVersion() {
+ String location = tempDir.resolve("add-blob").toString();
+ try (Dataset ignored =
+ lanceTableOps.createDataset(
+ location, new Column[] {Column.of("id", Types.IntegerType.get())}, Map.of())) {
+ // A dataset without blob columns uses Lance's default file format version.
+ }
+ Table table = mock(Table.class);
+ when(table.properties()).thenReturn(Map.of(Table.PROPERTY_LOCATION, location));
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ lanceTableOps.handleLanceTableChange(
+ table,
+ new TableChange[] {
+ TableChange.addColumn(
+ new String[] {"image"}, Types.ExternalType.of("lance.blob"))
+ }));
+ Assertions.assertTrue(exception.getMessage().contains("2.2"), exception.getMessage());
+
+ lanceTableOps.handleLanceTableChange(
+ table,
+ new TableChange[] {
+ TableChange.addColumn(
+ new String[] {"legacy_image"}, Types.ExternalType.of("lance.blob.legacy"))
+ });
+ try (Dataset dataset = lanceTableOps.openDataset(location, Map.of())) {
+ Assertions.assertEquals(
+ Types.ExternalType.of("lance.blob.legacy"),
+ LanceDataTypeConverter.CONVERTER.toGravitino(
+ dataset.getSchema().findField("legacy_image")));
+ }
+ }
+
@Test
public void testVersionCheckSkipsSchemaReadForEmptySchemaWhenVersionUnchanged() throws Exception {
lanceTableOps.setCatalogProperties(Map.of(LANCE_SCHEMA_REFRESH_MODE, "version-check"));
diff --git a/docs/lakehouse-generic-lance-table.md b/docs/lakehouse-generic-lance-table.md
index bd5db84f5e..28bc92e88e 100644
--- a/docs/lakehouse-generic-lance-table.md
+++ b/docs/lakehouse-generic-lance-table.md
@@ -75,6 +75,8 @@ Lance uses Apache Arrow for table schemas. The following table shows type mappin
| `Interval_year` | Not supported by Lance |
| `Interval_day` | `Duration(Microsecond)` |
| `External(arrow_field_json_str)` | Any Arrow Field |
+| `External("lance.blob")` | Lance blob |
+| `External("lance.blob.legacy")` | Lance legacy blob |
### External Types
@@ -82,7 +84,8 @@ For Arrow types not natively mapped in Gravitino, use the `External(arrow_field_
**Requirements:**
- JSON must conform to Apache Arrow [Field specification](https://github.com/apache/arrow-java/blob/ed81e5981a2bee40584b3a411ed755cb4cc5b91f/vector/src/main/java/org/apache/arrow/vector/types/pojo/Field.java#L80C1-L86C68)
-- `name` attribute must match column name exactly
+- `name` attribute is ignored: the column name is authoritative and overrides the name in the JSON,
+ so a column keeps its stored JSON type after a rename
- `nullable` attribute must match column nullability
- `children` array:
- Empty for primitive types
@@ -97,6 +100,46 @@ For Arrow types not natively mapped in Gravitino, use the `External(arrow_field_
| `Large List` | `External("{\"name\":\"col_name\",\"nullable\":true,\"type\":{\"name\":\"largelist\"},\"children\":[{\"name\":\"element\",\"nullable\":true,\"type\":{\"name\":\"int\",\"bitWidth\":32,\"isSigned\":true},\"children\":[]}]}")` |
| `Fixed-Size List` | `External("{\"name\":\"col_name\",\"nullable\":true,\"type\":{\"name\":\"fixedsizelist\",\"listSize\":10},\"children\":[{\"name\":\"element\",\"nullable\":true,\"type\":{\"name\":\"int\",\"bitWidth\":32,\"isSigned\":true},\"children\":[]}]}")` |
+Gravitino types cannot carry Arrow field metadata. When loading a Lance table, only Lance blob metadata
+is recognized (see [Blob Types](#blob-types)); other field metadata is ignored. Blob fields nested in a
+`Struct`, `List`, `Map` or `Union` keep the container as a native Gravitino type, for example
+`List(External("lance.blob"))`. As with other list columns, the list child is written back as
+`element`, whatever name it had in the Lance dataset (Lance and pyarrow use `item`).
+
+### Blob Types
+
+Lance blob columns use a readable external type instead of Arrow JSON:
+
+| External Type Definition | Arrow Field | Lance File Format Version |
+|-----------------------------------|-------------------------------------------------------------------------------------------|---------------------------|
+| `External("lance.blob")` | `Struct<data: LargeBinary, uri: Utf8>` with metadata `ARROW:extension:name=lance.blob.v2` | 2.2 or later |
+| `External("lance.blob.legacy")` | `LargeBinary` with metadata `lance-encoding:blob=true` | 2.1 or earlier |
+
+Use `lance.blob` for new tables. `lance.blob.legacy` is only for datasets that already use Lance's
+legacy blob encoding.
+
+When Gravitino creates a Lance dataset with blob columns, it picks the Lance file format version for
+them: 2.2 for `lance.blob` and 2.1 for `lance.blob.legacy`. A table cannot have both. Adding a blob
+column to an existing dataset fails with a clear error if the dataset's file format version does not
+support it.
+
+Only the blob marker is recognized. Other blob metadata, such as
+`lance-encoding:blob-dedicated-size-threshold`, is not shown in the Gravitino type, and columns created
+through Gravitino use Lance's defaults. A blob field in any other layout, for example a blob v2 struct
+with the optional `position` and `size` fields or a legacy blob stored as `Binary`, is returned as
+`External(arrow_field_json_str)` so that it keeps its exact definition.
+
+:::note
+Column types stored by an earlier Gravitino version are rewritten only when the table schema is
+refreshed from the Lance dataset, which depends on the catalog's
+[schema refresh mode](#schema-refresh). The default `DECLARED_AND_EMPTY` mode never refreshes a
+table that is neither declared nor empty, so such a table keeps its stored types even after the
+dataset version changes; set `lance.schema-refresh-mode` to `VERSION_CHECK` to refresh it on the next
+version change. Until a refresh happens, blob v2 columns still appear as a plain `Struct`, and legacy
+blob columns stored as `External(arrow_field_json_str)` keep that form instead of
+`External("lance.blob.legacy")`.
+:::
+
### Table Properties
Required and optional properties for tables in a Generic Lakehouse Catalog:
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceBlobTypes.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceBlobTypes.java
new file mode 100644
index 0000000000..42d6a63814
--- /dev/null
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceBlobTypes.java
@@ -0,0 +1,260 @@
+/*
+ * 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.
+ */
+
+package org.apache.gravitino.lance.common.ops.gravitino;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.FieldType;
+
+/**
+ * Converts Lance blob columns between their Arrow field form and the catalog strings used by
+ * Gravitino external types.
+ *
+ * <ul>
+ * <li>{@code lance.blob}: a Lance blob v2 column, an Arrow {@code Struct<data: LargeBinary, uri:
+ * Utf8>} tagged with {@code ARROW:extension:name=lance.blob.v2}. It requires Lance file
+ * format version 2.2 or later.
+ * <li>{@code lance.blob.legacy}: a Lance legacy blob column, an Arrow {@code LargeBinary} field
+ * with metadata {@code lance-encoding:blob=true}. Lance rejects it from file format version
+ * 2.2 on.
+ * </ul>
+ *
+ * <p>Only the blob marker is recognized; other field metadata, such as storage thresholds, is not
+ * represented. A blob field in any other layout is left to the Arrow JSON representation so that it
+ * round-trips unchanged.
+ */
+final class LanceBlobTypes {
+
+ static final String BLOB = "lance.blob";
+ static final String LEGACY_BLOB = "lance.blob.legacy";
+
+ static final String BLOB_META_KEY = "lance-encoding:blob";
+ static final String ARROW_EXT_NAME_KEY = "ARROW:extension:name";
+ static final String BLOB_V2_EXT_NAME = "lance.blob.v2";
+
+ /** The Lance file format version from which blob v2 is supported and legacy blob is rejected. */
+ static final String BLOB_FILE_FORMAT_VERSION = "2.2";
+
+ /** The Lance file format version used for datasets with legacy blob columns. */
+ static final String LEGACY_BLOB_FILE_FORMAT_VERSION = "2.1";
+
+ private static final List<Field> BLOB_CHILDREN =
+ ImmutableList.of(
+ new Field("data", new FieldType(true, ArrowType.LargeBinary.INSTANCE, null), null),
+ new Field("uri", new FieldType(true, ArrowType.Utf8.INSTANCE, null), null));
+
+ private LanceBlobTypes() {}
+
+ /**
+ * Returns whether the field carries a Lance blob marker, either legacy blob or blob v2. This
+ * matches Lance's own check, which only looks at whether the legacy key is present.
+ *
+ * @param field The Arrow field.
+ * @return true if the field is a Lance blob field.
+ */
+ static boolean isBlob(Field field) {
+ return isBlobV2(field) || isLegacyBlob(field);
+ }
+
+ /**
+ * Returns the catalog string of a Lance blob field in its standard layout.
+ *
+ * @param field The Arrow field.
+ * @return The catalog string, or empty if the field is not a Lance blob in its standard layout.
+ */
+ static Optional<String> toCatalogString(Field field) {
+ if (field.getDictionary() != null) {
+ return Optional.empty();
+ }
+ if (isBlobV2(field)
+ && field.getType() instanceof ArrowType.Struct
+ && childrenMatch(field.getChildren(), BLOB_CHILDREN)) {
+ return Optional.of(BLOB);
+ }
+ if (isLegacyBlob(field)
+ && field.getType() instanceof ArrowType.LargeBinary
+ && field.getChildren().isEmpty()
+ && "true".equals(field.getMetadata().get(BLOB_META_KEY))) {
+ return Optional.of(LEGACY_BLOB);
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Returns whether the catalog string names a Lance blob type.
+ *
+ * @param catalogString The external type catalog string.
+ * @return true if the string starts with {@code lance.blob}.
+ */
+ static boolean isBlobCatalogString(String catalogString) {
+ return catalogString != null && catalogString.trim().startsWith(BLOB);
+ }
+
+ /**
+ * Builds the Arrow field described by a Lance blob catalog string.
+ *
+ * @param name The field name.
+ * @param nullable Whether the field is nullable.
+ * @param catalogString The Lance blob catalog string.
+ * @return The Arrow field.
+ * @throws IllegalArgumentException If the catalog string is not a Lance blob type.
+ */
+ static Field toArrowField(String name, boolean nullable, String catalogString) {
+ switch (catalogString.trim()) {
+ case BLOB:
+ return new Field(
+ name,
+ new FieldType(
+ nullable,
+ ArrowType.Struct.INSTANCE,
+ null,
+ ImmutableMap.of(ARROW_EXT_NAME_KEY, BLOB_V2_EXT_NAME)),
+ BLOB_CHILDREN);
+ case LEGACY_BLOB:
+ return new Field(
+ name,
+ new FieldType(
+ nullable,
+ ArrowType.LargeBinary.INSTANCE,
+ null,
+ ImmutableMap.of(BLOB_META_KEY, "true")),
+ null);
+ default:
+ throw new IllegalArgumentException(
+ String.format(
+ "Unsupported Lance blob type %s, expected %s or %s",
+ catalogString.trim(), BLOB, LEGACY_BLOB));
+ }
+ }
+
+ /**
+ * Returns the Lance file format version that a new dataset with these fields must use.
+ *
+ * @param fields The top-level Arrow fields of the dataset.
+ * @return {@value #BLOB_FILE_FORMAT_VERSION} if any field contains a blob v2 column, {@value
+ * #LEGACY_BLOB_FILE_FORMAT_VERSION} if any field contains a legacy blob column, or empty if
+ * there is no blob column.
+ * @throws IllegalArgumentException If the fields contain both blob v2 and legacy blob columns.
+ */
+ static Optional<String> requiredFileFormatVersion(List<Field> fields) {
+ boolean hasBlobV2 = fields.stream().anyMatch(field -> contains(field, true));
+ boolean hasLegacyBlob = fields.stream().anyMatch(field -> contains(field, false));
+ if (hasBlobV2 && hasLegacyBlob) {
+ throw new IllegalArgumentException(
+ String.format(
+ "A Lance table cannot mix %s and %s columns: %s requires file format version %s or"
+ + " later, which does not support %s",
+ BLOB, LEGACY_BLOB, BLOB, BLOB_FILE_FORMAT_VERSION, LEGACY_BLOB));
+ }
+ if (hasBlobV2) {
+ return Optional.of(BLOB_FILE_FORMAT_VERSION);
+ }
+ return hasLegacyBlob ? Optional.of(LEGACY_BLOB_FILE_FORMAT_VERSION) : Optional.empty();
+ }
+
+ /**
+ * Checks that a field can be added to a dataset with the given Lance file format version.
+ *
+ * @param field The Arrow field to add.
+ * @param fileFormatVersion The dataset's Lance file format version, such as {@code 2.1}.
+ * @throws IllegalArgumentException If the field contains a blob column the version does not
+ * support.
+ */
+ static void checkFileFormatVersion(Field field, String fileFormatVersion) {
+ Optional<Boolean> supportsBlobV2 = supportsBlobV2(fileFormatVersion);
+ if (supportsBlobV2.isEmpty()) {
+ // Leave unknown versions to Lance.
+ return;
+ }
+ if (!supportsBlobV2.get() && contains(field, true)) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Column %s of type %s requires Lance file format version %s or later, but the"
+ + " dataset uses %s",
+ field.getName(), BLOB, BLOB_FILE_FORMAT_VERSION, fileFormatVersion));
+ }
+ if (supportsBlobV2.get() && contains(field, false)) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Column %s of type %s is not supported by Lance file format version %s or later,"
+ + " but the dataset uses %s; use %s instead",
+ field.getName(), LEGACY_BLOB, BLOB_FILE_FORMAT_VERSION, fileFormatVersion, BLOB));
+ }
+ }
+
+ private static boolean isBlobV2(Field field) {
+ Map<String, String> metadata = field.getMetadata();
+ return metadata != null && BLOB_V2_EXT_NAME.equals(metadata.get(ARROW_EXT_NAME_KEY));
+ }
+
+ private static boolean isLegacyBlob(Field field) {
+ Map<String, String> metadata = field.getMetadata();
+ return metadata != null && metadata.containsKey(BLOB_META_KEY) && !isBlobV2(field);
+ }
+
+ private static boolean contains(Field field, boolean blobV2) {
+ if (blobV2 ? isBlobV2(field) : isLegacyBlob(field)) {
+ return true;
+ }
+ return field.getChildren().stream().anyMatch(child -> contains(child, blobV2));
+ }
+
+ private static Optional<Boolean> supportsBlobV2(String fileFormatVersion) {
+ if (fileFormatVersion == null) {
+ return Optional.empty();
+ }
+ String[] parts = fileFormatVersion.trim().split("\\.");
+ if (parts.length != 2) {
+ return Optional.empty();
+ }
+ try {
+ int major = Integer.parseInt(parts[0]);
+ int minor = Integer.parseInt(parts[1]);
+ return Optional.of(major > 2 || (major == 2 && minor >= 2));
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+
+ // Compares blob v2 children the way Lance classifies the layout: by name, Arrow type and
+ // nullability. Child metadata is not part of the layout and is ignored.
+ private static boolean childrenMatch(List<Field> actual, List<Field> expected) {
+ if (actual.size() != expected.size()) {
+ return false;
+ }
+ for (int i = 0; i < actual.size(); i++) {
+ Field actualChild = actual.get(i);
+ Field expectedChild = expected.get(i);
+ if (!actualChild.getName().equals(expectedChild.getName())
+ || !actualChild.getType().equals(expectedChild.getType())
+ || actualChild.isNullable() != expectedChild.isNullable()
+ || actualChild.getDictionary() != null
+ || !actualChild.getChildren().isEmpty()) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceDataTypeConverter.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceDataTypeConverter.java
index 52d52d38fb..1484baf929 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceDataTypeConverter.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/LanceDataTypeConverter.java
@@ -24,6 +24,7 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
+import java.util.Optional;
import org.apache.arrow.vector.complex.MapVector;
import org.apache.arrow.vector.types.DateUnit;
import org.apache.arrow.vector.types.FloatingPointPrecision;
@@ -46,6 +47,32 @@ public class LanceDataTypeConverter implements DataTypeConverter<ArrowType, Fiel
public static final LanceDataTypeConverter CONVERTER = new LanceDataTypeConverter();
private static final ObjectMapper mapper = new ObjectMapper();
+ /**
+ * Returns the Lance file format version that a new dataset with these fields must use, so that
+ * its blob columns can be written: 2.2 for {@code lance.blob} and 2.1 for {@code
+ * lance.blob.legacy}.
+ *
+ * @param fields The top-level Arrow fields of the dataset.
+ * @return The required file format version, or empty if the fields have no blob column.
+ * @throws IllegalArgumentException If the fields mix {@code lance.blob} and {@code
+ * lance.blob.legacy} columns.
+ */
+ public static Optional<String> requiredFileFormatVersion(List<Field> fields) {
+ return LanceBlobTypes.requiredFileFormatVersion(fields);
+ }
+
+ /**
+ * Checks that a field can be added to a dataset with the given Lance file format version.
+ *
+ * @param field The Arrow field to add.
+ * @param fileFormatVersion The dataset's Lance file format version, such as {@code 2.1}.
+ * @throws IllegalArgumentException If the field contains a blob column the version does not
+ * support.
+ */
+ public static void checkFileFormatVersion(Field field, String fileFormatVersion) {
+ LanceBlobTypes.checkFileFormatVersion(field, fileFormatVersion);
+ }
+
public Field toArrowField(String name, Type type, boolean nullable) {
switch (type.name()) {
case LIST:
@@ -113,6 +140,9 @@ public class LanceDataTypeConverter implements DataTypeConverter<ArrowType, Fiel
case EXTERNAL:
Types.ExternalType externalType = (Types.ExternalType) type;
+ if (LanceBlobTypes.isBlobCatalogString(externalType.catalogString())) {
+ return LanceBlobTypes.toArrowField(name, nullable, externalType.catalogString());
+ }
Field field;
try {
field = mapper.readValue(externalType.catalogString(), Field.class);
@@ -120,17 +150,15 @@ public class LanceDataTypeConverter implements DataTypeConverter<ArrowType, Fiel
throw new RuntimeException(
"Failed to parse external type catalog string: " + externalType.catalogString(), e);
}
- Preconditions.checkArgument(
- name.equals(field.getName()),
- "expected field name %s but got %s",
- name,
- field.getName());
Preconditions.checkArgument(
nullable == field.isNullable(),
"expected field nullable %s but got %s",
nullable,
field.isNullable());
- return field;
+ // The column name is authoritative: a renamed column keeps its stored JSON type.
+ return name.equals(field.getName())
+ ? field
+ : new Field(name, field.getFieldType(), field.getChildren());
default:
// non-complex type
@@ -203,7 +231,19 @@ public class LanceDataTypeConverter implements DataTypeConverter<ArrowType, Fiel
@Override
public Type toGravitino(Field arrowField) {
+ Optional<String> blobType = LanceBlobTypes.toCatalogString(arrowField);
+ if (blobType.isPresent()) {
+ return Types.ExternalType.of(blobType.get());
+ }
+
+ // Only Lance blob metadata is recognized. A blob field outside the canonical layout keeps the
+ // whole field as Arrow JSON so the blob is not turned into a plain binary or struct column.
+ if (LanceBlobTypes.isBlob(arrowField)) {
+ return toExternalType(arrowField);
+ }
+
FieldType fieldType = arrowField.getFieldType();
+
switch (fieldType.getType().getTypeID()) {
case Map:
Field structField = arrowField.getChildren().get(0);
@@ -315,6 +355,10 @@ public class LanceDataTypeConverter implements DataTypeConverter<ArrowType, Fiel
// fallthrough
}
+ return toExternalType(arrowField);
+ }
+
+ private Type toExternalType(Field arrowField) {
String typeString;
try {
typeString = mapper.writeValueAsString(arrowField);
diff --git a/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceBlobTypes.java b/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceBlobTypes.java
new file mode 100644
index 0000000000..e04e3bdd31
--- /dev/null
+++ b/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceBlobTypes.java
@@ -0,0 +1,292 @@
+/*
+ * 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.
+ */
+package org.apache.gravitino.lance.common.ops.gravitino;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.DictionaryEncoding;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.FieldType;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class TestLanceBlobTypes {
+
+ private static final Map<String, String> LEGACY_META =
+ Map.of(LanceBlobTypes.BLOB_META_KEY, "true");
+
+ @Test
+ void testBlobRoundTrip() {
+ Field field = blobField(standardChildren(), Map.of());
+
+ assertEquals(Optional.of("lance.blob"), LanceBlobTypes.toCatalogString(field));
+ assertEquals(field, LanceBlobTypes.toArrowField("blob", true, "lance.blob"));
+ }
+
+ @Test
+ void testLegacyBlobRoundTrip() {
+ Field field =
+ new Field(
+ "image", new FieldType(false, ArrowType.LargeBinary.INSTANCE, null, LEGACY_META), null);
+
+ assertEquals(Optional.of("lance.blob.legacy"), LanceBlobTypes.toCatalogString(field));
+ assertEquals(field, LanceBlobTypes.toArrowField("image", false, "lance.blob.legacy"));
+ }
+
+ @Test
+ void testNonLayoutMetadataIsIgnored() {
+ Field legacy =
+ new Field(
+ "b",
+ new FieldType(
+ true,
+ ArrowType.LargeBinary.INSTANCE,
+ null,
+ Map.of(LanceBlobTypes.BLOB_META_KEY, "true", "other", "x")),
+ null);
+ assertEquals(Optional.of("lance.blob.legacy"), LanceBlobTypes.toCatalogString(legacy));
+
+ // Storage thresholds and pyarrow's ARROW:extension:metadata entry.
+ Field blob =
+ blobField(
+ standardChildren(),
+ Map.of(
+ "ARROW:extension:metadata", "",
+ "lance-encoding:blob-dedicated-size-threshold", "16"));
+ assertEquals(Optional.of("lance.blob"), LanceBlobTypes.toCatalogString(blob));
+
+ // Child metadata is not part of the blob v2 layout.
+ List<Field> childWithMetadata =
+ Arrays.asList(
+ new Field(
+ "data",
+ new FieldType(
+ true,
+ ArrowType.LargeBinary.INSTANCE,
+ null,
+ Map.of("lance-encoding:compression", "zstd")),
+ null),
+ standardChildren().get(1));
+ assertEquals(
+ Optional.of("lance.blob"),
+ LanceBlobTypes.toCatalogString(blobField(childWithMetadata, Map.of())));
+ }
+
+ @Test
+ void testNonStandardLegacyBlobIsNotReadable() {
+ assertFalse(
+ LanceBlobTypes.toCatalogString(
+ new Field(
+ "b", new FieldType(true, ArrowType.Binary.INSTANCE, null, LEGACY_META), null))
+ .isPresent());
+ assertFalse(
+ LanceBlobTypes.toCatalogString(
+ new Field(
+ "b",
+ new FieldType(
+ true,
+ ArrowType.LargeBinary.INSTANCE,
+ null,
+ Map.of(LanceBlobTypes.BLOB_META_KEY, "false")),
+ null))
+ .isPresent());
+ assertFalse(
+ LanceBlobTypes.toCatalogString(
+ new Field(
+ "b",
+ new FieldType(
+ true,
+ ArrowType.LargeBinary.INSTANCE,
+ new DictionaryEncoding(1L, false, new ArrowType.Int(32, true)),
+ LEGACY_META),
+ null))
+ .isPresent());
+ }
+
+ @Test
+ void testNonStandardBlobIsNotReadable() {
+ // With the optional external range fields.
+ List<Field> fullChildren = new ArrayList<>(standardChildren());
+ fullChildren.add(
+ new Field("position", new FieldType(true, new ArrowType.Int(64, false), null), null));
+ fullChildren.add(
+ new Field("size", new FieldType(true, new ArrowType.Int(64, false), null), null));
+ assertFalse(LanceBlobTypes.toCatalogString(blobField(fullChildren, Map.of())).isPresent());
+
+ // Wrong child order.
+ List<Field> reordered = new ArrayList<>(standardChildren());
+ Collections.reverse(reordered);
+ assertFalse(LanceBlobTypes.toCatalogString(blobField(reordered, Map.of())).isPresent());
+
+ // Non-nullable child.
+ List<Field> nonNullable =
+ Arrays.asList(
+ new Field("data", new FieldType(false, ArrowType.LargeBinary.INSTANCE, null), null),
+ standardChildren().get(1));
+ assertFalse(LanceBlobTypes.toCatalogString(blobField(nonNullable, Map.of())).isPresent());
+
+ // Dictionary-encoded child.
+ List<Field> dictionaryChild =
+ Arrays.asList(
+ standardChildren().get(0),
+ new Field(
+ "uri",
+ new FieldType(
+ true,
+ ArrowType.Utf8.INSTANCE,
+ new DictionaryEncoding(1L, false, new ArrowType.Int(32, true))),
+ null));
+ assertFalse(LanceBlobTypes.toCatalogString(blobField(dictionaryChild, Map.of())).isPresent());
+
+ // Not a struct.
+ assertFalse(
+ LanceBlobTypes.toCatalogString(
+ new Field(
+ "blob",
+ new FieldType(
+ true,
+ ArrowType.LargeBinary.INSTANCE,
+ null,
+ Map.of(LanceBlobTypes.ARROW_EXT_NAME_KEY, LanceBlobTypes.BLOB_V2_EXT_NAME)),
+ null))
+ .isPresent());
+ }
+
+ @Test
+ void testFieldWithoutBlobMarkerIsNotBlob() {
+ Field struct = new Field("s", new FieldType(true, ArrowType.Struct.INSTANCE, null), null);
+ assertFalse(LanceBlobTypes.isBlob(struct));
+ assertFalse(LanceBlobTypes.toCatalogString(struct).isPresent());
+ assertFalse(
+ LanceBlobTypes.isBlob(
+ new Field(
+ "b",
+ new FieldType(
+ true,
+ ArrowType.LargeBinary.INSTANCE,
+ null,
+ Map.of("lance-encoding:blob-dedicated-size-threshold", "1")),
+ null)));
+ }
+
+ @Test
+ void testIsBlob() {
+ assertTrue(LanceBlobTypes.isBlob(LanceBlobTypes.toArrowField("b", true, "lance.blob")));
+ assertTrue(LanceBlobTypes.isBlob(LanceBlobTypes.toArrowField("b", true, "lance.blob.legacy")));
+ // Lance only checks that the legacy key is present.
+ assertTrue(
+ LanceBlobTypes.isBlob(
+ new Field(
+ "b",
+ new FieldType(
+ true,
+ ArrowType.Binary.INSTANCE,
+ null,
+ Map.of(LanceBlobTypes.BLOB_META_KEY, "false")),
+ null)));
+ }
+
+ @Test
+ void testIsBlobCatalogString() {
+ assertTrue(LanceBlobTypes.isBlobCatalogString("lance.blob"));
+ assertTrue(LanceBlobTypes.isBlobCatalogString(" lance.blob.legacy "));
+ assertTrue(LanceBlobTypes.isBlobCatalogString("lance.blob.v2"));
+ assertFalse(LanceBlobTypes.isBlobCatalogString("{\"name\":\"lance.blob\"}"));
+ assertFalse(LanceBlobTypes.isBlobCatalogString(null));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"lance.blob.v1", "lance.blob.v2", "lance.blob(x=1)", "lance.blobs"})
+ void testInvalidCatalogStrings(String catalogString) {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LanceBlobTypes.toArrowField("blob", true, catalogString));
+ }
+
+ @Test
+ void testRequiredFileFormatVersion() {
+ Field id = new Field("id", new FieldType(false, new ArrowType.Int(32, true), null), null);
+ Field blob = LanceBlobTypes.toArrowField("blob", true, "lance.blob");
+ Field legacy = LanceBlobTypes.toArrowField("legacy", true, "lance.blob.legacy");
+ Field nestedBlob =
+ new Field(
+ "record",
+ new FieldType(true, ArrowType.Struct.INSTANCE, null),
+ Collections.singletonList(blob));
+
+ assertEquals(Optional.empty(), LanceBlobTypes.requiredFileFormatVersion(List.of(id)));
+ assertEquals(Optional.of("2.2"), LanceBlobTypes.requiredFileFormatVersion(List.of(id, blob)));
+ assertEquals(
+ Optional.of("2.2"), LanceBlobTypes.requiredFileFormatVersion(List.of(id, nestedBlob)));
+ assertEquals(Optional.of("2.1"), LanceBlobTypes.requiredFileFormatVersion(List.of(id, legacy)));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LanceBlobTypes.requiredFileFormatVersion(List.of(blob, legacy)));
+ }
+
+ @Test
+ void testCheckFileFormatVersion() {
+ Field id = new Field("id", new FieldType(true, new ArrowType.Int(32, true), null), null);
+ Field blob = LanceBlobTypes.toArrowField("blob", true, "lance.blob");
+ Field legacy = LanceBlobTypes.toArrowField("legacy", true, "lance.blob.legacy");
+
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(id, "2.1"));
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(blob, "2.2"));
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(blob, "2.3"));
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(legacy, "2.1"));
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(legacy, "0.1"));
+ // Unknown versions are left to Lance.
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(blob, "stable"));
+ assertDoesNotThrow(() -> LanceBlobTypes.checkFileFormatVersion(blob, null));
+
+ IllegalArgumentException blobError =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LanceBlobTypes.checkFileFormatVersion(blob, "2.1"));
+ assertTrue(blobError.getMessage().contains("2.2"), blobError.getMessage());
+ assertThrows(
+ IllegalArgumentException.class, () -> LanceBlobTypes.checkFileFormatVersion(legacy, "2.2"));
+ }
+
+ private static Field blobField(List<Field> children, Map<String, String> extraMetadata) {
+ Map<String, String> metadata = new HashMap<>(extraMetadata);
+ metadata.put(LanceBlobTypes.ARROW_EXT_NAME_KEY, LanceBlobTypes.BLOB_V2_EXT_NAME);
+ return new Field(
+ "blob", new FieldType(true, ArrowType.Struct.INSTANCE, null, metadata), children);
+ }
+
+ private static List<Field> standardChildren() {
+ return Arrays.asList(
+ new Field("data", new FieldType(true, ArrowType.LargeBinary.INSTANCE, null), null),
+ new Field("uri", new FieldType(true, ArrowType.Utf8.INSTANCE, null), null));
+ }
+}
diff --git a/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceDataTypeConverter.java b/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceDataTypeConverter.java
index 9908f8feff..a4f23c09da 100644
--- a/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceDataTypeConverter.java
+++ b/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestLanceDataTypeConverter.java
@@ -24,14 +24,18 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.List;
+import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.apache.arrow.vector.complex.MapVector;
import org.apache.arrow.vector.types.DateUnit;
import org.apache.arrow.vector.types.FloatingPointPrecision;
import org.apache.arrow.vector.types.TimeUnit;
+import org.apache.arrow.vector.types.Types.MinorType;
import org.apache.arrow.vector.types.UnionMode;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
@@ -257,6 +261,300 @@ public class TestLanceDataTypeConverter {
assertEquals(10, ((ArrowType.FixedSizeList) arrowField.getFieldType().getType()).getListSize());
}
+ @Test
+ void testBlobConvertsToReadableExternalTypeAndRoundTrips() {
+ // Storage thresholds and other non-layout metadata are not part of the Gravitino type.
+ Field blobField =
+ new Field(
+ "blob",
+ new FieldType(
+ true,
+ ArrowType.Struct.INSTANCE,
+ null,
+ Map.of(
+ "ARROW:extension:name", "lance.blob.v2",
+ "lance-encoding:blob-dedicated-size-threshold", "1048576")),
+ Arrays.asList(
+ new Field("data", new FieldType(true, ArrowType.LargeBinary.INSTANCE, null), null),
+ new Field("uri", new FieldType(true, ArrowType.Utf8.INSTANCE, null), null)));
+
+ Type type = CONVERTER.toGravitino(blobField);
+
+ assertEquals(Types.ExternalType.of("lance.blob"), type);
+ assertEquals(
+ LanceBlobTypes.toArrowField("blob", true, LanceBlobTypes.BLOB),
+ CONVERTER.toArrowField("blob", type, true));
+ }
+
+ @Test
+ void testLegacyBlobConvertsToReadableExternalTypeAndRoundTrips() {
+ Field legacyField =
+ new Field(
+ "image",
+ new FieldType(
+ false, ArrowType.LargeBinary.INSTANCE, null, Map.of("lance-encoding:blob", "true")),
+ null);
+
+ Type type = CONVERTER.toGravitino(legacyField);
+
+ assertEquals(Types.ExternalType.of("lance.blob.legacy"), type);
+ assertEquals(legacyField, CONVERTER.toArrowField("image", type, false));
+ }
+
+ @Test
+ void testNonStandardBlobConvertsToJsonExternalTypeAndRoundTrips() {
+ // A legacy blob stored as Binary instead of LargeBinary.
+ assertJsonExternalTypeRoundTrips(
+ new Field(
+ "image",
+ new FieldType(
+ true, ArrowType.Binary.INSTANCE, null, Map.of("lance-encoding:blob", "true")),
+ null));
+
+ // A legacy blob marker whose value is not "true"; Lance still treats it as a blob.
+ assertJsonExternalTypeRoundTrips(
+ new Field(
+ "image",
+ new FieldType(
+ true, ArrowType.LargeBinary.INSTANCE, null, Map.of("lance-encoding:blob", "false")),
+ null));
+
+ // A blob v2 struct with the optional external range fields.
+ Field blob = LanceBlobTypes.toArrowField("blob", true, LanceBlobTypes.BLOB);
+ List<Field> fullChildren = new ArrayList<>(blob.getChildren());
+ fullChildren.add(
+ new Field("position", new FieldType(true, new ArrowType.Int(64, false), null), null));
+ fullChildren.add(
+ new Field("size", new FieldType(true, new ArrowType.Int(64, false), null), null));
+ assertJsonExternalTypeRoundTrips(new Field("blob", blob.getFieldType(), fullChildren));
+ }
+
+ @Test
+ void testNonBlobMetadataIsIgnored() {
+ Field field =
+ new Field(
+ "id",
+ new FieldType(
+ false,
+ new ArrowType.Int(64, true),
+ null,
+ Map.of("lance-schema:unenforced-primary-key", "true")),
+ null);
+ assertEquals(Types.LongType.get(), CONVERTER.toGravitino(field));
+
+ Field listField =
+ new Field(
+ "tags",
+ new FieldType(true, ArrowType.List.INSTANCE, null),
+ Collections.singletonList(
+ new Field(
+ "element",
+ new FieldType(
+ true,
+ ArrowType.Utf8.INSTANCE,
+ null,
+ Map.of("lance-encoding:compression", "zstd")),
+ null)));
+ assertEquals(Types.ListType.of(Types.StringType.get(), true), CONVERTER.toGravitino(listField));
+ }
+
+ @Test
+ void testStructWithBlobChildRoundTrips() {
+ Field blobChild = LanceBlobTypes.toArrowField("image", true, LanceBlobTypes.BLOB);
+ Field structField =
+ new Field(
+ "record",
+ new FieldType(true, ArrowType.Struct.INSTANCE, null),
+ Arrays.asList(
+ new Field("id", new FieldType(false, new ArrowType.Int(64, true), null), null),
+ blobChild));
+
+ Type type = CONVERTER.toGravitino(structField);
+
+ Types.StructType structType = assertInstanceOf(Types.StructType.class, type);
+ assertEquals(Types.LongType.get(), structType.fields()[0].type());
+ assertEquals(Types.ExternalType.of(LanceBlobTypes.BLOB), structType.fields()[1].type());
+ assertEquals(structField, CONVERTER.toArrowField("record", type, true));
+ }
+
+ @Test
+ void testListWithBlobChildConvertsToNativeList() {
+ String blobType = LanceBlobTypes.BLOB;
+ // Lance and pyarrow name list children "item"; Gravitino writes them back as "element".
+ Field listField =
+ new Field(
+ "images",
+ new FieldType(true, ArrowType.List.INSTANCE, null),
+ Collections.singletonList(LanceBlobTypes.toArrowField("item", true, blobType)));
+
+ Type type = CONVERTER.toGravitino(listField);
+
+ assertEquals(Types.ListType.of(Types.ExternalType.of(blobType), true), type);
+ assertEquals(
+ new Field(
+ "images",
+ new FieldType(true, ArrowType.List.INSTANCE, null),
+ Collections.singletonList(LanceBlobTypes.toArrowField("element", true, blobType))),
+ CONVERTER.toArrowField("images", type, true));
+ }
+
+ @Test
+ void testListWithNonCanonicalBlobChildKeepsBlobMetadata() {
+ Map<String, String> blobMetadata = Map.of("lance-encoding:blob", "true");
+ Field listField =
+ new Field(
+ "images",
+ new FieldType(true, ArrowType.List.INSTANCE, null),
+ Collections.singletonList(
+ new Field(
+ "item",
+ new FieldType(true, ArrowType.Binary.INSTANCE, null, blobMetadata),
+ null)));
+
+ Type type = CONVERTER.toGravitino(listField);
+
+ Types.ListType listType = assertInstanceOf(Types.ListType.class, type);
+ Types.ExternalType elementType =
+ assertInstanceOf(Types.ExternalType.class, listType.elementType());
+ assertTrue(elementType.catalogString().startsWith("{"));
+ assertEquals(
+ new Field(
+ "images",
+ new FieldType(true, ArrowType.List.INSTANCE, null),
+ Collections.singletonList(
+ new Field(
+ "element",
+ new FieldType(true, ArrowType.Binary.INSTANCE, null, blobMetadata),
+ null))),
+ CONVERTER.toArrowField("images", type, true));
+ }
+
+ @Test
+ void testLargeAndFixedSizeListWithBlobChildRoundTrip() {
+ Field blobChild = LanceBlobTypes.toArrowField("item", true, LanceBlobTypes.BLOB);
+ assertJsonExternalTypeRoundTrips(
+ new Field(
+ "images",
+ new FieldType(true, ArrowType.LargeList.INSTANCE, null),
+ Collections.singletonList(blobChild)));
+ assertJsonExternalTypeRoundTrips(
+ new Field(
+ "images",
+ new FieldType(true, new ArrowType.FixedSizeList(2), null),
+ Collections.singletonList(blobChild)));
+ }
+
+ @Test
+ void testStructWithBlobListConvertsToNativeTypes() {
+ Field structField =
+ new Field(
+ "record",
+ new FieldType(true, ArrowType.Struct.INSTANCE, null),
+ Collections.singletonList(
+ new Field(
+ "images",
+ new FieldType(true, ArrowType.List.INSTANCE, null),
+ Collections.singletonList(
+ LanceBlobTypes.toArrowField("element", true, LanceBlobTypes.BLOB)))));
+
+ Type type = CONVERTER.toGravitino(structField);
+
+ assertEquals(
+ Types.StructType.of(
+ Types.StructType.Field.of(
+ "images",
+ Types.ListType.of(Types.ExternalType.of(LanceBlobTypes.BLOB), true),
+ true,
+ null)),
+ type);
+ assertEquals(structField, CONVERTER.toArrowField("record", type, true));
+ }
+
+ @Test
+ void testMapWithBlobValueConvertsToNativeMap() {
+ Field mapField =
+ new Field(
+ "images",
+ new FieldType(true, new ArrowType.Map(false), null),
+ Collections.singletonList(
+ new Field(
+ MapVector.DATA_VECTOR_NAME,
+ new FieldType(false, ArrowType.Struct.INSTANCE, null),
+ Arrays.asList(
+ new Field(
+ MapVector.KEY_NAME,
+ new FieldType(false, ArrowType.Utf8.INSTANCE, null),
+ null),
+ LanceBlobTypes.toArrowField(
+ MapVector.VALUE_NAME, true, LanceBlobTypes.LEGACY_BLOB)))));
+
+ Type type = CONVERTER.toGravitino(mapField);
+
+ assertEquals(
+ Types.MapType.of(
+ Types.StringType.get(), Types.ExternalType.of(LanceBlobTypes.LEGACY_BLOB), true),
+ type);
+ assertEquals(mapField, CONVERTER.toArrowField("images", type, true));
+ }
+
+ @Test
+ void testUnionWithBlobChildConvertsToNativeUnion() {
+ Field unionField =
+ new Field(
+ "value",
+ new FieldType(
+ true,
+ new ArrowType.Union(
+ UnionMode.Sparse,
+ new int[] {MinorType.LARGEVARBINARY.ordinal(), MinorType.INT.ordinal()}),
+ null),
+ Arrays.asList(
+ LanceBlobTypes.toArrowField("image", true, LanceBlobTypes.LEGACY_BLOB),
+ new Field("number", new FieldType(true, new ArrowType.Int(32, true), null), null)));
+
+ Type type = CONVERTER.toGravitino(unionField);
+
+ assertEquals(
+ Types.UnionType.of(
+ Types.ExternalType.of(LanceBlobTypes.LEGACY_BLOB), Types.IntegerType.get()),
+ type);
+ Field blobChild = CONVERTER.toArrowField("value", type, true).getChildren().get(0);
+ assertEquals(ArrowType.LargeBinary.INSTANCE, blobChild.getType());
+ assertEquals(Map.of("lance-encoding:blob", "true"), blobChild.getMetadata());
+ }
+
+ @Test
+ void testJsonExternalTypeUsesColumnName() {
+ Field field =
+ new Field("old_name", new FieldType(true, ArrowType.LargeUtf8.INSTANCE, null), null);
+ Type type = CONVERTER.toGravitino(field);
+
+ Field renamed = CONVERTER.toArrowField("new_name", type, true);
+
+ assertEquals(
+ new Field("new_name", new FieldType(true, ArrowType.LargeUtf8.INSTANCE, null), null),
+ renamed);
+ }
+
+ @Test
+ void testLegacyJsonExternalTypeStillParses() {
+ String json =
+ "{\"name\":\"col\",\"nullable\":true,\"type\":{\"name\":\"largeutf8\"},\"children\":[]}";
+
+ Field field = CONVERTER.toArrowField("col", Types.ExternalType.of(json), true);
+
+ assertEquals(
+ new Field("col", new FieldType(true, ArrowType.LargeUtf8.INSTANCE, null), null), field);
+ }
+
+ private static void assertJsonExternalTypeRoundTrips(Field field) {
+ Type type = CONVERTER.toGravitino(field);
+
+ Types.ExternalType externalType = assertInstanceOf(Types.ExternalType.class, type);
+ assertTrue(externalType.catalogString().startsWith("{"));
+ assertEquals(field, CONVERTER.toArrowField(field.getName(), type, field.isNullable()));
+ }
+
@ParameterizedTest(name = "[{index}] name={0}, type={1}, nullable={2}")
@MethodSource("toArrowFieldArguments")
@DisplayName("Test toArrowField for various types")