Skip to content

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

[#10445] improvement(lance): Upgrade lance-core to v2.0.1 and lance-namespace-core to v0.4.5 (#10637)

godbiaod9e87243cef6
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 1362b917a7..a1342e1cc9 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
@@ -23,13 +23,6 @@ import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
-import com.lancedb.lance.Dataset;
-import com.lancedb.lance.WriteParams;
-import com.lancedb.lance.index.DistanceType;
-import com.lancedb.lance.index.IndexParams;
-import com.lancedb.lance.index.IndexType;
-import com.lancedb.lance.index.vector.VectorIndexParams;
-import com.lancedb.lance.schema.ColumnAlteration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -59,6 +52,14 @@ import org.apache.gravitino.rel.expressions.sorts.SortOrder;
import org.apache.gravitino.rel.expressions.transforms.Transform;
import org.apache.gravitino.rel.indexes.Index;
import org.apache.gravitino.storage.IdGenerator;
+import org.lance.Dataset;
+import org.lance.WriteParams;
+import org.lance.index.DistanceType;
+import org.lance.index.IndexOptions;
+import org.lance.index.IndexParams;
+import org.lance.index.IndexType;
+import org.lance.index.vector.VectorIndexParams;
+import org.lance.schema.ColumnAlteration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -278,11 +279,13 @@ public class LanceTableOperations extends ManagedTableOperations {
Map<String, String> storageProps = LancePropertiesUtils.getLanceStorageOptions(properties);
try (Dataset ignored =
- Dataset.create(
- new RootAllocator(),
- location,
- convertColumnsToArrowSchema(columns),
- new WriteParams.Builder().withStorageOptions(storageProps).build())) {
+ Dataset.write()
+ .allocator(new RootAllocator())
+ .schema(convertColumnsToArrowSchema(columns))
+ .uri(location)
+ .mode(WriteParams.WriteMode.CREATE)
+ .storageOptions(storageProps)
+ .execute()) {
// Only create the table metadata in Gravitino after the Lance dataset is successfully
// created.
long datasetVersion = ignored.version();
@@ -349,13 +352,15 @@ public class LanceTableOperations extends ManagedTableOperations {
IndexType indexType = IndexType.valueOf(addIndex.getType().name());
IndexParams indexParams = getIndexParamsByIndexType(indexType);
dataset.createIndex(
- Arrays.stream(addIndex.getFieldNames())
- .map(field -> String.join(".", field))
- .collect(Collectors.toList()),
- indexType,
- Optional.of(addIndex.getName()),
- indexParams,
- true);
+ IndexOptions.builder(
+ Arrays.stream(addIndex.getFieldNames())
+ .map(field -> String.join(".", field))
+ .collect(Collectors.toList()),
+ indexType,
+ indexParams)
+ .replace(true)
+ .withIndexName(addIndex.getName())
+ .build());
} else if (change instanceof TableChange.RenameColumn renameColumn) {
ColumnAlteration lanceColumnAlter =
new ColumnAlteration.Builder(String.join(".", renameColumn.fieldName()))
@@ -380,7 +385,7 @@ public class LanceTableOperations extends ManagedTableOperations {
}
Dataset openDataset(String location) {
- return Dataset.open(location, new RootAllocator());
+ return Dataset.open().allocator(new RootAllocator()).uri(location).build();
}
private IndexParams getIndexParamsByIndexType(IndexType indexType) {
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 ef1d0e76e3..c102d321e2 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
@@ -21,16 +21,11 @@ package org.apache.gravitino.catalog.lakehouse.lance;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_CREATION_MODE;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import com.google.common.collect.Maps;
-import com.lancedb.lance.Dataset;
-import com.lancedb.lance.Version;
-import com.lancedb.lance.index.IndexParams;
-import com.lancedb.lance.index.IndexType;
import java.util.Map;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.NameIdentifier;
@@ -47,6 +42,9 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
+import org.lance.Dataset;
+import org.lance.Version;
+import org.lance.index.IndexOptions;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -124,9 +122,7 @@ public class TestLanceTableOperations {
InOrder inOrder = Mockito.inOrder(dataset);
inOrder.verify(dataset).alterColumns(anyList());
- inOrder
- .verify(dataset)
- .createIndex(anyList(), any(IndexType.class), any(), any(IndexParams.class), eq(true));
+ inOrder.verify(dataset).createIndex(any(IndexOptions.class));
inOrder.verify(dataset).dropColumns(anyList());
inOrder.verify(dataset).getVersion();
}
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java
index 7f4ef535af..4a39f18ccf 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java
@@ -27,14 +27,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
-import com.lancedb.lance.Dataset;
-import com.lancedb.lance.Fragment;
-import com.lancedb.lance.FragmentMetadata;
-import com.lancedb.lance.Transaction;
-import com.lancedb.lance.WriteParams;
-import com.lancedb.lance.ipc.LanceScanner;
-import com.lancedb.lance.ipc.ScanOptions;
-import com.lancedb.lance.operation.Append;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -87,6 +79,14 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.lance.Dataset;
+import org.lance.Fragment;
+import org.lance.FragmentMetadata;
+import org.lance.Transaction;
+import org.lance.WriteParams;
+import org.lance.ipc.LanceScanner;
+import org.lance.ipc.ScanOptions;
+import org.lance.operation.Append;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -358,7 +358,7 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {
null);
// Now try to read the lance directory and check it.
- try (Dataset dataset = Dataset.open(tableLocation)) {
+ try (Dataset dataset = Dataset.open().uri(tableLocation).build()) {
org.apache.arrow.vector.types.pojo.Schema lanceSchema = dataset.getSchema();
List<Field> fields = lanceSchema.getFields();
for (Field field : fields) {
@@ -470,7 +470,12 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {
root.setRowCount(index);
fragmentMetas =
- Fragment.create(tableLocation, rootAllocator, root, new WriteParams.Builder().build());
+ Fragment.write()
+ .datasetUri(tableLocation)
+ .allocator(rootAllocator)
+ .data(root)
+ .writeParams(new WriteParams.Builder().build())
+ .execute();
return fragmentMetas;
}
}
@@ -739,7 +744,12 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {
try (RootAllocator allocator = new RootAllocator();
Dataset dataset =
- Dataset.create(allocator, location, arrowSchema, new WriteParams.Builder().build())) {
+ Dataset.write()
+ .allocator(allocator)
+ .schema(arrowSchema)
+ .uri(location)
+ .mode(WriteParams.WriteMode.CREATE)
+ .execute()) {
// Dataset created successfully
}
@@ -811,7 +821,12 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {
try (RootAllocator allocator = new RootAllocator();
Dataset dataset =
- Dataset.create(allocator, location, arrowSchema, new WriteParams.Builder().build())) {
+ Dataset.write()
+ .allocator(allocator)
+ .schema(arrowSchema)
+ .uri(location)
+ .mode(WriteParams.WriteMode.CREATE)
+ .execute()) {
// Dataset created
}
@@ -894,7 +909,12 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {
try (RootAllocator allocator = new RootAllocator();
Dataset dataset =
- Dataset.create(allocator, location, arrowSchema, new WriteParams.Builder().build())) {
+ Dataset.write()
+ .allocator(allocator)
+ .schema(arrowSchema)
+ .uri(location)
+ .mode(WriteParams.WriteMode.CREATE)
+ .execute()) {
// Dataset created
}
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
index eb895b4046..bdf52f367a 100644
--- a/core/build.gradle.kts
+++ b/core/build.gradle.kts
@@ -53,7 +53,7 @@ dependencies {
exclude(group = "org.junit.jupiter", module = "*") // provided by test scope
exclude(group = "com.fasterxml.jackson.jaxrs", module = "jackson-jaxrs-json-provider") // using gravitino's version
exclude(group = "org.apache.httpcomponents.client5", module = "*") // provided by gravitino
- exclude(group = "com.lancedb", module = "lance-namespace-core") // This is unnecessary in the core module
+ exclude(group = "org.lance", module = "lance-namespace-core") // This is unnecessary in the core module
}
implementation(libs.mybatis)
diff --git a/core/src/main/java/org/apache/gravitino/stats/storage/LancePartitionStatisticStorage.java b/core/src/main/java/org/apache/gravitino/stats/storage/LancePartitionStatisticStorage.java
index ea2d000cc5..724e602372 100644
--- a/core/src/main/java/org/apache/gravitino/stats/storage/LancePartitionStatisticStorage.java
+++ b/core/src/main/java/org/apache/gravitino/stats/storage/LancePartitionStatisticStorage.java
@@ -28,15 +28,6 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import com.lancedb.lance.Dataset;
-import com.lancedb.lance.Fragment;
-import com.lancedb.lance.FragmentMetadata;
-import com.lancedb.lance.ReadOptions;
-import com.lancedb.lance.Transaction;
-import com.lancedb.lance.WriteParams;
-import com.lancedb.lance.ipc.LanceScanner;
-import com.lancedb.lance.ipc.ScanOptions;
-import com.lancedb.lance.operation.Append;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -76,6 +67,15 @@ import org.apache.gravitino.stats.PartitionStatisticsUpdate;
import org.apache.gravitino.stats.StatisticValue;
import org.apache.gravitino.utils.MetadataObjectUtil;
import org.apache.gravitino.utils.PrincipalUtils;
+import org.lance.Dataset;
+import org.lance.Fragment;
+import org.lance.FragmentMetadata;
+import org.lance.ReadOptions;
+import org.lance.Transaction;
+import org.lance.WriteParams;
+import org.lance.ipc.LanceScanner;
+import org.lance.ipc.ScanOptions;
+import org.lance.operation.Append;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -438,16 +438,18 @@ public class LancePartitionStatisticStorage implements PartitionStatisticStorage
root.setRowCount(index);
fragmentMetas =
- Fragment.create(
- getFilePath(tableId),
- allocator,
- root,
- new WriteParams.Builder()
- .withMaxRowsPerFile(maxRowsPerFile)
- .withMaxBytesPerFile(maxBytesPerFile)
- .withMaxRowsPerGroup(maxRowsPerGroup)
- .withStorageOptions(properties)
- .build());
+ Fragment.write()
+ .datasetUri(getFilePath(tableId))
+ .allocator(allocator)
+ .data(root)
+ .writeParams(
+ new WriteParams.Builder()
+ .withMaxRowsPerFile(maxRowsPerFile)
+ .withMaxBytesPerFile(maxBytesPerFile)
+ .withMaxRowsPerGroup(maxRowsPerGroup)
+ .withStorageOptions(properties)
+ .build())
+ .execute();
return fragmentMetas;
}
}
@@ -581,16 +583,23 @@ public class LancePartitionStatisticStorage implements PartitionStatisticStorage
private Dataset open(String fileName) {
try {
- return Dataset.open(
- allocator,
- fileName,
- new ReadOptions.Builder()
- .setMetadataCacheSizeBytes(metadataFileCacheSize)
- .setIndexCacheSizeBytes(indexCacheSize)
- .build());
+ return Dataset.open()
+ .allocator(allocator)
+ .uri(fileName)
+ .readOptions(
+ new ReadOptions.Builder()
+ .setMetadataCacheSizeBytes(metadataFileCacheSize)
+ .setIndexCacheSizeBytes(indexCacheSize)
+ .build())
+ .build();
} catch (IllegalArgumentException illegalArgumentException) {
if (illegalArgumentException.getMessage().contains("was not found")) {
- return Dataset.create(allocator, fileName, SCHEMA, new WriteParams.Builder().build());
+ return Dataset.write()
+ .allocator(allocator)
+ .schema(SCHEMA)
+ .uri(fileName)
+ .mode(WriteParams.WriteMode.CREATE)
+ .execute();
} else {
throw illegalArgumentException;
}
diff --git a/core/src/test/java/org/apache/gravitino/stats/storage/TestLancePartitionStatisticStorage.java b/core/src/test/java/org/apache/gravitino/stats/storage/TestLancePartitionStatisticStorage.java
index d1bee34f38..cc298e9b03 100644
--- a/core/src/test/java/org/apache/gravitino/stats/storage/TestLancePartitionStatisticStorage.java
+++ b/core/src/test/java/org/apache/gravitino/stats/storage/TestLancePartitionStatisticStorage.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.when;
import com.github.benmanes.caffeine.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
-import com.lancedb.lance.Dataset;
import java.io.File;
import java.nio.file.Files;
import java.util.List;
@@ -50,6 +49,7 @@ import org.apache.gravitino.stats.StatisticValue;
import org.apache.gravitino.stats.StatisticValues;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.lance.Dataset;
import org.mockito.InOrder;
public class TestLancePartitionStatisticStorage {
diff --git a/docs/lance-rest-integration.md b/docs/lance-rest-integration.md
index 8fd1fc36b6..101213dfcd 100644
--- a/docs/lance-rest-integration.md
+++ b/docs/lance-rest-integration.md
@@ -22,7 +22,8 @@ The following table outlines the tested compatibility between Gravitino versions
| Gravitino Version (Lance REST) | Supported lance-spark Versions | Supported lance-ray Versions |
|--------------------------------|--------------------------------|------------------------------|
-| 1.1.1 | 0.0.10 – 0.0.15 | 0.0.6 – 0.0.8 |
+| 1.1.1 - 1.2.1 | 0.0.10 - 0.0.15 | 0.0.6 - 0.0.8 |
+| 1.3.0 | 0.1.0 - 0.2.0 | 0.0.6 - 0.2.0 |
:::note
- These version ranges show which versions are expected to work together.
@@ -157,7 +158,7 @@ pip install lance-ray
:::info
- Ray will be automatically installed if not already present
-- lance-ray is currently tested with Ray versions 2.41.0 to 2.50.0
+- The lance-namespace version must be less than or equal to 0.4.5.
- Ensure Ray version compatibility in your environment before deployment
:::
diff --git a/docs/lance-rest-service.md b/docs/lance-rest-service.md
index f266787f50..5a299ac924 100644
--- a/docs/lance-rest-service.md
+++ b/docs/lance-rest-service.md
@@ -81,7 +81,8 @@ The Lance REST service provides comprehensive support for namespace management,
| TableExists | Check whether a table exists | POST | `/lance/v1/table/{id}/exists` | 1.1.0 |
| RegisterTable | Register an existing Lance table to a namespace | POST | `/lance/v1/table/{id}/register` | 1.1.0 |
| DeregisterTable | Unregister a table from a namespace (metadata only, data remains) | POST | `/lance/v1/table/{id}/deregister` | 1.1.0 |
-| CreateEmptyTable | Declare a table and store the metadata without touching lance table data, for more, please refer to [doc](https://docs.lancedb.com/api-reference/rest/table/create-an-empty-table) | POST | `/lance/v1/table/{id}/create-empty` | 1.1.0 |
+| CreateEmptyTable | **Deprecated**: Use `DeclareTable` instead. Declare a table and store the metadata without touching lance table data, for more, please refer to [doc](https://docs.lancedb.com/api-reference/rest/table/create-an-empty-table) | POST | `/lance/v1/table/{id}/create-empty` | 1.1.0 |
+| DeclareTable | Declare a table and store the metadata without touching lance table data. This is the preferred replacement for `CreateEmptyTable`. | POST | `/lance/v1/table/{id}/declare` | 1.3.0 |
More details, please refer to the [Lance REST API specification](https://lance.org/format/namespace/rest/catalog-spec/)
@@ -89,6 +90,9 @@ More details, please refer to the [Lance REST API specification](https://lance.o
Some operations have specific behaviors and modes. Below are important details to consider:
+Mode values are parsed case-insensitively. The examples below use lowercase values as the
+REST-style canonical form.
+
#### Namespace Operations
**CreateNamespace** supports three modes:
@@ -273,17 +277,26 @@ curl -X POST http://localhost:9101/lance/v1/table/lance_catalog%24schema%24table
-d '{
"id": ["lance_catalog", "schema", "table01"],
"location": "/tmp/lance_catalog/schema/table01",
- "mode": "CREATE"
+ "mode": "create"
}'
# Create a new empty table
+# x-lance-table-properties is optional; if omitted, it defaults to an empty map.
curl -X POST http://localhost:9101/lance/v1/table/lance_catalog%24schema%24table02/create-empty \
-H 'Content-Type: application/json' \
+ -H "x-lance-table-properties: {\"description\":\"This is table02\"}" \
-d '{
"id": ["lance_catalog", "schema", "table02"],
- "location": "/tmp/lance_catalog/schema/table02",
- "properties": { "description": "This is table02" }
+ "location": "/tmp/lance_catalog/schema/table02"
}'
+
+# Declare a table (preferred replacement for create-empty)
+curl -X POST http://localhost:9101/lance/v1/table/lance_catalog%24schema%24table04/declare \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "id": ["lance_catalog", "schema", "table04"],
+ "location": "/tmp/lance_catalog/schema/table04"
+ }'
# Create a table with schema, the schema is inferred from the Arrow IPC file
curl -X POST \
@@ -298,10 +311,13 @@ curl -X POST \
<TabItem value="java" label="Java">
```java
-// Add dependency: implementation("com.lancedb:lance-namespace-core:0.0.20")
+// Add dependency: implementation("org.lance:lance-namespace-core:0.4.5")
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
+import org.lance.namespace.client.apache.ApiClient;
+import org.lance.namespace.client.apache.api.TableApi;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -309,48 +325,51 @@ import java.util.Map;
private final BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE);
Map<String, String> props = new HashMap<>();
-props.put(RestNamespaceConfig.URI, "http://localhost:9101/lance");
-props.put(RestNamespaceConfig.DELIMITER, RestNamespaceConfig.DELIMITER_DEFAULT);
+props.put("uri", "http://localhost:9101/lance");
+props.put("delimiter", "$");
-LanceNamespace ns = LanceNamespaces.connect("rest", props, null, allocator);
+LanceNamespace ns = LanceNamespace.connect("rest", props, allocator);
// Create catalog namespace
CreateNamespaceRequest createCatalogNsRequest = new CreateNamespaceRequest();
createCatalogNsRequest.addIdItem("lance_catalog");
-createCatalogNsRequest.setMode(CreateNamespaceRequest.ModeEnum.CREATE);
+createCatalogNsRequest.setMode("create");
ns.createNamespace(createCatalogNsRequest);
// Create schema namespace
CreateNamespaceRequest createSchemaNsRequest = new CreateNamespaceRequest();
createSchemaNsRequest.addIdItem("lance_catalog");
createSchemaNsRequest.addIdItem("schema");
-createSchemaNsRequest.setMode(CreateNamespaceRequest.ModeEnum.CREATE);
+createSchemaNsRequest.setMode("create");
ns.createNamespace(createSchemaNsRequest);
// Register a table
RegisterTableRequest registerTableRequest = new RegisterTableRequest();
registerTableRequest.setLocation("/tmp/lance_catalog/schema/table01");
-registerTableRequest.setId(Lists.newArrayList("lance_catalog", "schema", "table01"));
-registerTableRequest.setMode(RegisterTableRequest.ModeEnum.CREATE);
+registerTableRequest.setId(Arrays.asList("lance_catalog", "schema", "table01"));
+registerTableRequest.setMode("create");
ns.registerTable(registerTableRequest);
// Create an empty table
CreateEmptyTableRequest createEmptyTableRequest = new CreateEmptyTableRequest();
createEmptyTableRequest.setLocation("/tmp/lance_catalog/schema/table02");
-createEmptyTableRequest.setId(Lists.newArrayList("lance_catalog", "schema", "table02"));
+createEmptyTableRequest.setId(Arrays.asList("lance_catalog", "schema", "table02"));
ns.createEmptyTable(createEmptyTableRequest);
-// Create a table with schema inferred from Arrow IPC file
-CreateTableRequest createTableRequest = new CreateTableRequest();
-createTableRequest.setIds(Lists.newArrayList("lance_catalog", "schema", "table03"));
-createTableRequest.setLocation("/tmp/lance_catalog/schema/table03");
+// Create a table with schema inferred from Arrow IPC file.
+// For REST create API, location/properties are passed via headers.
org.apache.arrow.vector.types.pojo.Schema schema =
new org.apache.arrow.vector.types.pojo.Schema(
Arrays.asList(
Field.nullable("id", new ArrowType.Int(32, true)),
Field.nullable("value", new ArrowType.Utf8())));
byte[] body = ArrowUtils.generateIpcStream(schema);
-ns.createTable(createTableRequest, body);
+TableApi tableApi = new TableApi(new ApiClient().setBasePath("http://localhost:9101/lance"));
+Map<String, String> createTableHeaders = new HashMap<>();
+createTableHeaders.put("x-lance-table-location", "/tmp/lance_catalog/schema/table03");
+createTableHeaders.put("x-lance-table-properties", "{}");
+tableApi.createTable(
+ "lance_catalog$schema$table03", body, "$", "create", createTableHeaders);
```
@@ -358,9 +377,10 @@ ns.createTable(createTableRequest, body);
<TabItem value="python" label="Python">
```python
-# Install: pip install lance-namespace==0.0.20
+# Install: pip install lance-namespace==0.4.5
import lance_namespace as ln
+import requests
# Connect to Lance REST service
ns = ln.connect("rest", {"uri": "http://your_lance_rest:9101/lance"})
@@ -385,16 +405,25 @@ create_empty_table_request = ln.CreateEmptyTableRequest(
id=['lance_catalog', 'schema', 'table02'],
location='/tmp/lance_catalog/schema/table02'
)
+ns.create_empty_table(create_empty_table_request)
-# Create a table with schema inferred from Arrow IPC file
-create_table_request = ln.CreateTableRequest(
- id=['lance_catalog', 'schema', 'table03'],
- location='/tmp/lance_catalog/schema/table03'
-)
+# Create a table with schema inferred from Arrow IPC file.
+# For REST create API, location/properties are passed via headers.
with open('schema.ipc', 'rb') as f:
body = f.read()
-ns.create_table(create_table_request, body)
+response = requests.post(
+ "http://your_lance_rest:9101/lance/v1/table/lance_catalog%24schema%24table03/create",
+ params={"delimiter": "$", "mode": "create"},
+ headers={
+ "Content-Type": "application/vnd.apache.arrow.stream",
+ "x-lance-table-location": "/tmp/lance_catalog/schema/table03",
+ "x-lance-table-properties": "{}",
+ },
+ data=body,
+ timeout=30,
+)
+response.raise_for_status()
```
</TabItem>
@@ -402,4 +431,4 @@ ns.create_table(create_table_request, body)
## Integration with Lance REST
-To use the Lance REST service with Apache Spark, Ray and other engines, please refer to [lance-rest-integration](./lance-rest-integration.md) for more details.
\ No newline at end of file
+To use the Lance REST service with Apache Spark, Ray and other engines, please refer to [lance-rest-integration](./lance-rest-integration.md) for more details.
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index f5d0b34629..b599024e42 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -28,8 +28,8 @@ guava = "32.1.3-jre"
lombok = "1.18.20"
slf4j = "2.0.16"
log4j = "2.24.3"
-lance = "0.39.0"
-lance-namespace = "0.0.20"
+lance = "2.0.1"
+lance-namespace = "0.4.5"
delta-kernel = "3.3.0"
jetty = "9.4.58.v20250814"
jersey = "2.41"
@@ -175,8 +175,8 @@ log4j-api = { group = "org.apache.logging.log4j", name = "log4j-api", version.re
log4j-core = { group = "org.apache.logging.log4j", name = "log4j-core", version.ref = "log4j" }
log4j-12-api = { group = "org.apache.logging.log4j", name = "log4j-1.2-api", version.ref = "log4j" }
log4j-layout-template-json = { group = "org.apache.logging.log4j", name = "log4j-layout-template-json", version.ref = "log4j" }
-lance = { group = "com.lancedb", name = "lance-core", version.ref = "lance" }
-lance-namespace-core = { group = "com.lancedb", name = "lance-namespace-core", version.ref = "lance-namespace" }
+lance = { group = "org.lance", name = "lance-core", version.ref = "lance" }
+lance-namespace-core = { group = "org.lance", name = "lance-namespace-core", version.ref = "lance-namespace" }
delta-kernel = { group = "io.delta", name = "delta-kernel-api", version.ref = "delta-kernel" }
delta-kernel-defaults = { group = "io.delta", name = "delta-kernel-defaults", version.ref = "delta-kernel" }
jakarta-validation-api = { group = "jakarta.validation", name = "jakarta.validation-api", version.ref = "jakarta-validation" }
diff --git a/lance/lance-common/build.gradle.kts b/lance/lance-common/build.gradle.kts
index e0c7546a6a..886fdbccd1 100644
--- a/lance/lance-common/build.gradle.kts
+++ b/lance/lance-common/build.gradle.kts
@@ -41,8 +41,9 @@ dependencies {
implementation(libs.jackson.datatype.jdk8)
implementation(libs.jackson.datatype.jsr310)
implementation(libs.jackson.jaxrs.json.provider)
+ implementation(libs.lance)
implementation(libs.lance.namespace.core) {
- exclude(group = "com.lancedb", module = "lance-core")
+ exclude(group = "org.lance", module = "lance-core")
exclude(group = "com.google.guava", module = "guava") // provided by gravitino
exclude(group = "com.fasterxml.jackson.core", module = "*") // provided by gravitino
exclude(group = "com.fasterxml.jackson.datatype", module = "*") // provided by gravitino
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceNamespaceOperations.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceNamespaceOperations.java
index 36d55c03e9..e9e26c29e6 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceNamespaceOperations.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceNamespaceOperations.java
@@ -18,15 +18,13 @@
*/
package org.apache.gravitino.lance.common.ops;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.model.CreateNamespaceRequest;
-import com.lancedb.lance.namespace.model.CreateNamespaceResponse;
-import com.lancedb.lance.namespace.model.DescribeNamespaceResponse;
-import com.lancedb.lance.namespace.model.DropNamespaceRequest;
-import com.lancedb.lance.namespace.model.DropNamespaceResponse;
-import com.lancedb.lance.namespace.model.ListNamespacesResponse;
-import com.lancedb.lance.namespace.model.ListTablesResponse;
import java.util.Map;
+import org.lance.namespace.errors.LanceNamespaceException;
+import org.lance.namespace.model.CreateNamespaceResponse;
+import org.lance.namespace.model.DescribeNamespaceResponse;
+import org.lance.namespace.model.DropNamespaceResponse;
+import org.lance.namespace.model.ListNamespacesResponse;
+import org.lance.namespace.model.ListTablesResponse;
public interface LanceNamespaceOperations {
@@ -36,16 +34,10 @@ public interface LanceNamespaceOperations {
DescribeNamespaceResponse describeNamespace(String namespaceId, String delimiter);
CreateNamespaceResponse createNamespace(
- String namespaceId,
- String delimiter,
- CreateNamespaceRequest.ModeEnum mode,
- Map<String, String> properties);
+ String namespaceId, String delimiter, String mode, Map<String, String> properties);
DropNamespaceResponse dropNamespace(
- String namespaceId,
- String delimiter,
- DropNamespaceRequest.ModeEnum mode,
- DropNamespaceRequest.BehaviorEnum behavior);
+ String namespaceId, String delimiter, String mode, String behavior);
void namespaceExists(String namespaceId, String delimiter) throws LanceNamespaceException;
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceTableOperations.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceTableOperations.java
index c8b21ef3b2..dae9049958 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceTableOperations.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/LanceTableOperations.java
@@ -18,16 +18,15 @@
*/
package org.apache.gravitino.lance.common.ops;
-import com.lancedb.lance.namespace.model.CreateEmptyTableResponse;
-import com.lancedb.lance.namespace.model.CreateTableRequest;
-import com.lancedb.lance.namespace.model.CreateTableResponse;
-import com.lancedb.lance.namespace.model.DeregisterTableResponse;
-import com.lancedb.lance.namespace.model.DescribeTableResponse;
-import com.lancedb.lance.namespace.model.DropTableResponse;
-import com.lancedb.lance.namespace.model.RegisterTableRequest;
-import com.lancedb.lance.namespace.model.RegisterTableResponse;
import java.util.Map;
import java.util.Optional;
+import org.lance.namespace.model.CreateEmptyTableResponse;
+import org.lance.namespace.model.CreateTableResponse;
+import org.lance.namespace.model.DeclareTableResponse;
+import org.lance.namespace.model.DeregisterTableResponse;
+import org.lance.namespace.model.DescribeTableResponse;
+import org.lance.namespace.model.DropTableResponse;
+import org.lance.namespace.model.RegisterTableResponse;
public interface LanceTableOperations {
@@ -54,21 +53,37 @@ public interface LanceTableOperations {
*/
CreateTableResponse createTable(
String tableId,
- CreateTableRequest.ModeEnum mode,
+ String mode,
String delimiter,
String tableLocation,
Map<String, String> tableProperties,
byte[] arrowStreamBody);
/**
- * Create an new table without schema.
+ * Declare a table without touching storage. This is the preferred API for creating metadata-only
+ * table entries, replacing the deprecated {@link #createEmptyTable} method.
+ *
+ * @param tableId table ids are in the format of "{namespace}{delimiter}{table_name}"
+ * @param delimiter the delimiter used in the namespace
+ * @param tableLocation the location where the table data will be stored
+ * @param tableProperties the properties of the table
+ * @return the response of the declare table operation
+ */
+ DeclareTableResponse declareTable(
+ String tableId, String delimiter, String tableLocation, Map<String, String> tableProperties);
+
+ /**
+ * Create a new table without schema.
*
* @param tableId table ids are in the format of "{namespace}{delimiter}{table_name}"
* @param delimiter the delimiter used in the namespace
* @param tableLocation the location where the table data will be stored
* @param tableProperties the properties of the table
* @return the response of the create table operation
+ * @deprecated Use {@link #declareTable} instead.
*/
+ @Deprecated
+ @SuppressWarnings("deprecation")
CreateEmptyTableResponse createEmptyTable(
String tableId, String delimiter, String tableLocation, Map<String, String> tableProperties);
@@ -82,10 +97,7 @@ public interface LanceTableOperations {
* @return the response of the register table operation
*/
RegisterTableResponse registerTable(
- String tableId,
- RegisterTableRequest.ModeEnum mode,
- String delimiter,
- Map<String, String> tableProperties);
+ String tableId, String mode, String delimiter, Map<String, String> tableProperties);
/**
* Deregister a table. It will not delete the underlying lance data.
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/CommonUtil.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/CommonUtil.java
new file mode 100644
index 0000000000..056b2c235b
--- /dev/null
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/CommonUtil.java
@@ -0,0 +1,47 @@
+/*
+ * 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.base.Throwables;
+import java.util.Locale;
+import org.lance.namespace.errors.InvalidInputException;
+
+/** Utility methods used by Gravitino Lance namespace operations. */
+class CommonUtil {
+
+ private CommonUtil() {}
+
+ static String formatCurrentStackTrace() {
+ return Throwables.getStackTraceAsString(new RuntimeException("Captured stacktrace"));
+ }
+
+ static String normalizeToken(String value) {
+ return value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
+ }
+
+ static <E extends Enum<E>> E parseEnumToken(
+ Class<E> enumClass, String value, String errorMessagePrefix, String instance) {
+ try {
+ return Enum.valueOf(enumClass, normalizeToken(value));
+ } catch (IllegalArgumentException e) {
+ throw new InvalidInputException(
+ errorMessagePrefix + value, formatCurrentStackTrace(), instance);
+ }
+ }
+}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java
index 21052421d4..af461b8d8c 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNameSpaceOperations.java
@@ -24,17 +24,6 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.ObjectIdentifier;
-import com.lancedb.lance.namespace.model.CreateNamespaceRequest;
-import com.lancedb.lance.namespace.model.CreateNamespaceResponse;
-import com.lancedb.lance.namespace.model.DescribeNamespaceResponse;
-import com.lancedb.lance.namespace.model.DropNamespaceRequest;
-import com.lancedb.lance.namespace.model.DropNamespaceResponse;
-import com.lancedb.lance.namespace.model.ListNamespacesResponse;
-import com.lancedb.lance.namespace.model.ListTablesResponse;
-import com.lancedb.lance.namespace.util.CommonUtil;
-import com.lancedb.lance.namespace.util.PageUtil;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -52,20 +41,45 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.client.GravitinoClient;
-import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;
import org.apache.gravitino.exceptions.CatalogInUseException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NonEmptyCatalogException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
-import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.lance.common.ops.LanceNamespaceOperations;
+import org.lance.namespace.errors.InvalidInputException;
+import org.lance.namespace.errors.LanceNamespaceException;
+import org.lance.namespace.errors.NamespaceAlreadyExistsException;
+import org.lance.namespace.errors.NamespaceNotFoundException;
+import org.lance.namespace.model.CreateNamespaceResponse;
+import org.lance.namespace.model.DescribeNamespaceResponse;
+import org.lance.namespace.model.DropNamespaceResponse;
+import org.lance.namespace.model.ListNamespacesResponse;
+import org.lance.namespace.model.ListTablesResponse;
public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperations {
private final GravitinoLanceNamespaceWrapper namespaceWrapper;
private final GravitinoClient client;
+ // lance-namespace 0.4.5 switched mode/behavior fields to plain strings in request models.
+ // Keep local enums as normalized internal states for type-safe branching.
+ private enum CreateMode {
+ CREATE,
+ EXIST_OK,
+ OVERWRITE
+ }
+
+ private enum DropMode {
+ FAIL,
+ SKIP
+ }
+
+ private enum DropBehavior {
+ RESTRICT,
+ CASCADE
+ }
+
public GravitinoLanceNameSpaceOperations(GravitinoLanceNamespaceWrapper namespaceWrapper) {
this.namespaceWrapper = namespaceWrapper;
this.client = namespaceWrapper.getClient();
@@ -143,10 +157,7 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
@Override
public CreateNamespaceResponse createNamespace(
- String namespaceId,
- String delimiter,
- CreateNamespaceRequest.ModeEnum mode,
- Map<String, String> properties) {
+ String namespaceId, String delimiter, String mode, Map<String, String> properties) {
ObjectIdentifier nsId = ObjectIdentifier.of(namespaceId, delimiter);
Preconditions.checkArgument(
nsId.levels() <= 2 && nsId.levels() > 0,
@@ -155,10 +166,14 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
switch (nsId.levels()) {
case 1:
- return createOrUpdateCatalog(nsId.levelAtListPos(0), mode, properties);
+ return createOrUpdateCatalog(
+ nsId.levelAtListPos(0), parseCreateMode(namespaceId, mode), properties);
case 2:
return createOrUpdateSchema(
- nsId.levelAtListPos(0), nsId.levelAtListPos(1), mode, properties);
+ nsId.levelAtListPos(0),
+ nsId.levelAtListPos(1),
+ parseCreateMode(namespaceId, mode),
+ properties);
default:
throw new IllegalArgumentException(
"Expected at most 2-level and at least 1-level namespace but got: " + namespaceId);
@@ -167,10 +182,7 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
@Override
public DropNamespaceResponse dropNamespace(
- String namespaceId,
- String delimiter,
- DropNamespaceRequest.ModeEnum mode,
- DropNamespaceRequest.BehaviorEnum behavior) {
+ String namespaceId, String delimiter, String mode, String behavior) {
ObjectIdentifier nsId = ObjectIdentifier.of(namespaceId, delimiter);
Preconditions.checkArgument(
nsId.levels() <= 2 && nsId.levels() > 0,
@@ -179,9 +191,16 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
switch (nsId.levels()) {
case 1:
- return dropCatalog(nsId.levelAtListPos(0), mode, behavior);
+ return dropCatalog(
+ nsId.levelAtListPos(0),
+ parseDropMode(namespaceId, mode),
+ parseDropBehavior(namespaceId, behavior));
case 2:
- return dropSchema(nsId.levelAtListPos(0), nsId.levelAtListPos(1), mode, behavior);
+ return dropSchema(
+ nsId.levelAtListPos(0),
+ nsId.levelAtListPos(1),
+ parseDropMode(namespaceId, mode),
+ parseDropBehavior(namespaceId, behavior));
default:
throw new IllegalArgumentException(
"Expected at most 2-level and at least 1-level namespace but got: " + namespaceId);
@@ -200,17 +219,14 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
if (nsId.levels() == 2) {
String schemaName = nsId.levelAtListPos(1);
if (!catalog.asSchemas().schemaExists(schemaName)) {
- throw LanceNamespaceException.notFound(
- "Schema not found: " + schemaName,
- NoSuchSchemaException.class.getSimpleName(),
- schemaName,
- CommonUtil.formatCurrentStackTrace());
+ throw new NamespaceNotFoundException(
+ "Schema not found: " + schemaName, CommonUtil.formatCurrentStackTrace(), schemaName);
}
}
}
private CreateNamespaceResponse createOrUpdateCatalog(
- String catalogName, CreateNamespaceRequest.ModeEnum mode, Map<String, String> properties) {
+ String catalogName, CreateMode mode, Map<String, String> properties) {
CreateNamespaceResponse response = new CreateNamespaceResponse();
Catalog catalog;
@@ -232,11 +248,10 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
// Catalog exists, validate type
if (!namespaceWrapper.isLakehouseCatalog(catalog)) {
- throw LanceNamespaceException.conflict(
+ throw new NamespaceAlreadyExistsException(
"Catalog already exists but is not a lakehouse catalog: " + catalogName,
- CatalogAlreadyExistsException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ catalogName);
}
// Catalog exists, handle based on mode
@@ -246,11 +261,10 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
Optional.ofNullable(catalog.properties()).orElse(Collections.emptyMap()));
return response;
case CREATE:
- throw LanceNamespaceException.conflict(
+ throw new NamespaceAlreadyExistsException(
"Catalog already exists: " + catalogName,
- CatalogAlreadyExistsException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ catalogName);
case OVERWRITE:
CatalogChange[] changes =
buildChanges(
@@ -274,10 +288,7 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
}
private CreateNamespaceResponse createOrUpdateSchema(
- String catalogName,
- String schemaName,
- CreateNamespaceRequest.ModeEnum mode,
- Map<String, String> properties) {
+ String catalogName, String schemaName, CreateMode mode, Map<String, String> properties) {
CreateNamespaceResponse response = new CreateNamespaceResponse();
Catalog loadedCatalog = namespaceWrapper.loadAndValidateLakehouseCatalog(catalogName);
@@ -299,11 +310,10 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
Optional.ofNullable(schema.properties()).orElse(Collections.emptyMap()));
return response;
case CREATE:
- throw LanceNamespaceException.conflict(
+ throw new NamespaceAlreadyExistsException(
"Schema already exists: " + schemaName,
- SchemaAlreadyExistsException.class.getSimpleName(),
- schemaName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ schemaName);
case OVERWRITE:
SchemaChange[] changes =
buildChanges(
@@ -321,76 +331,60 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
}
private DropNamespaceResponse dropCatalog(
- String catalogName,
- DropNamespaceRequest.ModeEnum mode,
- DropNamespaceRequest.BehaviorEnum behavior) {
+ String catalogName, DropMode mode, DropBehavior behavior) {
try {
- boolean dropped =
- client.dropCatalog(catalogName, behavior == DropNamespaceRequest.BehaviorEnum.CASCADE);
+ boolean dropped = client.dropCatalog(catalogName, behavior == DropBehavior.CASCADE);
if (dropped) {
return new DropNamespaceResponse();
} else {
// Catalog did not exist
- if (mode == DropNamespaceRequest.ModeEnum.FAIL) {
- throw LanceNamespaceException.notFound(
+ if (mode == DropMode.FAIL) {
+ throw new NamespaceNotFoundException(
"Catalog not found: " + catalogName,
- NoSuchCatalogException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ catalogName);
}
return new DropNamespaceResponse(); // SKIP mode
}
} catch (NonEmptyCatalogException e) {
- throw LanceNamespaceException.badRequest(
+ throw new InvalidInputException(
String.format("Catalog %s is not empty", catalogName),
- NonEmptyCatalogException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ catalogName);
} catch (CatalogInUseException e) {
- throw LanceNamespaceException.badRequest(
+ throw new InvalidInputException(
String.format("Catalog %s is in use", catalogName),
- CatalogInUseException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ catalogName);
}
}
private DropNamespaceResponse dropSchema(
- String catalogName,
- String schemaName,
- DropNamespaceRequest.ModeEnum mode,
- DropNamespaceRequest.BehaviorEnum behavior) {
+ String catalogName, String schemaName, DropMode mode, DropBehavior behavior) {
try {
boolean dropped =
client
.loadCatalog(catalogName)
.asSchemas()
- .dropSchema(schemaName, behavior == DropNamespaceRequest.BehaviorEnum.CASCADE);
+ .dropSchema(schemaName, behavior == DropBehavior.CASCADE);
if (dropped) {
return new DropNamespaceResponse();
} else {
// Schema did not exist
- if (mode == DropNamespaceRequest.ModeEnum.FAIL) {
- throw LanceNamespaceException.notFound(
- "Schema not found: " + schemaName,
- NoSuchSchemaException.class.getSimpleName(),
- schemaName,
- CommonUtil.formatCurrentStackTrace());
+ if (mode == DropMode.FAIL) {
+ throw new NamespaceNotFoundException(
+ "Schema not found: " + schemaName, CommonUtil.formatCurrentStackTrace(), schemaName);
}
return new DropNamespaceResponse(); // SKIP mode
}
} catch (NoSuchCatalogException e) {
- throw LanceNamespaceException.notFound(
- "Catalog not found: " + catalogName,
- NoSuchCatalogException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ throw new NamespaceNotFoundException(
+ "Catalog not found: " + catalogName, CommonUtil.formatCurrentStackTrace(), catalogName);
} catch (NonEmptySchemaException e) {
- throw LanceNamespaceException.badRequest(
+ throw new InvalidInputException(
String.format("Schema %s is not empty.", schemaName),
- NonEmptySchemaException.class.getSimpleName(),
- schemaName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ schemaName);
}
}
@@ -414,6 +408,30 @@ public class GravitinoLanceNameSpaceOperations implements LanceNamespaceOperatio
return Stream.concat(setPropertiesStream, removePropertiesStream).toArray(arrayCreator);
}
+ private static CreateMode parseCreateMode(String instance, String mode) {
+ if (mode == null) {
+ return CreateMode.CREATE;
+ }
+ return CommonUtil.parseEnumToken(
+ CreateMode.class, mode, "Unknown create namespace mode: ", instance);
+ }
+
+ private static DropMode parseDropMode(String instance, String mode) {
+ if (mode == null) {
+ return DropMode.FAIL;
+ }
+ return CommonUtil.parseEnumToken(
+ DropMode.class, mode, "Unknown drop namespace mode: ", instance);
+ }
+
+ private static DropBehavior parseDropBehavior(String instance, String behavior) {
+ if (behavior == null) {
+ return DropBehavior.RESTRICT;
+ }
+ return CommonUtil.parseEnumToken(
+ DropBehavior.class, behavior, "Unknown drop namespace behavior: ", instance);
+ }
+
@Override
public ListTablesResponse listTables(
String namespaceId, String delimiter, String pageToken, Integer limit) {
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNamespaceWrapper.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNamespaceWrapper.java
index 0a48dd01e3..b7cc36ec23 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNamespaceWrapper.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceNamespaceWrapper.java
@@ -23,8 +23,6 @@ import static org.apache.gravitino.lance.common.config.LanceConfig.NAMESPACE_BAC
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.util.CommonUtil;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
@@ -35,6 +33,7 @@ import org.apache.gravitino.lance.common.config.LanceConfig;
import org.apache.gravitino.lance.common.ops.LanceNamespaceOperations;
import org.apache.gravitino.lance.common.ops.LanceTableOperations;
import org.apache.gravitino.lance.common.ops.NamespaceWrapper;
+import org.lance.namespace.errors.NamespaceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -125,18 +124,14 @@ public class GravitinoLanceNamespaceWrapper extends NamespaceWrapper {
try {
catalog = client.loadCatalog(catalogName);
} catch (NoSuchCatalogException e) {
- throw LanceNamespaceException.notFound(
- "Catalog not found: " + catalogName,
- NoSuchCatalogException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ throw new NamespaceNotFoundException(
+ "Catalog not found: " + catalogName, CommonUtil.formatCurrentStackTrace(), catalogName);
}
if (!isLakehouseCatalog(catalog)) {
- throw LanceNamespaceException.notFound(
+ throw new NamespaceNotFoundException(
"Catalog is not a lakehouse catalog: " + catalogName,
- NoSuchCatalogException.class.getSimpleName(),
- catalogName,
- CommonUtil.formatCurrentStackTrace());
+ CommonUtil.formatCurrentStackTrace(),
+ catalogName);
}
return catalog;
}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableAlterHandler.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableAlterHandler.java
index 5ab08d546e..55b6bf10d4 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableAlterHandler.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableAlterHandler.java
@@ -20,11 +20,6 @@
package org.apache.gravitino.lance.common.ops.gravitino;
import com.google.common.annotations.VisibleForTesting;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsResponse;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsResponse;
-import com.lancedb.lance.namespace.model.ColumnAlteration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -32,6 +27,11 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.lance.common.utils.LanceConstants;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableChange;
+import org.lance.namespace.model.AlterColumnsEntry;
+import org.lance.namespace.model.AlterTableAlterColumnsRequest;
+import org.lance.namespace.model.AlterTableAlterColumnsResponse;
+import org.lance.namespace.model.AlterTableDropColumnsRequest;
+import org.lance.namespace.model.AlterTableDropColumnsResponse;
/**
* Handler for altering a Gravitino table. It builds the Gravitino table changes based on the
@@ -97,6 +97,9 @@ public interface GravitinoLanceTableAlterHandler<REQUEST, RESPONSE> {
implements GravitinoLanceTableAlterHandler<
AlterTableAlterColumnsRequest, AlterTableAlterColumnsResponse> {
+ private static final String RENAME_ONLY_ERROR =
+ "Only RENAME alteration is supported currently.";
+
@Override
public TableChange[] buildGravitinoTableChange(AlterTableAlterColumnsRequest request) {
return buildAlterColumnChanges(request);
@@ -115,26 +118,28 @@ public interface GravitinoLanceTableAlterHandler<REQUEST, RESPONSE> {
}
private TableChange[] buildAlterColumnChanges(AlterTableAlterColumnsRequest request) {
- List<ColumnAlteration> columns = request.getAlterations();
+ List<AlterColumnsEntry> columns = request.getAlterations();
List<TableChange> changes = new ArrayList<>();
- for (ColumnAlteration column : columns) {
+ for (AlterColumnsEntry column : columns) {
// Column name will not be null according to LanceDB spec.
- String columnName = column.getColumn();
+ String columnName = column.getPath();
String newName = column.getRename();
if (StringUtils.isNotBlank(newName)) {
changes.add(TableChange.renameColumn(new String[] {columnName}, newName));
}
- // The format of ColumnAlteration#castTo is unclear, so we will skip it now
- // for more, please refer to: https://shorturl.at/bYI0Z (short url for
- // github.com/lance-format/lance-namespace)
- if (StringUtils.isNotBlank(column.getCastTo())) {
- throw new UnsupportedOperationException(
- "Altering column data type is not supported yet.");
+ if (hasUnsupportedAlterColumnFields(column)) {
+ throw new UnsupportedOperationException(RENAME_ONLY_ERROR);
}
}
return changes.stream().toArray(TableChange[]::new);
}
+
+ private boolean hasUnsupportedAlterColumnFields(AlterColumnsEntry column) {
+ return column.getDataType() != null
+ || column.getNullable() != null
+ || column.getVirtualColumn() != null;
+ }
}
}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableOperations.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableOperations.java
index b3039a656d..d43aad8f0c 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableOperations.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/GravitinoLanceTableOperations.java
@@ -31,22 +31,6 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.ObjectIdentifier;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsRequest;
-import com.lancedb.lance.namespace.model.CreateEmptyTableResponse;
-import com.lancedb.lance.namespace.model.CreateTableRequest;
-import com.lancedb.lance.namespace.model.CreateTableRequest.ModeEnum;
-import com.lancedb.lance.namespace.model.CreateTableResponse;
-import com.lancedb.lance.namespace.model.DeregisterTableResponse;
-import com.lancedb.lance.namespace.model.DescribeTableResponse;
-import com.lancedb.lance.namespace.model.DropTableResponse;
-import com.lancedb.lance.namespace.model.JsonArrowSchema;
-import com.lancedb.lance.namespace.model.RegisterTableRequest;
-import com.lancedb.lance.namespace.model.RegisterTableResponse;
-import com.lancedb.lance.namespace.util.CommonUtil;
-import com.lancedb.lance.namespace.util.JsonArrowSchemaConverter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -66,6 +50,17 @@ import org.apache.gravitino.lance.common.utils.LancePropertiesUtils;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableChange;
+import org.lance.namespace.errors.TableNotFoundException;
+import org.lance.namespace.model.AlterTableAlterColumnsRequest;
+import org.lance.namespace.model.AlterTableDropColumnsRequest;
+import org.lance.namespace.model.CreateEmptyTableResponse;
+import org.lance.namespace.model.CreateTableResponse;
+import org.lance.namespace.model.DeclareTableResponse;
+import org.lance.namespace.model.DeregisterTableResponse;
+import org.lance.namespace.model.DescribeTableResponse;
+import org.lance.namespace.model.DropTableResponse;
+import org.lance.namespace.model.JsonArrowSchema;
+import org.lance.namespace.model.RegisterTableResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,13 +68,32 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
public static final Logger LOG = LoggerFactory.getLogger(GravitinoLanceTableOperations.class);
- private final GravitinoLanceNamespaceWrapper namespaceWrapper;
-
private static final Map<Class<?>, GravitinoLanceTableAlterHandler<?, ?>> ALTER_HANDLERS =
Map.of(
AlterTableDropColumnsRequest.class, new DropColumns(),
AlterTableAlterColumnsRequest.class, new AlterColumnsGravitinoLance());
+ private final GravitinoLanceNamespaceWrapper namespaceWrapper;
+
+ private enum CreateMode {
+ CREATE,
+ EXIST_OK,
+ OVERWRITE
+ }
+
+ private enum RegisterMode {
+ CREATE,
+ REGISTER,
+ OVERWRITE;
+
+ String toCreationMode() {
+ if (this == REGISTER) {
+ return CREATE.name();
+ }
+ return name();
+ }
+ }
+
public GravitinoLanceTableOperations(GravitinoLanceNamespaceWrapper namespaceWrapper) {
this.namespaceWrapper = namespaceWrapper;
}
@@ -102,9 +116,15 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
NameIdentifier tableIdentifier =
NameIdentifier.of(nsId.levelAtListPos(1), nsId.levelAtListPos(2));
- Table table = catalog.asTableCatalog().loadTable(tableIdentifier);
+ Table table;
+ try {
+ table = catalog.asTableCatalog().loadTable(tableIdentifier);
+ } catch (NoSuchTableException e) {
+ throw new TableNotFoundException(
+ "Table not found: " + tableId, CommonUtil.formatCurrentStackTrace(), tableId);
+ }
DescribeTableResponse response = new DescribeTableResponse();
- response.setProperties(table.properties());
+ response.setMetadata(table.properties());
response.setLocation(table.properties().get(LANCE_LOCATION));
response.setSchema(toJsonArrowSchema(table.columns()));
response.setVersion(
@@ -118,7 +138,7 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
@Override
public CreateTableResponse createTable(
String tableId,
- CreateTableRequest.ModeEnum mode,
+ String mode,
String delimiter,
String tableLocation,
Map<String, String> tableProperties,
@@ -150,7 +170,7 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
createTableProperties.put(Table.PROPERTY_EXTERNAL, "true");
// Pass creation mode as property to delegate handling to LanceTableOperations
- createTableProperties.put(LANCE_CREATION_MODE, mode.name());
+ createTableProperties.put(LANCE_CREATION_MODE, normalizeCreateMode(mode, tableId));
// Single call - mode is handled server-side
Table t =
@@ -167,11 +187,29 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
response.setVersion(
Optional.ofNullable(properties.get(LANCE_TABLE_VERSION)).map(Long::valueOf).orElse(null));
response.setLocation(properties.get(LANCE_LOCATION));
- response.setProperties(properties);
return response;
}
@Override
+ public DeclareTableResponse declareTable(
+ String tableId, String delimiter, String tableLocation, Map<String, String> tableProperties) {
+ ImmutableMap<String, String> props =
+ ImmutableMap.<String, String>builder()
+ .putAll(tableProperties)
+ .put(LANCE_TABLE_CREATE_EMPTY, "true")
+ .put(Table.PROPERTY_EXTERNAL, "true")
+ .build();
+
+ CreateTableResponse response =
+ createTable(tableId, "create", delimiter, tableLocation, props, null);
+ DeclareTableResponse declareTableResponse = new DeclareTableResponse();
+ declareTableResponse.setLocation(response.getLocation());
+ declareTableResponse.setStorageOptions(response.getStorageOptions());
+ return declareTableResponse;
+ }
+
+ @Override
+ @SuppressWarnings("deprecation")
public CreateEmptyTableResponse createEmptyTable(
String tableId, String delimiter, String tableLocation, Map<String, String> tableProperties) {
// Empty table creation only supports CREATE mode (not EXIST_OK or OVERWRITE).
@@ -183,9 +221,8 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
.build();
CreateTableResponse response =
- createTable(tableId, ModeEnum.CREATE, delimiter, tableLocation, props, null);
+ createTable(tableId, "create", delimiter, tableLocation, props, null);
CreateEmptyTableResponse emptyTableResponse = new CreateEmptyTableResponse();
- emptyTableResponse.setProperties(response.getProperties());
emptyTableResponse.setLocation(response.getLocation());
emptyTableResponse.setStorageOptions(response.getStorageOptions());
return emptyTableResponse;
@@ -193,10 +230,7 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
@Override
public RegisterTableResponse registerTable(
- String tableId,
- RegisterTableRequest.ModeEnum mode,
- String delimiter,
- Map<String, String> tableProperties) {
+ String tableId, String mode, String delimiter, Map<String, String> tableProperties) {
ObjectIdentifier nsId = ObjectIdentifier.of(tableId, Pattern.quote(delimiter));
Preconditions.checkArgument(
nsId.levels() == 3, "Expected at 3-level namespace but got: %s", nsId.levels());
@@ -211,7 +245,7 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
copiedTableProperties.put(Table.PROPERTY_EXTERNAL, "true");
// Pass creation mode as property to delegate handling to LanceTableOperations
- copiedTableProperties.put(LANCE_CREATION_MODE, mode.name());
+ copiedTableProperties.put(LANCE_CREATION_MODE, normalizeRegisterMode(mode, tableId));
// Single call - mode is handled server-side
Table t =
@@ -236,16 +270,19 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
NameIdentifier tableIdentifier =
NameIdentifier.of(nsId.levelAtListPos(1), nsId.levelAtListPos(2));
- Table t = catalog.asTableCatalog().loadTable(tableIdentifier);
+ Table t;
+ try {
+ t = catalog.asTableCatalog().loadTable(tableIdentifier);
+ } catch (NoSuchTableException e) {
+ throw new TableNotFoundException(
+ "Table not found: " + tableId, CommonUtil.formatCurrentStackTrace(), tableId);
+ }
Map<String, String> properties = t.properties();
// TODO Support real deregister API.
boolean result = catalog.asTableCatalog().dropTable(tableIdentifier);
if (!result) {
- throw LanceNamespaceException.notFound(
- "Table not found: " + tableId,
- NoSuchTableException.class.getSimpleName(),
- tableId,
- CommonUtil.formatCurrentStackTrace());
+ throw new TableNotFoundException(
+ "Table not found: " + tableId, CommonUtil.formatCurrentStackTrace(), tableId);
}
DeregisterTableResponse response = new DeregisterTableResponse();
@@ -286,28 +323,20 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
try {
table = catalog.asTableCatalog().loadTable(tableIdentifier);
} catch (NoSuchTableException e) {
- throw LanceNamespaceException.notFound(
- "Table not found: " + tableId,
- NoSuchTableException.class.getSimpleName(),
- tableId,
- CommonUtil.formatCurrentStackTrace());
+ throw new TableNotFoundException(
+ "Table not found: " + tableId, CommonUtil.formatCurrentStackTrace(), tableId);
}
boolean deleted = catalog.asTableCatalog().purgeTable(tableIdentifier);
if (!deleted) {
- throw LanceNamespaceException.notFound(
- "Table not found: " + tableId,
- NoSuchTableException.class.getSimpleName(),
- tableId,
- CommonUtil.formatCurrentStackTrace());
+ throw new TableNotFoundException(
+ "Table not found: " + tableId, CommonUtil.formatCurrentStackTrace(), tableId);
}
DropTableResponse response = new DropTableResponse();
response.setId(nsId.listStyleId());
response.setLocation(table.properties().get(LANCE_LOCATION));
response.setProperties(table.properties());
- // TODO Support transaction ids later
- response.setTransactionId(List.of());
return response;
}
@@ -366,4 +395,21 @@ public class GravitinoLanceTableOperations implements LanceTableOperations {
return JsonArrowSchemaConverter.convertToJsonArrowSchema(
new org.apache.arrow.vector.types.pojo.Schema(fields));
}
+
+ private static String normalizeCreateMode(String mode, String tableId) {
+ if (mode == null) {
+ return CreateMode.CREATE.name();
+ }
+ return CommonUtil.parseEnumToken(CreateMode.class, mode, "Unknown create table mode: ", tableId)
+ .name();
+ }
+
+ private static String normalizeRegisterMode(String mode, String tableId) {
+ if (mode == null) {
+ return RegisterMode.CREATE.toCreationMode();
+ }
+ return CommonUtil.parseEnumToken(
+ RegisterMode.class, mode, "Unknown register table mode: ", tableId)
+ .toCreationMode();
+ }
}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/JsonArrowSchemaConverter.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/JsonArrowSchemaConverter.java
new file mode 100644
index 0000000000..2d1b5a11fc
--- /dev/null
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/JsonArrowSchemaConverter.java
@@ -0,0 +1,167 @@
+/*
+ * 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 java.util.List;
+import java.util.Locale;
+import java.util.stream.Collectors;
+import org.apache.arrow.vector.types.FloatingPointPrecision;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.lance.namespace.model.JsonArrowDataType;
+import org.lance.namespace.model.JsonArrowField;
+import org.lance.namespace.model.JsonArrowSchema;
+
+/** Converts Arrow schema to Lance Namespace JsonArrowSchema model. */
+class JsonArrowSchemaConverter {
+
+ private JsonArrowSchemaConverter() {}
+
+ static JsonArrowSchema convertToJsonArrowSchema(Schema schema) {
+ JsonArrowSchema jsonSchema = new JsonArrowSchema();
+ jsonSchema.setFields(
+ schema.getFields().stream()
+ .map(JsonArrowSchemaConverter::toJsonArrowField)
+ .collect(Collectors.toList()));
+ if (schema.getCustomMetadata() != null && !schema.getCustomMetadata().isEmpty()) {
+ jsonSchema.setMetadata(schema.getCustomMetadata());
+ }
+ return jsonSchema;
+ }
+
+ private static JsonArrowField toJsonArrowField(Field field) {
+ JsonArrowField jsonField = new JsonArrowField();
+ jsonField.setName(field.getName());
+ jsonField.setNullable(field.isNullable());
+ if (field.getMetadata() != null && !field.getMetadata().isEmpty()) {
+ jsonField.setMetadata(field.getMetadata());
+ }
+ jsonField.setType(toJsonArrowDataType(field.getType(), field.getChildren()));
+ return jsonField;
+ }
+
+ private static JsonArrowDataType toJsonArrowDataType(ArrowType type, List<Field> children) {
+ JsonArrowDataType jsonDataType = new JsonArrowDataType();
+ jsonDataType.setType(toTypeName(type));
+
+ Long length = toLength(type);
+ if (length != null) {
+ jsonDataType.setLength(length);
+ }
+
+ if (children != null && !children.isEmpty()) {
+ jsonDataType.setFields(
+ children.stream()
+ .map(JsonArrowSchemaConverter::toJsonArrowField)
+ .collect(Collectors.toList()));
+ }
+ return jsonDataType;
+ }
+
+ private static Long toLength(ArrowType type) {
+ if (type instanceof ArrowType.FixedSizeBinary) {
+ return (long) ((ArrowType.FixedSizeBinary) type).getByteWidth();
+ }
+ if (type instanceof ArrowType.FixedSizeList) {
+ return (long) ((ArrowType.FixedSizeList) type).getListSize();
+ }
+ return null;
+ }
+
+ private static String toTypeName(ArrowType type) {
+ if (type instanceof ArrowType.Int) {
+ ArrowType.Int intType = (ArrowType.Int) type;
+ return (intType.getIsSigned() ? "int" : "uint") + intType.getBitWidth();
+ }
+ if (type instanceof ArrowType.FloatingPoint) {
+ FloatingPointPrecision precision = ((ArrowType.FloatingPoint) type).getPrecision();
+ if (precision == FloatingPointPrecision.HALF) {
+ return "float16";
+ }
+ if (precision == FloatingPointPrecision.SINGLE) {
+ return "float32";
+ }
+ return "float64";
+ }
+ if (type instanceof ArrowType.Utf8) {
+ return "utf8";
+ }
+ if (type instanceof ArrowType.LargeUtf8) {
+ return "large_utf8";
+ }
+ if (type instanceof ArrowType.Bool) {
+ return "bool";
+ }
+ if (type instanceof ArrowType.Binary) {
+ return "binary";
+ }
+ if (type instanceof ArrowType.LargeBinary) {
+ return "large_binary";
+ }
+ if (type instanceof ArrowType.FixedSizeBinary) {
+ return "fixed_size_binary";
+ }
+ if (type instanceof ArrowType.Struct) {
+ return "struct";
+ }
+ if (type instanceof ArrowType.List) {
+ return "list";
+ }
+ if (type instanceof ArrowType.LargeList) {
+ return "large_list";
+ }
+ if (type instanceof ArrowType.FixedSizeList) {
+ return "fixed_size_list";
+ }
+ if (type instanceof ArrowType.Map) {
+ return "map";
+ }
+ if (type instanceof ArrowType.Decimal) {
+ return "decimal";
+ }
+ if (type instanceof ArrowType.Date) {
+ ArrowType.Date dateType = (ArrowType.Date) type;
+ if (dateType.getUnit() == org.apache.arrow.vector.types.DateUnit.DAY) {
+ return "date32";
+ }
+ return "date64";
+ }
+ if (type instanceof ArrowType.Time) {
+ ArrowType.Time timeType = (ArrowType.Time) type;
+ return timeType.getBitWidth() == 32 ? "time32" : "time64";
+ }
+ if (type instanceof ArrowType.Timestamp) {
+ return "timestamp";
+ }
+ if (type instanceof ArrowType.Interval) {
+ return "interval";
+ }
+ if (type instanceof ArrowType.Duration) {
+ return "duration";
+ }
+ if (type instanceof ArrowType.Union) {
+ return "union";
+ }
+ if (type instanceof ArrowType.Null) {
+ return "null";
+ }
+ return type.getTypeID().name().toLowerCase(Locale.ROOT);
+ }
+}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/ObjectIdentifier.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/ObjectIdentifier.java
new file mode 100644
index 0000000000..af114f27bc
--- /dev/null
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/ObjectIdentifier.java
@@ -0,0 +1,64 @@
+/*
+ * 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.base.Preconditions;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+
+/** Utility identifier parser for Lance namespace/table string IDs. */
+class ObjectIdentifier {
+
+ private final List<String> levels;
+
+ private ObjectIdentifier(List<String> levels) {
+ this.levels = levels;
+ }
+
+ static ObjectIdentifier of(String id, String delimiterRegex) {
+ Preconditions.checkArgument(id != null, "Identifier cannot be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(delimiterRegex), "Delimiter regex cannot be blank");
+
+ if (id.isEmpty()) {
+ return new ObjectIdentifier(Collections.emptyList());
+ }
+
+ List<String> parsedLevels =
+ Arrays.stream(id.split(delimiterRegex))
+ .filter(StringUtils::isNotEmpty)
+ .collect(Collectors.toList());
+ return new ObjectIdentifier(parsedLevels);
+ }
+
+ int levels() {
+ return levels.size();
+ }
+
+ String levelAtListPos(int index) {
+ return levels.get(index);
+ }
+
+ List<String> listStyleId() {
+ return Collections.unmodifiableList(levels);
+ }
+}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/PageUtil.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/PageUtil.java
new file mode 100644
index 0000000000..fc820f9693
--- /dev/null
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/ops/gravitino/PageUtil.java
@@ -0,0 +1,85 @@
+/*
+ * 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.base.Preconditions;
+import java.util.Collections;
+import java.util.List;
+import org.apache.commons.lang3.StringUtils;
+
+/** Pagination helper for Lance REST compatible list APIs. */
+class PageUtil {
+
+ private static final int DEFAULT_PAGE_SIZE = 1000;
+
+ private PageUtil() {}
+
+ static int normalizePageSize(Integer limit) {
+ if (limit == null) {
+ return DEFAULT_PAGE_SIZE;
+ }
+
+ Preconditions.checkArgument(limit > 0, "Page size limit must be positive");
+ return limit;
+ }
+
+ static Page splitPage(List<String> sortedItems, String pageToken, int pageSize) {
+ int startIndex = 0;
+ if (StringUtils.isNotBlank(pageToken)) {
+ try {
+ startIndex = Integer.parseInt(pageToken);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid page token: " + pageToken, e);
+ }
+ }
+
+ Preconditions.checkArgument(startIndex >= 0, "Page token cannot be negative: %s", pageToken);
+ Preconditions.checkArgument(
+ startIndex <= sortedItems.size(),
+ "Page token out of range: %s, total items: %s",
+ pageToken,
+ sortedItems.size());
+
+ int endIndex = Math.min(startIndex + pageSize, sortedItems.size());
+ List<String> pageItems =
+ startIndex == endIndex
+ ? Collections.emptyList()
+ : sortedItems.subList(startIndex, endIndex);
+ String nextPageToken = endIndex < sortedItems.size() ? String.valueOf(endIndex) : null;
+ return new Page(pageItems, nextPageToken);
+ }
+
+ static class Page {
+ private final List<String> items;
+ private final String nextPageToken;
+
+ Page(List<String> items, String nextPageToken) {
+ this.items = items;
+ this.nextPageToken = nextPageToken;
+ }
+
+ List<String> items() {
+ return items;
+ }
+
+ String nextPageToken() {
+ return nextPageToken;
+ }
+ }
+}
diff --git a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/SerializationUtils.java b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/SerializationUtils.java
index 8e5fb2494b..ed27ff15b2 100644
--- a/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/SerializationUtils.java
+++ b/lance/lance-common/src/main/java/org/apache/gravitino/lance/common/utils/SerializationUtils.java
@@ -19,11 +19,12 @@
*/
package org.apache.gravitino.lance.common.utils;
-import com.google.common.collect.ImmutableMap;
-import com.lancedb.lance.namespace.util.JsonUtil;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.json.JsonUtils;
public class SerializationUtils {
@@ -35,19 +36,19 @@ public class SerializationUtils {
// see https://github.com/lancedb/lance-namespace/blob/2033b2fca126e87e56ba0d5ec19c5ec010c7a98f/
// java/lance-namespace-core/src/main/java/com/lancedb/lance/namespace/rest/RestNamespace.java#L207-L208
public static Map<String, String> deserializeProperties(String serializedProperties) {
- return StringUtils.isBlank(serializedProperties)
- ? ImmutableMap.of()
- : JsonUtil.parse(
- serializedProperties,
- jsonNode -> {
- Map<String, String> map = new HashMap<>();
- jsonNode
- .fields()
- .forEachRemaining(
- entry -> {
- map.put(entry.getKey(), entry.getValue().asText());
- });
- return map;
- });
+ if (StringUtils.isBlank(serializedProperties)) {
+ return new HashMap<>();
+ }
+
+ try {
+ Map<String, Object> rawProperties =
+ JsonUtils.anyFieldMapper()
+ .readValue(serializedProperties, new TypeReference<Map<String, Object>>() {});
+ Map<String, String> deserializedProperties = new HashMap<>();
+ rawProperties.forEach((k, v) -> deserializedProperties.put(k, String.valueOf(v)));
+ return deserializedProperties;
+ } catch (JsonProcessingException e) {
+ throw new IllegalArgumentException("Failed to deserialize table properties JSON", e);
+ }
}
}
diff --git a/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/utils/TestSerializationUtils.java b/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/utils/TestSerializationUtils.java
new file mode 100644
index 0000000000..8248e6a5f1
--- /dev/null
+++ b/lance/lance-common/src/test/java/org/apache/gravitino/lance/common/utils/TestSerializationUtils.java
@@ -0,0 +1,54 @@
+/*
+ * 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.utils;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.Map;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestSerializationUtils {
+
+ @Test
+ public void testDeserializeProperties() {
+ Map<String, String> result =
+ SerializationUtils.deserializeProperties("{\"k1\":\"v1\",\"k2\":2,\"k3\":true}");
+
+ Assertions.assertEquals("v1", result.get("k1"));
+ Assertions.assertEquals("2", result.get("k2"));
+ Assertions.assertEquals("true", result.get("k3"));
+ Assertions.assertEquals(3, result.size());
+ }
+
+ @Test
+ public void testDeserializePropertiesWithBlankInput() {
+ Assertions.assertTrue(SerializationUtils.deserializeProperties(" ").isEmpty());
+ Assertions.assertTrue(SerializationUtils.deserializeProperties(null).isEmpty());
+ }
+
+ @Test
+ public void testDeserializePropertiesWithInvalidJson() {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> SerializationUtils.deserializeProperties("{\"k1\":}"));
+ Assertions.assertEquals("Failed to deserialize table properties JSON", exception.getMessage());
+ Assertions.assertInstanceOf(JsonProcessingException.class, exception.getCause());
+ }
+}
diff --git a/lance/lance-rest-server/build.gradle.kts b/lance/lance-rest-server/build.gradle.kts
index 52f045af2b..0198099df5 100644
--- a/lance/lance-rest-server/build.gradle.kts
+++ b/lance/lance-rest-server/build.gradle.kts
@@ -24,6 +24,19 @@ plugins {
id("idea")
}
+val scalaVersion: String =
+ project.properties["scalaVersion"] as? String ?: extra["defaultScalaVersion"].toString()
+val sparkVersion: String = libs.versions.spark35.get()
+val scalaCollectionCompatVersion: String = libs.versions.scala.collection.compat.get()
+val lanceSparkBundleVersion = "0.2.0"
+val lanceSparkBundleJarPathProperty = "gravitino.lance.spark.bundle.jar"
+val lanceSparkBundleDir = layout.buildDirectory.dir("lance-spark-bundle")
+val lanceSparkBundle by configurations.creating {
+ isCanBeConsumed = false
+ isCanBeResolved = true
+ isTransitive = false
+}
+
dependencies {
implementation(project(":api"))
implementation(project(":common")) {
@@ -45,7 +58,7 @@ dependencies {
implementation(libs.bundles.prometheus)
implementation(libs.commons.lang3)
implementation(libs.lance.namespace.core) {
- exclude(group = "com.lancedb", module = "lance-core")
+ exclude(group = "org.lance", module = "lance-core")
exclude(group = "com.google.guava", module = "guava") // provided by gravitino
exclude(group = "com.fasterxml.jackson.core", module = "*") // provided by gravitino
exclude(group = "com.fasterxml.jackson.datatype", module = "*") // provided by gravitino
@@ -65,9 +78,26 @@ dependencies {
testImplementation(project(":clients:client-java"))
testImplementation(project(":server"))
testImplementation(project(":integration-test-common", "testArtifacts"))
+ testImplementation(libs.lance)
+
+ add(
+ lanceSparkBundle.name,
+ "org.lance:lance-spark-bundle-3.5_2.12:$lanceSparkBundleVersion"
+ )
+
+ testImplementation("org.scala-lang.modules:scala-collection-compat_$scalaVersion:$scalaCollectionCompatVersion")
+ testImplementation("org.apache.spark:spark-sql_$scalaVersion:$sparkVersion") {
+ exclude("org.apache.avro")
+ exclude("org.apache.hadoop")
+ exclude("org.apache.zookeeper")
+ exclude("io.dropwizard.metrics")
+ exclude("org.rocksdb")
+ }
testImplementation(libs.awaitility)
testImplementation(libs.commons.io)
+ testImplementation(libs.hadoop3.client.api)
+ testImplementation(libs.hadoop3.client.runtime)
testImplementation(libs.jersey.test.framework.core) {
exclude(group = "org.junit.jupiter")
}
@@ -89,6 +119,10 @@ tasks {
from(configurations.runtimeClasspath)
into("build/libs")
}
+ val prepareLanceSparkBundle by registering(Sync::class) {
+ from(lanceSparkBundle)
+ into(lanceSparkBundleDir)
+ }
jar {
finalizedBy(copyDepends)
@@ -119,9 +153,20 @@ tasks {
}
test {
+ dependsOn(prepareLanceSparkBundle)
+
+ doFirst {
+ val bundleJar =
+ lanceSparkBundleDir.get().asFile.listFiles()?.singleOrNull { it.extension == "jar" }
+ ?: throw GradleException(
+ "Expected exactly one Lance Spark bundle jar in ${lanceSparkBundleDir.get().asFile}"
+ )
+ systemProperty(lanceSparkBundleJarPathProperty, bundleJar.absolutePath)
+ }
+
val testMode = project.properties["testMode"] as? String ?: "embedded"
if (testMode == "embedded") {
- dependsOn(":catalogs:catalog-lakehouse-generic:build")
+ dependsOn(":catalogs:catalog-lakehouse-generic:jar")
}
}
}
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/LanceExceptionMapper.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/LanceExceptionMapper.java
index 6ae9419e1c..2078b75fe6 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/LanceExceptionMapper.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/LanceExceptionMapper.java
@@ -20,14 +20,24 @@ package org.apache.gravitino.lance.service;
import static org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.model.ErrorResponse;
-import java.util.Optional;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
+import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.NotFoundException;
-import org.apache.gravitino.exceptions.TableAlreadyExistsException;
+import org.lance.namespace.errors.ConcurrentModificationException;
+import org.lance.namespace.errors.InternalException;
+import org.lance.namespace.errors.InvalidInputException;
+import org.lance.namespace.errors.LanceNamespaceException;
+import org.lance.namespace.errors.NamespaceAlreadyExistsException;
+import org.lance.namespace.errors.NamespaceNotEmptyException;
+import org.lance.namespace.errors.NamespaceNotFoundException;
+import org.lance.namespace.errors.PermissionDeniedException;
+import org.lance.namespace.errors.ServiceUnavailableException;
+import org.lance.namespace.errors.TableAlreadyExistsException;
+import org.lance.namespace.errors.TableNotFoundException;
+import org.lance.namespace.errors.UnauthenticatedException;
+import org.lance.namespace.model.ErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -56,43 +66,70 @@ public class LanceExceptionMapper implements ExceptionMapper<Exception> {
}
private static LanceNamespaceException toLanceNamespaceException(String instance, Exception ex) {
- if (ex instanceof NotFoundException) {
- return LanceNamespaceException.notFound(
- ex.getMessage(), ex.getClass().getSimpleName(), instance, getStackTrace(ex));
+ if (ex instanceof NoSuchTableException) {
+ return new TableNotFoundException(ex.getMessage(), getStackTrace(ex), instance);
+
+ } else if (ex instanceof NotFoundException) {
+ return new NamespaceNotFoundException(ex.getMessage(), getStackTrace(ex), instance);
} else if (ex instanceof IllegalArgumentException) {
- return LanceNamespaceException.badRequest(
- ex.getMessage(), ex.getClass().getSimpleName(), instance, getStackTrace(ex));
+ return new InvalidInputException(ex.getMessage(), getStackTrace(ex), instance);
- } else if (ex instanceof TableAlreadyExistsException) {
- return LanceNamespaceException.conflict(
- ex.getMessage(), ex.getClass().getSimpleName(), instance, getStackTrace(ex));
+ } else if (ex instanceof org.apache.gravitino.exceptions.TableAlreadyExistsException) {
+ return new TableAlreadyExistsException(ex.getMessage(), getStackTrace(ex), instance);
} else if (ex instanceof UnsupportedOperationException) {
- return LanceNamespaceException.unsupportedOperation(
- ex.getMessage(), ex.getClass().getSimpleName(), instance, getStackTrace(ex));
+ return new org.lance.namespace.errors.UnsupportedOperationException(
+ ex.getMessage(), getStackTrace(ex), instance);
} else {
LOG.warn("Lance REST server unexpected exception:", ex);
- return LanceNamespaceException.serverError(
- ex.getMessage(), ex.getClass().getSimpleName(), instance, getStackTrace(ex));
+ return new InternalException(ex.getMessage(), getStackTrace(ex), instance);
}
}
- // Referred from lance-namespace-adapter's LanceNamespaces exception handling
- // com.lancedb.lance.namespace.adapter.GlobalExceptionHandler
- private static Response handleLanceNamespaceException(LanceNamespaceException ex) {
- ErrorResponse errResp = new ErrorResponse();
- Optional<ErrorResponse> errorResponse = ex.getErrorResponse();
- if (errorResponse.isPresent() && errorResponse.get().getCode() != null) {
- errResp = errorResponse.get();
+ private static int toHttpStatus(LanceNamespaceException exception) {
+ if (exception instanceof NamespaceNotFoundException
+ || exception instanceof TableNotFoundException) {
+ return Response.Status.NOT_FOUND.getStatusCode();
+ }
- } else {
- // Transform error info into ErrorResponse
- errResp.setCode(ex.getCode());
- errResp.setError(ex.getMessage());
+ if (exception instanceof NamespaceAlreadyExistsException
+ || exception instanceof TableAlreadyExistsException
+ || exception instanceof ConcurrentModificationException) {
+ return Response.Status.CONFLICT.getStatusCode();
}
- return Response.status(errResp.getCode()).entity(errResp).build();
+ if (exception instanceof org.lance.namespace.errors.UnsupportedOperationException) {
+ return Response.Status.NOT_ACCEPTABLE.getStatusCode();
+ }
+
+ if (exception instanceof PermissionDeniedException) {
+ return Response.Status.FORBIDDEN.getStatusCode();
+ }
+
+ if (exception instanceof UnauthenticatedException) {
+ return Response.Status.UNAUTHORIZED.getStatusCode();
+ }
+
+ if (exception instanceof ServiceUnavailableException) {
+ return Response.Status.SERVICE_UNAVAILABLE.getStatusCode();
+ }
+
+ if (exception instanceof InvalidInputException
+ || exception instanceof NamespaceNotEmptyException) {
+ return Response.Status.BAD_REQUEST.getStatusCode();
+ }
+
+ return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
+ }
+
+ private static Response handleLanceNamespaceException(LanceNamespaceException ex) {
+ ErrorResponse errResp = new ErrorResponse();
+ errResp.setCode(ex.getCode());
+ errResp.setError(ex.getMessage());
+ errResp.setDetail(ex.getDetail());
+ errResp.setInstance(ex.getInstance());
+ return Response.status(toHttpStatus(ex)).entity(errResp).build();
}
}
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java
index 464201b851..b448e84295 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceNamespaceOperations.java
@@ -22,13 +22,6 @@ import static org.apache.gravitino.lance.common.ops.NamespaceWrapper.NAMESPACE_D
import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
-import com.lancedb.lance.namespace.model.CreateNamespaceRequest;
-import com.lancedb.lance.namespace.model.CreateNamespaceResponse;
-import com.lancedb.lance.namespace.model.DescribeNamespaceResponse;
-import com.lancedb.lance.namespace.model.DropNamespaceRequest;
-import com.lancedb.lance.namespace.model.DropNamespaceResponse;
-import com.lancedb.lance.namespace.model.ListNamespacesResponse;
-import com.lancedb.lance.namespace.model.ListTablesResponse;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
@@ -44,12 +37,21 @@ import javax.ws.rs.core.Response;
import org.apache.gravitino.lance.common.ops.NamespaceWrapper;
import org.apache.gravitino.lance.service.LanceExceptionMapper;
import org.apache.gravitino.metrics.MetricNames;
+import org.lance.namespace.model.CreateNamespaceRequest;
+import org.lance.namespace.model.CreateNamespaceResponse;
+import org.lance.namespace.model.DescribeNamespaceResponse;
+import org.lance.namespace.model.DropNamespaceRequest;
+import org.lance.namespace.model.DropNamespaceResponse;
+import org.lance.namespace.model.ListNamespacesResponse;
+import org.lance.namespace.model.ListTablesResponse;
@Path("/v1/namespace")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class LanceNamespaceOperations {
+ private static final String ROOT_NAMESPACE_ID = "";
+
private final NamespaceWrapper lanceNamespace;
@Inject
@@ -66,6 +68,22 @@ public class LanceNamespaceOperations {
@DefaultValue(NAMESPACE_DELIMITER_DEFAULT) @QueryParam("delimiter") String delimiter,
@QueryParam("page_token") String pageToken,
@QueryParam("limit") Integer limit) {
+ return listNamespacesInternal(namespaceId, delimiter, pageToken, limit);
+ }
+
+ @GET
+ @Path("/list")
+ @Timed(name = "list-namespaces-root." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-namespaces-root", absolute = true)
+ public Response listNamespacesOnRoot(
+ @DefaultValue(NAMESPACE_DELIMITER_DEFAULT) @QueryParam("delimiter") String delimiter,
+ @QueryParam("page_token") String pageToken,
+ @QueryParam("limit") Integer limit) {
+ return listNamespacesInternal(ROOT_NAMESPACE_ID, delimiter, pageToken, limit);
+ }
+
+ private Response listNamespacesInternal(
+ String namespaceId, String delimiter, String pageToken, Integer limit) {
try {
ListNamespacesResponse response =
lanceNamespace
@@ -108,9 +126,7 @@ public class LanceNamespaceOperations {
.createNamespace(
namespaceId,
Pattern.quote(delimiter),
- request.getMode() == null
- ? CreateNamespaceRequest.ModeEnum.CREATE
- : request.getMode(),
+ request.getMode() == null ? "create" : request.getMode(),
request.getProperties());
return Response.ok(response).build();
} catch (Exception e) {
@@ -133,12 +149,8 @@ public class LanceNamespaceOperations {
.dropNamespace(
namespaceId,
Pattern.quote(delimiter),
- request.getMode() == null
- ? DropNamespaceRequest.ModeEnum.FAIL
- : request.getMode(),
- request.getBehavior() == null
- ? DropNamespaceRequest.BehaviorEnum.RESTRICT
- : request.getBehavior());
+ request.getMode() == null ? "fail" : request.getMode(),
+ request.getBehavior() == null ? "restrict" : request.getBehavior());
return Response.ok(response).build();
} catch (Exception e) {
return LanceExceptionMapper.toRESTResponse(namespaceId, e);
diff --git a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java
index c71d9969b3..667eb1b498 100644
--- a/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java
+++ b/lance/lance-rest-server/src/main/java/org/apache/gravitino/lance/service/rest/LanceTableOperations.java
@@ -27,25 +27,6 @@ import com.codahale.metrics.annotation.ResponseMetered;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsResponse;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsResponse;
-import com.lancedb.lance.namespace.model.ColumnAlteration;
-import com.lancedb.lance.namespace.model.CreateEmptyTableRequest;
-import com.lancedb.lance.namespace.model.CreateEmptyTableResponse;
-import com.lancedb.lance.namespace.model.CreateTableRequest;
-import com.lancedb.lance.namespace.model.CreateTableResponse;
-import com.lancedb.lance.namespace.model.DeregisterTableRequest;
-import com.lancedb.lance.namespace.model.DeregisterTableResponse;
-import com.lancedb.lance.namespace.model.DescribeTableRequest;
-import com.lancedb.lance.namespace.model.DescribeTableResponse;
-import com.lancedb.lance.namespace.model.DropTableRequest;
-import com.lancedb.lance.namespace.model.DropTableResponse;
-import com.lancedb.lance.namespace.model.RegisterTableRequest;
-import com.lancedb.lance.namespace.model.RegisterTableRequest.ModeEnum;
-import com.lancedb.lance.namespace.model.RegisterTableResponse;
-import com.lancedb.lance.namespace.model.TableExistsRequest;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
@@ -67,6 +48,25 @@ import org.apache.gravitino.lance.common.utils.LanceConstants;
import org.apache.gravitino.lance.common.utils.SerializationUtils;
import org.apache.gravitino.lance.service.LanceExceptionMapper;
import org.apache.gravitino.metrics.MetricNames;
+import org.lance.namespace.errors.TableNotFoundException;
+import org.lance.namespace.model.AlterColumnsEntry;
+import org.lance.namespace.model.AlterTableAlterColumnsRequest;
+import org.lance.namespace.model.AlterTableAlterColumnsResponse;
+import org.lance.namespace.model.AlterTableDropColumnsRequest;
+import org.lance.namespace.model.AlterTableDropColumnsResponse;
+import org.lance.namespace.model.CreateEmptyTableResponse;
+import org.lance.namespace.model.CreateTableResponse;
+import org.lance.namespace.model.DeclareTableRequest;
+import org.lance.namespace.model.DeclareTableResponse;
+import org.lance.namespace.model.DeregisterTableRequest;
+import org.lance.namespace.model.DeregisterTableResponse;
+import org.lance.namespace.model.DescribeTableRequest;
+import org.lance.namespace.model.DescribeTableResponse;
+import org.lance.namespace.model.DropTableRequest;
+import org.lance.namespace.model.DropTableResponse;
+import org.lance.namespace.model.RegisterTableRequest;
+import org.lance.namespace.model.RegisterTableResponse;
+import org.lance.namespace.model.TableExistsRequest;
@Path("/v1/table/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@@ -117,12 +117,17 @@ public class LanceTableOperations {
MultivaluedMap<String, String> headersMap = headers.getRequestHeaders();
String tableLocation = headersMap.getFirst(LANCE_TABLE_LOCATION_HEADER);
String tableProperties = headersMap.getFirst(LANCE_TABLE_PROPERTIES_PREFIX_HEADER);
- CreateTableRequest.ModeEnum modeEnum = CreateTableRequest.ModeEnum.fromValue(mode);
Map<String, String> props = SerializationUtils.deserializeProperties(tableProperties);
CreateTableResponse response =
lanceNamespace
.asTableOps()
- .createTable(tableId, modeEnum, delimiter, tableLocation, props, arrowStreamBody);
+ .createTable(
+ tableId,
+ normalizeCreateTableMode(mode),
+ delimiter,
+ tableLocation,
+ props,
+ arrowStreamBody);
return Response.ok(response).build();
} catch (Exception e) {
return LanceExceptionMapper.toRESTResponse(tableId, e);
@@ -138,19 +143,26 @@ public class LanceTableOperations {
@Produces("application/json")
@Timed(name = "create-empty-table." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "create-empty-table", absolute = true)
+ @SuppressWarnings("deprecation")
public Response createEmptyTable(
@PathParam("id") String tableId,
@QueryParam("delimiter") @DefaultValue(NAMESPACE_DELIMITER_DEFAULT) String delimiter,
- CreateEmptyTableRequest request,
+ Map<String, Object> requestBody,
@Context HttpHeaders headers) {
try {
- validateCreateEmptyTableRequest(request);
-
- String tableLocation = request.getLocation();
- Map<String, String> props =
- request.getProperties() == null
- ? Maps.newHashMap()
- : Maps.newHashMap(request.getProperties());
+ validateCreateEmptyTableRequest(requestBody);
+ String tableLocation =
+ Optional.ofNullable(requestBody)
+ .map(body -> body.get(LANCE_LOCATION))
+ .map(String::valueOf)
+ .orElse(null);
+ Map<String, String> props = extractPropertiesFromBody(requestBody);
+ MultivaluedMap<String, String> headersMap = headers.getRequestHeaders();
+ String tableProperties = headersMap.getFirst(LANCE_TABLE_PROPERTIES_PREFIX_HEADER);
+ Map<String, String> headerProps = SerializationUtils.deserializeProperties(tableProperties);
+ // Keep backward compatibility: accept body properties and let header override on key
+ // conflict.
+ props.putAll(headerProps);
CreateEmptyTableResponse response =
lanceNamespace.asTableOps().createEmptyTable(tableId, delimiter, tableLocation, props);
@@ -160,6 +172,32 @@ public class LanceTableOperations {
}
}
+ @POST
+ @Path("/declare")
+ @Produces("application/json")
+ @Timed(name = "declare-table." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "declare-table", absolute = true)
+ public Response declareTable(
+ @PathParam("id") String tableId,
+ @QueryParam("delimiter") @DefaultValue(NAMESPACE_DELIMITER_DEFAULT) String delimiter,
+ DeclareTableRequest declareTableRequest,
+ @Context HttpHeaders headers) {
+ try {
+ validateDeclareTableRequest(declareTableRequest);
+ String tableLocation =
+ declareTableRequest.getLocation() != null ? declareTableRequest.getLocation() : null;
+ MultivaluedMap<String, String> headersMap = headers.getRequestHeaders();
+ String tableProperties = headersMap.getFirst(LANCE_TABLE_PROPERTIES_PREFIX_HEADER);
+ Map<String, String> props = SerializationUtils.deserializeProperties(tableProperties);
+
+ DeclareTableResponse response =
+ lanceNamespace.asTableOps().declareTable(tableId, delimiter, tableLocation, props);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ return LanceExceptionMapper.toRESTResponse(tableId, e);
+ }
+ }
+
@POST
@Path("/register")
@Timed(name = "register-table." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@@ -178,8 +216,8 @@ public class LanceTableOperations {
: Maps.newHashMap(registerTableRequest.getProperties());
props.put(LANCE_LOCATION, registerTableRequest.getLocation());
props.put(LanceConstants.LANCE_TABLE_REGISTER, "true");
- ModeEnum mode =
- registerTableRequest.getMode() == null ? ModeEnum.CREATE : registerTableRequest.getMode();
+ String mode =
+ registerTableRequest.getMode() == null ? "create" : registerTableRequest.getMode();
RegisterTableResponse response =
lanceNamespace.asTableOps().registerTable(tableId, mode, delimiter, props);
@@ -224,7 +262,7 @@ public class LanceTableOperations {
if (exists) {
return Response.status(Response.Status.OK).build();
}
- return Response.status(Response.Status.NOT_FOUND).build();
+ throw new TableNotFoundException("Table not found: " + tableId, null, tableId);
} catch (Exception e) {
return LanceExceptionMapper.toRESTResponse(tableId, e);
}
@@ -293,11 +331,32 @@ public class LanceTableOperations {
}
}
- private void validateCreateEmptyTableRequest(
- @SuppressWarnings("unused") CreateEmptyTableRequest request) {
+ @SuppressWarnings({"unused", "deprecation"})
+ private void validateCreateEmptyTableRequest(Map<String, Object> requestBody) {
// No specific fields to validate for now
}
+ private void validateDeclareTableRequest(
+ @SuppressWarnings("unused") DeclareTableRequest request) {
+ // No specific fields to validate for now
+ }
+
+ private static Map<String, String> extractPropertiesFromBody(Map<String, Object> requestBody) {
+ if (requestBody == null) {
+ return Maps.newHashMap();
+ }
+
+ Object propertiesObject = requestBody.get("properties");
+ if (!(propertiesObject instanceof Map<?, ?>)) {
+ return Maps.newHashMap();
+ }
+
+ Map<String, String> properties = Maps.newHashMap();
+ ((Map<?, ?>) propertiesObject)
+ .forEach((key, value) -> properties.put(String.valueOf(key), String.valueOf(value)));
+ return properties;
+ }
+
private void validateRegisterTableRequest(
@SuppressWarnings("unused") RegisterTableRequest request) {
// No specific fields to validate for now
@@ -337,13 +396,23 @@ public class LanceTableOperations {
Preconditions.checkArgument(
!request.getAlterations().isEmpty(), "Columns to alter cannot be empty.");
- for (ColumnAlteration alteration : request.getAlterations()) {
+ for (AlterColumnsEntry alteration : request.getAlterations()) {
Preconditions.checkArgument(
- StringUtils.isBlank(alteration.getCastTo()),
- "Only RENAME alteration is supported currently.");
+ StringUtils.isNotBlank(alteration.getPath()), "Column path to alter cannot be empty.");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(alteration.getRename()), "Rename field must be specified.");
Preconditions.checkArgument(
- StringUtils.isNotBlank(alteration.getRename()),
- "Rename field must be specified when castTo is not provided.");
+ alteration.getDataType() == null
+ && alteration.getNullable() == null
+ && alteration.getVirtualColumn() == null,
+ "Only RENAME alteration is supported currently.");
+ }
+ }
+
+ private static String normalizeCreateTableMode(String mode) {
+ if (mode == null) {
+ return "create";
}
+ return mode;
}
}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceModeParsing.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceModeParsing.java
new file mode 100644
index 0000000000..4ac063a406
--- /dev/null
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/common/ops/gravitino/TestGravitinoLanceModeParsing.java
@@ -0,0 +1,178 @@
+/*
+ * 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.apache.gravitino.lance.common.utils.LanceConstants.LANCE_CREATION_MODE;
+import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_LOCATION;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.when;
+
+import java.util.Map;
+import java.util.regex.Pattern;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.TableCatalog;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.lance.namespace.errors.InvalidInputException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+class TestGravitinoLanceModeParsing {
+
+ private enum TestMode {
+ CREATE,
+ EXIST_OK
+ }
+
+ @Test
+ void testNormalizeTokenPreservesSpecialCharacters() {
+ Assertions.assertEquals("CREATE", CommonUtil.normalizeToken(" create "));
+ Assertions.assertEquals("EXIST_OK", CommonUtil.normalizeToken("exist_ok"));
+ Assertions.assertEquals("#CREATE$", CommonUtil.normalizeToken("#create$"));
+ }
+
+ @Test
+ void testParseEnumTokenRejectsMalformedValues() {
+ Assertions.assertEquals(
+ TestMode.EXIST_OK,
+ CommonUtil.parseEnumToken(TestMode.class, "exist_ok", "Unknown mode: ", "table"));
+
+ InvalidInputException exception =
+ Assertions.assertThrows(
+ InvalidInputException.class,
+ () -> CommonUtil.parseEnumToken(TestMode.class, "#create$", "Unknown mode: ", "table"));
+ Assertions.assertTrue(exception.getMessage().contains("Unknown mode: #create$"));
+ }
+
+ @Test
+ void testNamespaceModeRejectsMalformedValues() {
+ GravitinoLanceNameSpaceOperations operations =
+ new GravitinoLanceNameSpaceOperations(Mockito.mock(GravitinoLanceNamespaceWrapper.class));
+ String delimiter = Pattern.quote(".");
+
+ InvalidInputException createException =
+ Assertions.assertThrows(
+ InvalidInputException.class,
+ () -> operations.createNamespace("catalog", delimiter, "#create$", Map.of()));
+ Assertions.assertTrue(
+ createException.getMessage().contains("Unknown create namespace mode: #create$"));
+
+ InvalidInputException dropModeException =
+ Assertions.assertThrows(
+ InvalidInputException.class,
+ () -> operations.dropNamespace("catalog", delimiter, "#fail$", "restrict"));
+ Assertions.assertTrue(
+ dropModeException.getMessage().contains("Unknown drop namespace mode: #fail$"));
+
+ InvalidInputException dropBehaviorException =
+ Assertions.assertThrows(
+ InvalidInputException.class,
+ () -> operations.dropNamespace("catalog", delimiter, "fail", "#cascade$"));
+ Assertions.assertTrue(
+ dropBehaviorException.getMessage().contains("Unknown drop namespace behavior: #cascade$"));
+ }
+
+ @Test
+ void testCreateTableModeNormalizesCase() {
+ TableCatalog tableCatalog = Mockito.mock(TableCatalog.class);
+ Table table = Mockito.mock(Table.class);
+ when(table.properties()).thenReturn(Map.of());
+ when(tableCatalog.createTable(
+ any(NameIdentifier.class), any(Column[].class), isNull(), anyMap()))
+ .thenReturn(table);
+ GravitinoLanceTableOperations operations = newTableOperations(tableCatalog);
+
+ operations.createTable("catalog.schema.table", " exist_ok ", ".", null, Map.of(), null);
+
+ ArgumentCaptor<Map<String, String>> propertiesCaptor = propertiesCaptor();
+ Mockito.verify(tableCatalog)
+ .createTable(
+ any(NameIdentifier.class), any(Column[].class), isNull(), propertiesCaptor.capture());
+ Assertions.assertEquals("EXIST_OK", propertiesCaptor.getValue().get(LANCE_CREATION_MODE));
+ }
+
+ @Test
+ void testCreateTableModeRejectsMalformedValues() {
+ GravitinoLanceTableOperations operations = newTableOperations(Mockito.mock(TableCatalog.class));
+
+ InvalidInputException exception =
+ Assertions.assertThrows(
+ InvalidInputException.class,
+ () ->
+ operations.createTable(
+ "catalog.schema.table", "#create$", ".", null, Map.of(), null));
+ Assertions.assertTrue(exception.getMessage().contains("Unknown create table mode: #create$"));
+ }
+
+ @Test
+ void testRegisterModeMapsRegisterToCreate() {
+ TableCatalog tableCatalog = Mockito.mock(TableCatalog.class);
+ Table table = Mockito.mock(Table.class);
+ when(table.properties()).thenReturn(Map.of(LANCE_LOCATION, "/tmp/table"));
+ when(tableCatalog.createTable(
+ any(NameIdentifier.class), any(Column[].class), isNull(), anyMap()))
+ .thenReturn(table);
+ GravitinoLanceTableOperations operations = newTableOperations(tableCatalog);
+
+ operations.registerTable(
+ "catalog.schema.table", " register ", ".", Map.of(LANCE_LOCATION, "/tmp/table"));
+
+ ArgumentCaptor<Map<String, String>> propertiesCaptor = propertiesCaptor();
+ Mockito.verify(tableCatalog)
+ .createTable(
+ any(NameIdentifier.class), any(Column[].class), isNull(), propertiesCaptor.capture());
+ Assertions.assertEquals("CREATE", propertiesCaptor.getValue().get(LANCE_CREATION_MODE));
+ }
+
+ @Test
+ void testRegisterModeRejectsMalformedValues() {
+ GravitinoLanceTableOperations operations = newTableOperations(Mockito.mock(TableCatalog.class));
+
+ InvalidInputException exception =
+ Assertions.assertThrows(
+ InvalidInputException.class,
+ () ->
+ operations.registerTable(
+ "catalog.schema.table",
+ "#register$",
+ ".",
+ Map.of(LANCE_LOCATION, "/tmp/table")));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Unknown register table mode: #register$"));
+ }
+
+ private static GravitinoLanceTableOperations newTableOperations(TableCatalog tableCatalog) {
+ GravitinoLanceNamespaceWrapper namespaceWrapper =
+ Mockito.mock(GravitinoLanceNamespaceWrapper.class);
+ Catalog catalog = Mockito.mock(Catalog.class);
+ when(namespaceWrapper.loadAndValidateLakehouseCatalog("catalog")).thenReturn(catalog);
+ when(catalog.asTableCatalog()).thenReturn(tableCatalog);
+ return new GravitinoLanceTableOperations(namespaceWrapper);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static ArgumentCaptor<Map<String, String>> propertiesCaptor() {
+ return ArgumentCaptor.forClass(Map.class);
+ }
+}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java
index d2bf5e113a..501f1394e7 100644
--- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceRESTServiceIT.java
@@ -22,43 +22,6 @@ import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import com.lancedb.lance.namespace.LanceNamespace;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.LanceNamespaces;
-import com.lancedb.lance.namespace.client.apache.ApiException;
-import com.lancedb.lance.namespace.client.apache.api.TableApi;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsResponse;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsResponse;
-import com.lancedb.lance.namespace.model.ColumnAlteration;
-import com.lancedb.lance.namespace.model.CreateEmptyTableRequest;
-import com.lancedb.lance.namespace.model.CreateEmptyTableResponse;
-import com.lancedb.lance.namespace.model.CreateNamespaceRequest;
-import com.lancedb.lance.namespace.model.CreateNamespaceResponse;
-import com.lancedb.lance.namespace.model.CreateTableRequest;
-import com.lancedb.lance.namespace.model.CreateTableResponse;
-import com.lancedb.lance.namespace.model.DeregisterTableRequest;
-import com.lancedb.lance.namespace.model.DeregisterTableResponse;
-import com.lancedb.lance.namespace.model.DescribeNamespaceRequest;
-import com.lancedb.lance.namespace.model.DescribeNamespaceResponse;
-import com.lancedb.lance.namespace.model.DescribeTableRequest;
-import com.lancedb.lance.namespace.model.DescribeTableResponse;
-import com.lancedb.lance.namespace.model.DropNamespaceRequest;
-import com.lancedb.lance.namespace.model.DropNamespaceResponse;
-import com.lancedb.lance.namespace.model.DropTableRequest;
-import com.lancedb.lance.namespace.model.ErrorResponse;
-import com.lancedb.lance.namespace.model.JsonArrowField;
-import com.lancedb.lance.namespace.model.ListNamespacesRequest;
-import com.lancedb.lance.namespace.model.ListNamespacesResponse;
-import com.lancedb.lance.namespace.model.ListTablesRequest;
-import com.lancedb.lance.namespace.model.NamespaceExistsRequest;
-import com.lancedb.lance.namespace.model.RegisterTableRequest;
-import com.lancedb.lance.namespace.model.RegisterTableRequest.ModeEnum;
-import com.lancedb.lance.namespace.model.RegisterTableResponse;
-import com.lancedb.lance.namespace.model.TableExistsRequest;
-import com.lancedb.lance.namespace.rest.RestNamespace;
-import com.lancedb.lance.namespace.rest.RestNamespaceConfig;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
@@ -69,21 +32,19 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
-import java.util.Optional;
import java.util.Set;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Schema;
import org.apache.gravitino.client.GravitinoMetalake;
-import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.integration.test.util.BaseIT;
import org.apache.gravitino.integration.test.util.GravitinoITUtils;
+import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.lance.common.utils.ArrowUtils;
import org.apache.gravitino.lance.common.utils.LanceConstants;
import org.apache.gravitino.rel.Table;
@@ -92,10 +53,48 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
-
+import org.lance.namespace.LanceNamespace;
+import org.lance.namespace.client.apache.ApiClient;
+import org.lance.namespace.client.apache.ApiException;
+import org.lance.namespace.client.apache.api.TableApi;
+import org.lance.namespace.errors.ErrorCode;
+import org.lance.namespace.errors.LanceNamespaceException;
+import org.lance.namespace.model.AlterColumnsEntry;
+import org.lance.namespace.model.AlterTableAlterColumnsRequest;
+import org.lance.namespace.model.AlterTableAlterColumnsResponse;
+import org.lance.namespace.model.AlterTableDropColumnsRequest;
+import org.lance.namespace.model.AlterTableDropColumnsResponse;
+import org.lance.namespace.model.CreateEmptyTableRequest;
+import org.lance.namespace.model.CreateEmptyTableResponse;
+import org.lance.namespace.model.CreateNamespaceRequest;
+import org.lance.namespace.model.CreateNamespaceResponse;
+import org.lance.namespace.model.CreateTableResponse;
+import org.lance.namespace.model.DeclareTableRequest;
+import org.lance.namespace.model.DeclareTableResponse;
+import org.lance.namespace.model.DeregisterTableRequest;
+import org.lance.namespace.model.DeregisterTableResponse;
+import org.lance.namespace.model.DescribeNamespaceRequest;
+import org.lance.namespace.model.DescribeNamespaceResponse;
+import org.lance.namespace.model.DescribeTableRequest;
+import org.lance.namespace.model.DescribeTableResponse;
+import org.lance.namespace.model.DropNamespaceRequest;
+import org.lance.namespace.model.DropNamespaceResponse;
+import org.lance.namespace.model.DropTableRequest;
+import org.lance.namespace.model.ErrorResponse;
+import org.lance.namespace.model.JsonArrowField;
+import org.lance.namespace.model.ListNamespacesRequest;
+import org.lance.namespace.model.ListNamespacesResponse;
+import org.lance.namespace.model.ListTablesRequest;
+import org.lance.namespace.model.NamespaceExistsRequest;
+import org.lance.namespace.model.RegisterTableRequest;
+import org.lance.namespace.model.RegisterTableResponse;
+import org.lance.namespace.model.TableExistsRequest;
+
+@SuppressWarnings("deprecation")
public class LanceRESTServiceIT extends BaseIT {
private static final String CATALOG_NAME = GravitinoITUtils.genRandomName("lance_rest_catalog");
private static final String SCHEMA_NAME = GravitinoITUtils.genRandomName("lance_rest_schema");
+ private static final String DELIMITER = ".";
private GravitinoMetalake metalake;
private Catalog catalog;
@@ -116,17 +115,48 @@ public class LanceRESTServiceIT extends BaseIT {
this.metalake = createMetalake(getLanceRESTServerMetalakeName());
HashMap<String, String> props = Maps.newHashMap();
- props.put(RestNamespaceConfig.URI, getLanceRestServiceUrl());
- props.put(RestNamespaceConfig.DELIMITER, RestNamespaceConfig.DELIMITER_DEFAULT);
- this.ns = LanceNamespaces.connect("rest", props, null, allocator);
+ props.put("uri", getLanceRestServiceUrl());
+ props.put("delimiter", DELIMITER);
+ this.ns = LanceNamespace.connect("rest", props, allocator);
this.tempDir = Files.createTempDirectory("test_lance_rest_service_it_");
}
@AfterAll
- public void clean() throws IOException {
- client.dropMetalake(getLanceRESTServerMetalakeName(), true);
- FileUtils.deleteDirectory(tempDir.toFile());
+ public void clean() throws Exception {
+ Exception failure = null;
+
+ try {
+ if (client != null) {
+ client.dropMetalake(getLanceRESTServerMetalakeName(), true);
+ }
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ if (tempDir != null) {
+ FileUtils.deleteDirectory(tempDir.toFile());
+ }
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ allocator.close();
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ super.stopIntegrationTest();
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ if (failure != null) {
+ throw failure;
+ }
}
@AfterEach
@@ -181,31 +211,13 @@ public class LanceRESTServiceIT extends BaseIT {
Assertions.assertEquals(schema.properties(), describeNamespaceResp.getProperties());
- // test describe the root namespace
- DescribeNamespaceRequest rootDescNamespaceReq = new DescribeNamespaceRequest();
- LanceNamespaceException exception =
- Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.describeNamespace(rootDescNamespaceReq));
-
- Assertions.assertEquals(400, exception.getCode());
- Assertions.assertTrue(exception.getErrorResponse().isPresent());
- Assertions.assertTrue(
- exception
- .getErrorResponse()
- .get()
- .getError()
- .contains("Expected at most 2-level and at least 1-level namespace"));
- Assertions.assertEquals(
- IllegalArgumentException.class.getSimpleName(),
- exception.getErrorResponse().get().getType());
-
// test describe a non-existent catalog namespace
DescribeNamespaceRequest nonExistentCatalogReq = new DescribeNamespaceRequest();
nonExistentCatalogReq.addIdItem("non_existent_catalog");
- exception =
+ RuntimeException exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.describeNamespace(nonExistentCatalogReq));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException.class, () -> ns.describeNamespace(nonExistentCatalogReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":1"));
// test describe a non-existent schema namespace
DescribeNamespaceRequest nonExistentSchemaReq = new DescribeNamespaceRequest();
@@ -213,8 +225,8 @@ public class LanceRESTServiceIT extends BaseIT {
nonExistentSchemaReq.addIdItem("non_existent_schema");
exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.describeNamespace(nonExistentSchemaReq));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException.class, () -> ns.describeNamespace(nonExistentSchemaReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":1"));
}
@Test
@@ -237,13 +249,13 @@ public class LanceRESTServiceIT extends BaseIT {
Assertions.assertEquals(catalog.properties(), createNamespaceResp.getProperties());
// create catalog again with default mode (create) should fail
- LanceNamespaceException exception =
+ RuntimeException exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.createNamespace(createNamespaceReq));
- Assertions.assertEquals(409, exception.getCode());
+ RuntimeException.class, () -> ns.createNamespace(createNamespaceReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":2"));
// create catalog again with exist_ok mode should succeed
- createNamespaceReq.setMode(CreateNamespaceRequest.ModeEnum.EXIST_OK);
+ createNamespaceReq.setMode("exist_ok");
createNamespaceResp = ns.createNamespace(createNamespaceReq);
Assertions.assertEquals(catalog.properties(), createNamespaceResp.getProperties());
@@ -254,7 +266,7 @@ public class LanceRESTServiceIT extends BaseIT {
put("catalog_key2", "catalog_value2");
}
};
- createNamespaceReq.setMode(CreateNamespaceRequest.ModeEnum.OVERWRITE);
+ createNamespaceReq.setMode("overwrite");
createNamespaceReq.setProperties(newProps);
createNamespaceResp = ns.createNamespace(createNamespaceReq);
@@ -281,12 +293,11 @@ public class LanceRESTServiceIT extends BaseIT {
// create schema again with default mode (create) should fail
exception =
- Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.createNamespace(createSchemaReq));
- Assertions.assertEquals(409, exception.getCode());
+ Assertions.assertThrows(RuntimeException.class, () -> ns.createNamespace(createSchemaReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":2"));
// create schema again with exist_ok mode should succeed
- createSchemaReq.setMode(CreateNamespaceRequest.ModeEnum.EXIST_OK);
+ createSchemaReq.setMode("exist_ok");
createNamespaceResp = ns.createNamespace(createSchemaReq);
Assertions.assertEquals(schema.properties(), createNamespaceResp.getProperties());
@@ -297,7 +308,7 @@ public class LanceRESTServiceIT extends BaseIT {
put("schema_key2", "schema_value2");
}
};
- createSchemaReq.setMode(CreateNamespaceRequest.ModeEnum.OVERWRITE);
+ createSchemaReq.setMode("overwrite");
createSchemaReq.setProperties(newSchemaProps);
createNamespaceResp = ns.createNamespace(createSchemaReq);
@@ -313,13 +324,12 @@ public class LanceRESTServiceIT extends BaseIT {
// test drop a non-existent namespace (catalog) with default mode (FAIL) should fail
DropNamespaceRequest dropNamespaceReq = new DropNamespaceRequest();
dropNamespaceReq.addIdItem("non_existent_catalog");
- LanceNamespaceException exception =
- Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.dropNamespace(dropNamespaceReq));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException exception =
+ Assertions.assertThrows(RuntimeException.class, () -> ns.dropNamespace(dropNamespaceReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":1"));
// test drop a non-existent namespace (catalog) with SKIP mode should succeed
- dropNamespaceReq.setMode(DropNamespaceRequest.ModeEnum.SKIP);
+ dropNamespaceReq.setMode("skip");
DropNamespaceResponse dropNamespaceResp = ns.dropNamespace(dropNamespaceReq);
Assertions.assertTrue(dropNamespaceResp.getTransactionId().isEmpty());
@@ -328,12 +338,11 @@ public class LanceRESTServiceIT extends BaseIT {
dropSchemaReq.addIdItem(catalog.name());
dropSchemaReq.addIdItem("non_existent_schema");
exception =
- Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.dropNamespace(dropSchemaReq));
- Assertions.assertEquals(404, exception.getCode());
+ Assertions.assertThrows(RuntimeException.class, () -> ns.dropNamespace(dropSchemaReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":1"));
// test drop a non-existent namespace (schema) with SKIP mode should succeed
- dropSchemaReq.setMode(DropNamespaceRequest.ModeEnum.SKIP);
+ dropSchemaReq.setMode("skip");
dropNamespaceResp = ns.dropNamespace(dropSchemaReq);
Assertions.assertTrue(dropNamespaceResp.getTransactionId().isEmpty());
@@ -342,11 +351,11 @@ public class LanceRESTServiceIT extends BaseIT {
dropNonEmptyCatalogReq.addIdItem(catalog.name());
exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.dropNamespace(dropNonEmptyCatalogReq));
- Assertions.assertEquals(400, exception.getCode());
+ RuntimeException.class, () -> ns.dropNamespace(dropNonEmptyCatalogReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":13"));
// test drop a non-empty namespace (catalog) with CASCADE behavior should succeed
- dropNonEmptyCatalogReq.setBehavior(DropNamespaceRequest.BehaviorEnum.CASCADE);
+ dropNonEmptyCatalogReq.setBehavior("cascade");
dropNamespaceResp = ns.dropNamespace(dropNonEmptyCatalogReq);
Assertions.assertTrue(dropNamespaceResp.getTransactionId().isEmpty());
Assertions.assertFalse(metalake.catalogExists(catalog.name()));
@@ -370,12 +379,12 @@ public class LanceRESTServiceIT extends BaseIT {
dropNonEmptySchemaReq.addIdItem(schema.name());
exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.dropNamespace(dropNonEmptySchemaReq));
- Assertions.assertEquals(400, exception.getCode());
+ RuntimeException.class, () -> ns.dropNamespace(dropNonEmptySchemaReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":13"));
Assertions.assertTrue(catalog.asSchemas().schemaExists(schema.name()));
// test drop a non-empty namespace (schema) with CASCADE behavior should succeed
- dropNonEmptySchemaReq.setBehavior(DropNamespaceRequest.BehaviorEnum.CASCADE);
+ dropNonEmptySchemaReq.setBehavior("cascade");
dropNamespaceResp = ns.dropNamespace(dropNonEmptySchemaReq);
Assertions.assertTrue(dropNamespaceResp.getTransactionId().isEmpty());
Assertions.assertFalse(catalog.asSchemas().schemaExists(schema.name()));
@@ -394,10 +403,10 @@ public class LanceRESTServiceIT extends BaseIT {
// test non-existing catalog
NamespaceExistsRequest nonExistentCatalogReq = new NamespaceExistsRequest();
nonExistentCatalogReq.addIdItem("non_existent_catalog");
- LanceNamespaceException exception =
+ RuntimeException exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.namespaceExists(nonExistentCatalogReq));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException.class, () -> ns.namespaceExists(nonExistentCatalogReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":1"));
// test existing schema
NamespaceExistsRequest schemaExistsReq = new NamespaceExistsRequest();
@@ -411,8 +420,8 @@ public class LanceRESTServiceIT extends BaseIT {
nonExistentSchemaReq.addIdItem("non_existent_schema");
exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.namespaceExists(nonExistentSchemaReq));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException.class, () -> ns.namespaceExists(nonExistentSchemaReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":1"));
}
@Test
@@ -423,19 +432,11 @@ public class LanceRESTServiceIT extends BaseIT {
CreateEmptyTableRequest request = new CreateEmptyTableRequest();
String location = tempDir + "/" + "empty_table/";
request.setLocation(location);
- request.setProperties(
- ImmutableMap.of(
- "key1", "v1",
- "lance.storage.a", "value_a",
- "lance.storage.b", "value_b"));
request.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "empty_table"));
CreateEmptyTableResponse response = ns.createEmptyTable(request);
Assertions.assertNotNull(response);
Assertions.assertEquals(location, response.getLocation());
- Assertions.assertEquals("v1", response.getProperties().get("key1"));
- Assertions.assertEquals("value_a", response.getStorageOptions().get("a"));
- Assertions.assertEquals("value_b", response.getStorageOptions().get("b"));
DescribeTableRequest describeTableRequest = new DescribeTableRequest();
describeTableRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "empty_table"));
@@ -444,17 +445,17 @@ public class LanceRESTServiceIT extends BaseIT {
Assertions.assertNotNull(loadTable);
Assertions.assertEquals(location, loadTable.getLocation());
Assertions.assertEquals(
- "true", loadTable.getProperties().get(LanceConstants.LANCE_TABLE_CREATE_EMPTY));
- Assertions.assertEquals("true", loadTable.getProperties().get(Table.PROPERTY_EXTERNAL));
+ "true", loadTable.getMetadata().get(LanceConstants.LANCE_TABLE_CREATE_EMPTY));
+ Assertions.assertEquals("true", loadTable.getMetadata().get(Table.PROPERTY_EXTERNAL));
// Try to create the same table again should fail
- LanceNamespaceException exception =
+ RuntimeException exception =
Assertions.assertThrows(
- LanceNamespaceException.class,
+ RuntimeException.class,
() -> {
ns.createEmptyTable(request);
});
- Assertions.assertEquals(409, exception.getCode());
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":5"));
// Create an empty table with non-existent location should succeed
// since storage is not touched
@@ -480,7 +481,7 @@ public class LanceRESTServiceIT extends BaseIT {
}
@Test
- void testCreateTable() throws IOException, ApiException, IllegalAccessException {
+ void testCreateTable() throws IOException {
catalog = createCatalog(CATALOG_NAME);
createSchema();
@@ -493,19 +494,15 @@ public class LanceRESTServiceIT extends BaseIT {
Field.nullable("value", new ArrowType.Utf8())));
byte[] body = ArrowUtils.generateIpcStream(schema);
- CreateTableRequest request = new CreateTableRequest();
- request.setId(ids);
- request.setLocation(location);
- request.setProperties(
+ Map<String, String> createTableProperties =
ImmutableMap.of(
"key1", "v1",
"lance.storage.a", "value_a",
- "lance.storage.b", "value_b"));
-
- CreateTableResponse response = ns.createTable(request, body);
+ "lance.storage.b", "value_b");
+ CreateTableResponse response =
+ createTable(ids, location, createTableProperties, body, /* mode= */ null);
Assertions.assertNotNull(response);
Assertions.assertEquals(location, response.getLocation());
- Assertions.assertEquals("v1", response.getProperties().get("key1"));
Assertions.assertEquals("value_a", response.getStorageOptions().get("a"));
Assertions.assertEquals("value_b", response.getStorageOptions().get("b"));
Assertions.assertNotNull(response.getVersion());
@@ -531,74 +528,87 @@ public class LanceRESTServiceIT extends BaseIT {
}
// Check the location exists
Assertions.assertTrue(new File(location).exists());
- Assertions.assertEquals("v1", loadTable.getProperties().get("key1"));
+ Assertions.assertEquals("v1", loadTable.getMetadata().get("key1"));
Assertions.assertEquals("value_a", loadTable.getStorageOptions().get("a"));
Assertions.assertEquals("value_b", loadTable.getStorageOptions().get("b"));
// Check overwrite mode
String newLocation = tempDir + "/" + "table_new/";
- request.setLocation(newLocation);
- request.setMode(CreateTableRequest.ModeEnum.OVERWRITE);
- request.setProperties(
+ Map<String, String> overwriteTableProperties =
ImmutableMap.of(
"key1", "v2",
"lance.storage.a", "value_va",
- "lance.storage.b", "value_vb"));
+ "lance.storage.b", "value_vb");
- response = Assertions.assertDoesNotThrow(() -> ns.createTable(request, body));
+ response =
+ Assertions.assertDoesNotThrow(
+ () -> createTable(ids, newLocation, overwriteTableProperties, body, "overwrite"));
Assertions.assertNotNull(response);
Assertions.assertEquals(newLocation, response.getLocation());
- Assertions.assertTrue(response.getProperties().get("key1").equals("v2"));
Assertions.assertEquals("value_va", response.getStorageOptions().get("a"));
Assertions.assertEquals("value_vb", response.getStorageOptions().get("b"));
Assertions.assertTrue(new File(newLocation).exists());
Assertions.assertFalse(new File(location).exists());
// Check exist_ok mode
- request.setMode(CreateTableRequest.ModeEnum.EXIST_OK);
- response = Assertions.assertDoesNotThrow(() -> ns.createTable(request, body));
+ response =
+ Assertions.assertDoesNotThrow(
+ () -> createTable(ids, newLocation, overwriteTableProperties, body, "exist_ok"));
Assertions.assertNotNull(response);
- Assertions.assertEquals("v2", response.getProperties().get("key1"));
Assertions.assertEquals("value_va", response.getStorageOptions().get("a"));
Assertions.assertEquals("value_vb", response.getStorageOptions().get("b"));
Assertions.assertEquals(newLocation, response.getLocation());
Assertions.assertTrue(new File(newLocation).exists());
// Create table again without overwrite or exist_ok should fail
- request.setMode(CreateTableRequest.ModeEnum.CREATE);
LanceNamespaceException exception =
- Assertions.assertThrows(LanceNamespaceException.class, () -> ns.createTable(request, body));
+ Assertions.assertThrows(
+ LanceNamespaceException.class,
+ () -> createTable(ids, newLocation, overwriteTableProperties, body, "create"));
Assertions.assertTrue(exception.getMessage().contains("already exists"));
- Assertions.assertEquals(409, exception.getCode());
+ Assertions.assertEquals(5, exception.getCode());
// Create a table without location should fail
- CreateTableRequest noLocationRequest = new CreateTableRequest();
- noLocationRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "no_location_table"));
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.createTable(noLocationRequest, body));
+ LanceNamespaceException.class,
+ () ->
+ createTable(
+ List.of(CATALOG_NAME, SCHEMA_NAME, "no_location_table"),
+ /* location= */ null,
+ ImmutableMap.of(),
+ body,
+ /* mode= */ null));
// Create table with invalid schema should fail
byte[] invalidBody = "".getBytes(Charset.defaultCharset());
- CreateTableRequest invalidRequest = new CreateTableRequest();
- invalidRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "invalid_table"));
- invalidRequest.setLocation(tempDir + "/" + "invalid_table/");
LanceNamespaceException apiException =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.createTable(invalidRequest, invalidBody));
+ LanceNamespaceException.class,
+ () ->
+ createTable(
+ List.of(CATALOG_NAME, SCHEMA_NAME, "invalid_table"),
+ tempDir + "/" + "invalid_table/",
+ ImmutableMap.of(),
+ invalidBody,
+ /* mode= */ null));
Assertions.assertTrue(apiException.getMessage().contains("Failed to parse Arrow IPC stream"));
- Assertions.assertEquals(400, apiException.getCode());
+ Assertions.assertEquals(13, apiException.getCode());
// Create table with wrong ids should fail
- CreateTableRequest wrongIdRequest = new CreateTableRequest();
- wrongIdRequest.setId(List.of(CATALOG_NAME, "wrong_schema")); // This is a schema NOT a table.
- wrongIdRequest.setLocation(tempDir + "/" + "wrong_id_table/");
LanceNamespaceException wrongIdException =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.createTable(wrongIdRequest, body));
+ LanceNamespaceException.class,
+ () ->
+ createTable(
+ List.of(CATALOG_NAME, "wrong_schema"),
+ tempDir + "/" + "wrong_id_table/",
+ ImmutableMap.of(),
+ body,
+ /* mode= */ null));
Assertions.assertTrue(wrongIdException.getMessage().contains("Expected at 3-level namespace"));
- Assertions.assertEquals(400, wrongIdException.getCode());
+ Assertions.assertEquals(13, wrongIdException.getCode());
// Now test list tables
ListTablesRequest listRequest = new ListTablesRequest();
@@ -613,10 +623,8 @@ public class LanceRESTServiceIT extends BaseIT {
dropColumnsRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "table"));
dropColumnsRequest.setColumns(List.of("value"));
- // No alterTableDropColumns in Namespace interface, so we need to get TableApi via reflection
- RestNamespace restNamespace = (RestNamespace) ns;
- TableApi tableApi = (TableApi) FieldUtils.readField(restNamespace, "tableApi", true);
- String delimiter = RestNamespaceConfig.DELIMITER_DEFAULT;
+ TableApi tableApi = createTableApi();
+ String delimiter = DELIMITER;
AlterTableDropColumnsResponse alterTableDropColumnsResponse =
Assertions.assertDoesNotThrow(
@@ -667,20 +675,15 @@ public class LanceRESTServiceIT extends BaseIT {
Field.nullable("value", new ArrowType.Utf8())));
byte[] body = ArrowUtils.generateIpcStream(schema);
- CreateTableRequest request = new CreateTableRequest();
- request.setId(ids);
- request.setLocation(location);
- request.setProperties(ImmutableMap.of("key1", "v1"));
- ns.createTable(request, body);
+ createTable(ids, location, ImmutableMap.of("key1", "v1"), body, /* mode= */ null);
- RestNamespace restNamespace = (RestNamespace) ns;
- TableApi tableApi = (TableApi) FieldUtils.readField(restNamespace, "tableApi", true);
- String delimiter = RestNamespaceConfig.DELIMITER_DEFAULT;
+ TableApi tableApi = createTableApi();
+ String delimiter = DELIMITER;
AlterTableAlterColumnsRequest alterRequest = new AlterTableAlterColumnsRequest();
alterRequest.setId(ids);
- ColumnAlteration columnAlteration = new ColumnAlteration();
- columnAlteration.setColumn("value");
+ AlterColumnsEntry columnAlteration = new AlterColumnsEntry();
+ columnAlteration.setPath("value");
columnAlteration.setRename("value_new");
alterRequest.setAlterations(List.of(columnAlteration));
@@ -712,7 +715,7 @@ public class LanceRESTServiceIT extends BaseIT {
List<String> ids = List.of(CATALOG_NAME, SCHEMA_NAME, "table_register");
RegisterTableRequest registerTableRequest = new RegisterTableRequest();
registerTableRequest.setLocation(location);
- registerTableRequest.setMode(ModeEnum.CREATE);
+ registerTableRequest.setMode("create");
registerTableRequest.setId(ids);
registerTableRequest.setProperties(ImmutableMap.of("key1", "value1"));
@@ -727,11 +730,11 @@ public class LanceRESTServiceIT extends BaseIT {
DescribeTableResponse loadTable = ns.describeTable(describeTableRequest);
Assertions.assertNotNull(loadTable);
Assertions.assertEquals(location, loadTable.getLocation());
- Assertions.assertTrue(loadTable.getProperties().containsKey("key1"));
+ Assertions.assertTrue(loadTable.getMetadata().containsKey("key1"));
// Test register again with OVERWRITE mode
String newLocation = tempDir + "/" + "register_new/";
- registerTableRequest.setMode(ModeEnum.OVERWRITE);
+ registerTableRequest.setMode("overwrite");
registerTableRequest.setLocation(newLocation);
response = Assertions.assertDoesNotThrow(() -> ns.registerTable(registerTableRequest));
Assertions.assertNotNull(response);
@@ -743,7 +746,7 @@ public class LanceRESTServiceIT extends BaseIT {
String existingLocation = tempDir + "/" + "existing_location/";
new File(existingLocation).mkdirs();
Assertions.assertTrue(new File(existingLocation).exists());
- registerTableRequest.setMode(ModeEnum.CREATE);
+ registerTableRequest.setMode("create");
registerTableRequest.setLocation(existingLocation);
registerTableRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "table_with_existing_location"));
RegisterTableResponse existingLocationResponse =
@@ -775,7 +778,7 @@ public class LanceRESTServiceIT extends BaseIT {
// Test Overwrite again after deregister
String nonExistingLocation = tempDir + "/" + "non_existing_location/";
- registerTableRequest.setMode(ModeEnum.OVERWRITE);
+ registerTableRequest.setMode("overwrite");
registerTableRequest.setId(ids);
registerTableRequest.setLocation(nonExistingLocation);
response = Assertions.assertDoesNotThrow(() -> ns.registerTable(registerTableRequest));
@@ -802,22 +805,16 @@ public class LanceRESTServiceIT extends BaseIT {
DeregisterTableRequest deregisterTableRequest = new DeregisterTableRequest();
deregisterTableRequest.setId(ids);
- LanceNamespaceException exception =
+ RuntimeException exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.deregisterTable(deregisterTableRequest));
- Assertions.assertEquals(404, exception.getCode());
- Assertions.assertTrue(exception.getMessage().contains("does not exist"));
- Optional<ErrorResponse> responseOptional = exception.getErrorResponse();
- Assertions.assertTrue(responseOptional.isPresent());
- Assertions.assertEquals(
- NoSuchTableException.class.getSimpleName(), responseOptional.get().getType());
-
+ RuntimeException.class, () -> ns.deregisterTable(deregisterTableRequest));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":4"));
+ Assertions.assertTrue(exception.getMessage().contains("Table not found"));
// Try to create a table and then deregister table
CreateEmptyTableRequest createEmptyTableRequest = new CreateEmptyTableRequest();
String location = tempDir + "/" + "to_be_deregistered_table/";
ids = List.of(CATALOG_NAME, SCHEMA_NAME, "to_be_deregistered_table");
createEmptyTableRequest.setLocation(location);
- createEmptyTableRequest.setProperties(ImmutableMap.of());
createEmptyTableRequest.setId(ids);
CreateEmptyTableResponse response =
Assertions.assertDoesNotThrow(() -> ns.createEmptyTable(createEmptyTableRequest));
@@ -837,16 +834,19 @@ public class LanceRESTServiceIT extends BaseIT {
// Now try to describe the table, should fail
DescribeTableRequest describeTableRequest = new DescribeTableRequest();
describeTableRequest.setId(ids);
- LanceNamespaceException lanceNamespaceException =
+ RuntimeException describeException =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.describeTable(describeTableRequest));
- Assertions.assertEquals(404, lanceNamespaceException.getCode());
+ RuntimeException.class, () -> ns.describeTable(describeTableRequest));
+ Assertions.assertTrue(describeException.getMessage().contains("\"code\":4"));
describeTableRequest.setVersion(1L);
- lanceNamespaceException =
+ RuntimeException versionException =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.describeTable(describeTableRequest));
- Assertions.assertEquals(406, lanceNamespaceException.getCode());
+ RuntimeException.class, () -> ns.describeTable(describeTableRequest));
+ Assertions.assertTrue(
+ versionException
+ .getMessage()
+ .contains("Describing specific table version is not supported"));
}
@Test
@@ -858,7 +858,6 @@ public class LanceRESTServiceIT extends BaseIT {
CreateEmptyTableRequest createEmptyTableRequest = new CreateEmptyTableRequest();
String location = tempDir + "/" + "table_exists/";
createEmptyTableRequest.setLocation(location);
- createEmptyTableRequest.setProperties(ImmutableMap.of());
createEmptyTableRequest.setId(ids);
CreateEmptyTableResponse response =
Assertions.assertDoesNotThrow(() -> ns.createEmptyTable(createEmptyTableRequest));
@@ -873,10 +872,9 @@ public class LanceRESTServiceIT extends BaseIT {
// Test non-existing table
List<String> nonExistingIds = List.of(CATALOG_NAME, SCHEMA_NAME, "non_existing_table");
tableExistsReq.setId(nonExistingIds);
- LanceNamespaceException exception =
- Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.tableExists(tableExistsReq));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException exception =
+ Assertions.assertThrows(RuntimeException.class, () -> ns.tableExists(tableExistsReq));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":4"));
Assertions.assertTrue(exception.getMessage().contains("Not Found"));
}
@@ -889,7 +887,6 @@ public class LanceRESTServiceIT extends BaseIT {
CreateEmptyTableRequest createEmptyTableRequest = new CreateEmptyTableRequest();
String location = tempDir + "/" + "table_to_drop/";
createEmptyTableRequest.setLocation(location);
- createEmptyTableRequest.setProperties(ImmutableMap.of());
createEmptyTableRequest.setId(ids);
CreateEmptyTableResponse response =
Assertions.assertDoesNotThrow(() -> ns.createEmptyTable(createEmptyTableRequest));
@@ -904,17 +901,123 @@ public class LanceRESTServiceIT extends BaseIT {
// Describe the dropped table should fail
DescribeTableRequest describeTableRequest = new DescribeTableRequest();
describeTableRequest.setId(ids);
- LanceNamespaceException exception =
+ RuntimeException exception =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.describeTable(describeTableRequest));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException.class, () -> ns.describeTable(describeTableRequest));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":4"));
// Drop a non-existing table should fail
dropTableRequest.setId(ids);
exception =
+ Assertions.assertThrows(RuntimeException.class, () -> ns.dropTable(dropTableRequest));
+ Assertions.assertTrue(exception.getMessage().contains("\"code\":4"));
+ }
+
+ @Test
+ void testDeclareTable() {
+ catalog = createCatalog(CATALOG_NAME);
+ createSchema();
+
+ DeclareTableRequest request = new DeclareTableRequest();
+ String location = tempDir + "/" + "declared_table/";
+ request.setLocation(location);
+ request.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "declared_table"));
+
+ DeclareTableResponse response = ns.declareTable(request);
+ Assertions.assertNotNull(response);
+ Assertions.assertEquals(location, response.getLocation());
+
+ DescribeTableRequest describeTableRequest = new DescribeTableRequest();
+ describeTableRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "declared_table"));
+
+ DescribeTableResponse loadTable = ns.describeTable(describeTableRequest);
+ Assertions.assertNotNull(loadTable);
+ Assertions.assertEquals(location, loadTable.getLocation());
+ Assertions.assertEquals(
+ "true", loadTable.getMetadata().get(LanceConstants.LANCE_TABLE_CREATE_EMPTY));
+ Assertions.assertEquals("true", loadTable.getMetadata().get(Table.PROPERTY_EXTERNAL));
+
+ // Try to declare the same table again should fail
+ RuntimeException declareException =
Assertions.assertThrows(
- LanceNamespaceException.class, () -> ns.dropTable(dropTableRequest));
- Assertions.assertEquals(404, exception.getCode());
+ RuntimeException.class,
+ () -> {
+ ns.declareTable(request);
+ });
+ Assertions.assertTrue(declareException.getMessage().contains("\"code\":5"));
+
+ // Declare a table with non-existent location should succeed
+ // since storage is not touched
+ DeclareTableRequest anotherRequest = new DeclareTableRequest();
+ anotherRequest.setId(List.of(CATALOG_NAME, SCHEMA_NAME, "another_declared_table"));
+ String anotherLocation = tempDir + "/" + "another_declared_location/";
+ Assertions.assertFalse(new File(anotherLocation).exists());
+ anotherRequest.setLocation(anotherLocation);
+ DeclareTableResponse anotherResponse = ns.declareTable(anotherRequest);
+ Assertions.assertNotNull(anotherResponse);
+ Assertions.assertEquals(anotherLocation, anotherResponse.getLocation());
+ // Will not touch storage, so the path should not be created.
+ Assertions.assertFalse(new File(anotherLocation).exists());
+ }
+
+ private CreateTableResponse createTable(
+ List<String> ids,
+ String location,
+ Map<String, String> tableProperties,
+ byte[] body,
+ String mode) {
+ Map<String, String> additionalHeaders = Maps.newHashMap();
+ if (location != null) {
+ additionalHeaders.put(LanceConstants.LANCE_TABLE_LOCATION_HEADER, location);
+ }
+ if (tableProperties != null && !tableProperties.isEmpty()) {
+ additionalHeaders.put(
+ LanceConstants.LANCE_TABLE_PROPERTIES_PREFIX_HEADER,
+ serializeTableProperties(tableProperties));
+ }
+
+ try {
+ return createTableApi()
+ .createTable(String.join(DELIMITER, ids), body, DELIMITER, mode, additionalHeaders);
+ } catch (ApiException e) {
+ throw toLanceNamespaceException(e);
+ }
+ }
+
+ private static String serializeTableProperties(Map<String, String> tableProperties) {
+ try {
+ return JsonUtils.anyFieldMapper().writeValueAsString(tableProperties);
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to serialize table properties", e);
+ }
+ }
+
+ private static LanceNamespaceException toLanceNamespaceException(ApiException e) {
+ if (e.getResponseBody() != null) {
+ try {
+ ErrorResponse errorResponse =
+ JsonUtils.anyFieldMapper().readValue(e.getResponseBody(), ErrorResponse.class);
+ ErrorCode errorCode =
+ errorResponse.getCode() == null
+ ? ErrorCode.INTERNAL
+ : ErrorCode.fromCode(errorResponse.getCode());
+ return new LanceNamespaceException(
+ errorCode,
+ errorResponse.getError(),
+ errorResponse.getDetail(),
+ errorResponse.getInstance(),
+ e);
+ } catch (IOException ignored) {
+ // Fall through to a generic internal error.
+ }
+ }
+
+ return new LanceNamespaceException(ErrorCode.INTERNAL, e.getMessage(), e);
+ }
+
+ private TableApi createTableApi() {
+ ApiClient apiClient = new ApiClient().setBasePath(getLanceRestServiceUrl());
+ return new TableApi(apiClient);
}
private GravitinoMetalake createMetalake(String metalakeName) {
@@ -940,4 +1043,13 @@ public class LanceRESTServiceIT extends BaseIT {
private String getLanceRestServiceUrl() {
return String.format("http://%s:%d/lance", "localhost", getLanceRESTServerPort());
}
+
+ private Exception appendFailure(Exception failure, Exception candidate) {
+ if (failure == null) {
+ return candidate;
+ }
+
+ failure.addSuppressed(candidate);
+ return failure;
+ }
}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceSparkRESTServiceIT.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceSparkRESTServiceIT.java
new file mode 100644
index 0000000000..cebf03abc1
--- /dev/null
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceSparkRESTServiceIT.java
@@ -0,0 +1,750 @@
+/*
+ * 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.integration.test;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.errorprone.annotations.FormatMethod;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.io.FileUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Schema;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.integration.test.util.BaseIT;
+import org.apache.gravitino.integration.test.util.GravitinoITUtils;
+import org.apache.gravitino.lance.common.utils.LanceConstants;
+import org.apache.gravitino.rel.Table;
+import org.apache.spark.SparkConf;
+import org.apache.spark.sql.AnalysisException;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.SparkSession;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class LanceSparkRESTServiceIT extends BaseIT {
+
+ private static final String LANCE_SPARK_CATALOG = "lance";
+ private static final String LANCE_SPARK_CATALOG_CLASS =
+ "org.lance.spark.LanceNamespaceSparkCatalog";
+ private static final String LANCE_SPARK_BUNDLE_JAR_PATH_PROPERTY =
+ "gravitino.lance.spark.bundle.jar";
+ private static final String JAVA_MODULE_OPEN_OPTIONS =
+ "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED";
+ private static final String CATALOG_NAME = GravitinoITUtils.genRandomName("lance_spark_catalog");
+ private static final String TABLE_COLUMNS = "(id INT, score FLOAT)";
+ private static final String LANCE_CLASS_PREFIX = "org.lance.";
+ private static final String LANCE_NATIVE_LOADER_CLASS_PREFIX = "io.questdb.jar.jni.";
+ private static final String LANCE_NATIVE_RESOURCE_PREFIX = "nativelib/";
+
+ private final Set<String> createdSchemas = new LinkedHashSet<>();
+
+ private SparkSession sparkSession;
+ private URLClassLoader sparkClientClassLoader;
+ private GravitinoMetalake metalake;
+ private Catalog catalog;
+ private Path tempDir;
+
+ @Override
+ @BeforeAll
+ public void startIntegrationTest() throws Exception {
+ super.ignoreLanceAuxRestService = false;
+ super.startIntegrationTest();
+
+ this.metalake = createMetalake(getLanceRESTServerMetalakeName());
+ this.tempDir = Files.createTempDirectory("lance_spark_rest_service_it_");
+ this.catalog = createCatalog(CATALOG_NAME);
+ this.sparkSession = createSparkSession();
+ }
+
+ @AfterAll
+ public void clean() throws Exception {
+ Exception failure = null;
+
+ try {
+ stopSparkSession();
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ stopSparkClientClassLoader();
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ if (client != null) {
+ client.dropMetalake(getLanceRESTServerMetalakeName(), true);
+ }
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ if (tempDir != null) {
+ FileUtils.deleteDirectory(tempDir.toFile());
+ }
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ try {
+ super.stopIntegrationTest();
+ } catch (Exception e) {
+ failure = appendFailure(failure, e);
+ }
+
+ if (failure != null) {
+ throw failure;
+ }
+ }
+
+ @AfterEach
+ public void cleanupSchemas() {
+ for (String schemaName : createdSchemas) {
+ dropSchema(schemaName);
+ }
+ createdSchemas.clear();
+ }
+
+ @Test
+ public void testCreateAndListNamespacesViaSpark() {
+ String schemaName = createSchema("spark_ns_list");
+
+ Assertions.assertTrue(catalog.asSchemas().schemaExists(schemaName));
+ Assertions.assertTrue(listNamespaces().contains(schemaName));
+ }
+
+ @Test
+ public void testCreateNamespaceWithPropertiesViaSpark() {
+ String schemaName = newSchemaName("spark_ns_props");
+ sql("CREATE DATABASE %s WITH DBPROPERTIES ('team'='analytics', 'env'='it')", schemaName);
+ createdSchemas.add(schemaName);
+
+ Schema schema = catalog.asSchemas().loadSchema(schemaName);
+ Map<String, String> schemaProperties = schema.properties();
+
+ Assertions.assertNotNull(schemaProperties);
+ Assertions.assertEquals("analytics", schemaProperties.get("team"));
+ Assertions.assertEquals("it", schemaProperties.get("env"));
+ }
+
+ @Test
+ public void testCreateAndDescribeTableViaSpark() {
+ String schemaName = createSchema("spark_tbl_desc");
+ String tableName = newTableName("orders");
+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, tableName);
+
+ createLanceTable(schemaName, tableName);
+
+ Assertions.assertTrue(catalog.asTableCatalog().tableExists(tableIdentifier));
+ List<Row> tables = sql("SHOW TABLES IN %s", schemaName);
+ Assertions.assertTrue(
+ hasTable(tables, schemaName, tableName),
+ String.format(
+ "Expected table %s in schema %s, SHOW TABLES result: %s",
+ tableName, schemaName, tables));
+
+ Table table = catalog.asTableCatalog().loadTable(tableIdentifier);
+ assertTableLocationAndFormat(table, schemaName, tableName);
+ }
+
+ @Test
+ public void testInsertAndSelectMultipleBatchesViaSpark() {
+ String schemaName = createSchema("spark_dml");
+ String tableName = newTableName("orders");
+
+ createLanceTable(schemaName, tableName);
+ sql(
+ "INSERT INTO %s.%s VALUES (1, CAST(1.1 AS FLOAT)), (2, CAST(2.2 AS FLOAT))",
+ schemaName, tableName);
+ sql(
+ "INSERT INTO %s.%s VALUES (3, CAST(3.3 AS FLOAT)), (4, CAST(4.4 AS FLOAT))",
+ schemaName, tableName);
+
+ List<Row> rows = sql("SELECT id, score FROM %s.%s ORDER BY id", schemaName, tableName);
+ Assertions.assertEquals(4, rows.size());
+ assertRow(rows.get(0), 1, 1.1f);
+ assertRow(rows.get(1), 2, 2.2f);
+ assertRow(rows.get(2), 3, 3.3f);
+ assertRow(rows.get(3), 4, 4.4f);
+ }
+
+ @Test
+ public void testSelectFromEmptyTableViaSpark() {
+ String schemaName = createSchema("spark_empty_tbl");
+ String tableName = newTableName("orders");
+
+ createLanceTable(schemaName, tableName);
+
+ List<Row> rows = sql("SELECT id, score FROM %s.%s ORDER BY id", schemaName, tableName);
+ Assertions.assertTrue(rows.isEmpty(), "Expected no rows for a newly created empty table");
+ }
+
+ @Test
+ public void testSelectWithFilterViaSpark() {
+ String schemaName = createSchema("spark_filter_tbl");
+ String tableName = newTableName("orders");
+
+ createLanceTable(schemaName, tableName);
+ sql(
+ "INSERT INTO %s.%s VALUES "
+ + "(1, CAST(1.1 AS FLOAT)), "
+ + "(2, CAST(2.2 AS FLOAT)), "
+ + "(3, CAST(3.3 AS FLOAT)), "
+ + "(4, CAST(4.4 AS FLOAT))",
+ schemaName, tableName);
+
+ List<Row> rows =
+ sql(
+ "SELECT id, score FROM %s.%s "
+ + "WHERE id >= 2 AND score < CAST(4.0 AS FLOAT) ORDER BY id",
+ schemaName, tableName);
+ Assertions.assertEquals(2, rows.size());
+ assertRow(rows.get(0), 2, 2.2f);
+ assertRow(rows.get(1), 3, 3.3f);
+ }
+
+ @Test
+ public void testDropTableViaSpark() {
+ String schemaName = createSchema("spark_drop_tbl");
+ String tableName = newTableName("orders");
+ NameIdentifier tableIdentifier = NameIdentifier.of(schemaName, tableName);
+
+ createLanceTable(schemaName, tableName);
+ Assertions.assertTrue(catalog.asTableCatalog().tableExists(tableIdentifier));
+
+ sql("DROP TABLE %s.%s", schemaName, tableName);
+
+ Assertions.assertFalse(catalog.asTableCatalog().tableExists(tableIdentifier));
+ List<Row> tables = sql("SHOW TABLES IN %s", schemaName);
+ Assertions.assertFalse(
+ hasTable(tables, schemaName, tableName),
+ String.format(
+ "Expected table %s removed from schema %s, SHOW TABLES result: %s",
+ tableName, schemaName, tables));
+ }
+
+ @Test
+ public void testDropDatabaseViaSpark() {
+ String schemaName = createSchema("spark_drop_ns");
+ String tableName = newTableName("orders");
+
+ createLanceTable(schemaName, tableName);
+ Assertions.assertTrue(catalog.asSchemas().schemaExists(schemaName));
+
+ sql("DROP DATABASE %s CASCADE", schemaName);
+ createdSchemas.remove(schemaName);
+
+ Assertions.assertFalse(catalog.asSchemas().schemaExists(schemaName));
+ Assertions.assertFalse(listNamespaces().contains(schemaName));
+ }
+
+ @Test
+ public void testCreateDuplicateTableFails() {
+ String schemaName = createSchema("spark_duplicate_tbl");
+ String tableName = newTableName("orders");
+
+ createLanceTable(schemaName, tableName);
+
+ Throwable throwable =
+ Assertions.assertThrows(Throwable.class, () -> createLanceTable(schemaName, tableName));
+ assertSparkAnalysisFailure(throwable, "already exists", "table already exists");
+ }
+
+ @Test
+ public void testCreateTableInNonExistentSchemaFails() {
+ String nonExistentSchemaName = newSchemaName("spark_missing_ns");
+ String tableName = newTableName("orders");
+
+ RuntimeException exception =
+ Assertions.assertThrows(
+ RuntimeException.class, () -> createLanceTable(nonExistentSchemaName, tableName));
+ assertFailureContainsAll(
+ exception, "NoSuchSchemaException", nonExistentSchemaName, "does not exist");
+ Assertions.assertFalse(catalog.asSchemas().schemaExists(nonExistentSchemaName));
+ }
+
+ @Test
+ public void testSelectFromNonExistentTableFails() {
+ String schemaName = createSchema("spark_missing_tbl");
+ String nonExistentTableName = newTableName("orders");
+
+ Throwable throwable =
+ Assertions.assertThrows(
+ Throwable.class, () -> sql("SELECT * FROM %s.%s", schemaName, nonExistentTableName));
+ assertFailureContainsAll(throwable, nonExistentTableName);
+ assertFailureContainsAny(
+ throwable,
+ "Failed to describe table",
+ "TABLE_OR_VIEW_NOT_FOUND",
+ "not found",
+ "does not exist",
+ "cannot be found");
+ }
+
+ @Test
+ public void testAlterTableRenameColumnUnsupportedViaSpark() {
+ String schemaName = createSchema("spark_alter_column");
+ String tableName = newTableName("orders");
+
+ createLanceTable(schemaName, tableName);
+
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () ->
+ sql("ALTER TABLE %s.%s RENAME COLUMN score TO final_score", schemaName, tableName));
+ Assertions.assertTrue(
+ exception.getMessage().toLowerCase(Locale.ROOT).contains("not supported"),
+ "Expected unsupported-operation message, but got: " + exception.getMessage());
+
+ sql("INSERT INTO %s.%s VALUES (1, CAST(9.9 AS FLOAT))", schemaName, tableName);
+ List<Row> rows = sql("SELECT id, score FROM %s.%s ORDER BY id", schemaName, tableName);
+ Assertions.assertEquals(1, rows.size());
+ assertRow(rows.get(0), 1, 9.9f);
+
+ Throwable renamedColumnThrowable =
+ Assertions.assertThrows(
+ Throwable.class, () -> sql("SELECT final_score FROM %s.%s", schemaName, tableName));
+ assertFailureContainsAll(renamedColumnThrowable, "final_score");
+ assertFailureContainsAny(
+ renamedColumnThrowable,
+ "cannot resolve",
+ "cannot be resolved",
+ "not found",
+ "does not exist");
+ }
+
+ private GravitinoMetalake createMetalake(String metalakeName) {
+ return client.createMetalake(metalakeName, "metalake for lance spark rest service tests", null);
+ }
+
+ private Catalog createCatalog(String catalogName) {
+ return metalake.createCatalog(
+ catalogName,
+ Catalog.Type.RELATIONAL,
+ "lakehouse-generic",
+ "catalog for lance spark rest service tests",
+ ImmutableMap.of(Catalog.PROPERTY_LOCATION, tempDir.toString()));
+ }
+
+ private SparkSession createSparkSession() {
+ String bundleJarPath = System.getProperty(LANCE_SPARK_BUNDLE_JAR_PATH_PROPERTY);
+ if (bundleJarPath == null || bundleJarPath.isEmpty()) {
+ throw new IllegalStateException(
+ "Missing Spark bundle jar path, expected system property "
+ + LANCE_SPARK_BUNDLE_JAR_PATH_PROPERTY);
+ }
+
+ this.sparkClientClassLoader = createSparkClientClassLoader(bundleJarPath);
+ assertSparkClientClassLoaderUsesBundle(bundleJarPath);
+
+ SparkConf sparkConf =
+ new SparkConf()
+ .set("spark.jars", bundleJarPath)
+ .set("spark.driver.extraClassPath", bundleJarPath)
+ .set("spark.executor.extraClassPath", bundleJarPath)
+ .set("spark.sql.catalog." + LANCE_SPARK_CATALOG, LANCE_SPARK_CATALOG_CLASS)
+ .set("spark.sql.catalog." + LANCE_SPARK_CATALOG + ".impl", "rest")
+ .set("spark.sql.catalog." + LANCE_SPARK_CATALOG + ".uri", getLanceRestServiceUrl())
+ .set("spark.sql.catalog." + LANCE_SPARK_CATALOG + ".parent", CATALOG_NAME)
+ .set("spark.sql.defaultCatalog", LANCE_SPARK_CATALOG)
+ .set("spark.driver.extraJavaOptions", JAVA_MODULE_OPEN_OPTIONS)
+ .set("spark.executor.extraJavaOptions", JAVA_MODULE_OPEN_OPTIONS)
+ .set("spark.ui.enabled", "false");
+
+ // Load the bundle the same way an external Spark client does instead of relying on test
+ // classpath.
+ ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(sparkClientClassLoader);
+ try {
+ return SparkSession.builder()
+ .appName(getClass().getSimpleName())
+ .master("local[1]")
+ .config(sparkConf)
+ .getOrCreate();
+ } catch (RuntimeException | Error e) {
+ try {
+ stopSparkClientClassLoader();
+ } catch (IOException closeException) {
+ e.addSuppressed(closeException);
+ }
+ throw e;
+ } finally {
+ Thread.currentThread().setContextClassLoader(originalClassLoader);
+ }
+ }
+
+ private void stopSparkSession() {
+ if (sparkSession != null) {
+ sparkSession.close();
+ sparkSession = null;
+ }
+ }
+
+ private void stopSparkClientClassLoader() throws IOException {
+ if (sparkClientClassLoader != null) {
+ sparkClientClassLoader.close();
+ sparkClientClassLoader = null;
+ }
+ }
+
+ private URLClassLoader createSparkClientClassLoader(String bundleJarPath) {
+ try {
+ URL bundleJarUrl = Path.of(bundleJarPath).toUri().toURL();
+ return new LanceSparkBundleClassLoader(
+ bundleJarUrl, Thread.currentThread().getContextClassLoader());
+ } catch (MalformedURLException e) {
+ throw new IllegalStateException("Failed to create Spark client classloader", e);
+ }
+ }
+
+ private void assertSparkClientClassLoaderUsesBundle(String bundleJarPath) {
+ try {
+ Class<?> jniLoaderClass = sparkClientClassLoader.loadClass("org.lance.JniLoader");
+ Assertions.assertSame(
+ sparkClientClassLoader,
+ jniLoaderClass.getClassLoader(),
+ "Expected Lance JNI loader to come from the Spark bundle classloader");
+
+ URL nativeResource = sparkClientClassLoader.getResource(LANCE_NATIVE_RESOURCE_PREFIX);
+ Assertions.assertNotNull(
+ nativeResource, "Expected Lance native resources in the Spark bundle");
+ Assertions.assertTrue(
+ nativeResource.toExternalForm().contains(Path.of(bundleJarPath).getFileName().toString()),
+ "Expected Lance native resources to come from the Spark bundle, but got: "
+ + nativeResource);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Failed to load Lance JNI loader from Spark bundle", e);
+ }
+ }
+
+ @FormatMethod
+ private List<Row> sql(String sqlPattern, Object... args) {
+ ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(sparkClientClassLoader);
+ try {
+ return sparkSession.sql(String.format(Locale.ROOT, sqlPattern, args)).collectAsList();
+ } finally {
+ Thread.currentThread().setContextClassLoader(originalClassLoader);
+ }
+ }
+
+ private String createSchema(String schemaNamePrefix) {
+ String schemaName = newSchemaName(schemaNamePrefix);
+ sql("CREATE DATABASE %s", schemaName);
+ createdSchemas.add(schemaName);
+ return schemaName;
+ }
+
+ private void createLanceTable(String schemaName, String tableName) {
+ sql(
+ "CREATE TABLE %s.%s %s USING lance TBLPROPERTIES ('format'='lance')",
+ schemaName, tableName, TABLE_COLUMNS);
+ }
+
+ private void dropSchema(String schemaName) {
+ if (sparkSession != null) {
+ try {
+ sql("DROP DATABASE IF EXISTS %s CASCADE", schemaName);
+ return;
+ } catch (RuntimeException e) {
+ if (catalog == null) {
+ throw e;
+ }
+ }
+ }
+
+ if (catalog != null && catalog.asSchemas().schemaExists(schemaName)) {
+ catalog.asSchemas().dropSchema(schemaName, true);
+ }
+ }
+
+ private List<String> listNamespaces() {
+ return sql("SHOW NAMESPACES IN %s", LANCE_SPARK_CATALOG).stream()
+ .map(row -> row.getString(0))
+ .collect(Collectors.toList());
+ }
+
+ private String newSchemaName(String prefix) {
+ return GravitinoITUtils.genRandomName(prefix);
+ }
+
+ private String newTableName(String prefix) {
+ return GravitinoITUtils.genRandomName(prefix);
+ }
+
+ private void assertTableLocationAndFormat(Table table, String schemaName, String tableName) {
+ String persistedLocation = table.properties().get(Table.PROPERTY_LOCATION);
+
+ Assertions.assertEquals(LanceConstants.LANCE_TABLE_FORMAT, table.properties().get("format"));
+ Assertions.assertNotNull(persistedLocation);
+
+ String normalizedPersistedLocation = normalizeLocation(persistedLocation);
+ String normalizedSchemaPath = normalizeLocation(tempDir.resolve(schemaName).toString());
+ Assertions.assertTrue(normalizedPersistedLocation.startsWith(normalizedSchemaPath));
+ Assertions.assertTrue(normalizedPersistedLocation.contains(tableName));
+ Assertions.assertTrue(Files.exists(Path.of(persistedLocation)));
+ }
+
+ private void assertRow(Row row, int expectedId, float expectedScore) {
+ Assertions.assertEquals(expectedId, row.<Integer>getAs("id"));
+ // Spark may materialize FLOAT columns through different numeric wrappers across execution
+ // paths.
+ Assertions.assertEquals(expectedScore, ((Number) row.getAs("score")).floatValue(), 0.001f);
+ }
+
+ private boolean hasTable(List<Row> tables, String schemaName, String tableName) {
+ String expectedSchema = schemaName.toLowerCase(Locale.ROOT);
+ String expectedTable = tableName.toLowerCase(Locale.ROOT);
+
+ for (Row row : tables) {
+ Map<String, String> rowValues = extractShowTableRowValues(row);
+ String actualSchema = rowValues.get("namespace");
+ String rawTableName = rowValues.get("tableName");
+ if (actualSchema == null || rawTableName == null) {
+ continue;
+ }
+
+ if (expectedSchema.equals(actualSchema.toLowerCase(Locale.ROOT))
+ && expectedTable.equals(extractLeafTableName(rawTableName).toLowerCase(Locale.ROOT))) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private Map<String, String> extractShowTableRowValues(Row row) {
+ // SHOW TABLES rows can be exposed either as named columns or positional values.
+ Map<String, String> values = new LinkedHashMap<>();
+ values.put("namespace", getStringColumn(row, "namespace", 0));
+ values.put("tableName", getStringColumn(row, "tableName", 1));
+ return values;
+ }
+
+ private String getStringColumn(Row row, String columnName, int fallbackIndex) {
+ try {
+ Object value = row.getAs(columnName);
+ if (value != null) {
+ return value.toString();
+ }
+ } catch (IllegalArgumentException ignored) {
+ // Fall back to index access if column name is not present.
+ }
+
+ if (fallbackIndex >= 0 && fallbackIndex < row.size()) {
+ Object value = row.get(fallbackIndex);
+ return value == null ? null : value.toString();
+ }
+
+ return null;
+ }
+
+ private String extractLeafTableName(String rawTableName) {
+ int delimiterIndex = Math.max(rawTableName.lastIndexOf('$'), rawTableName.lastIndexOf('.'));
+ if (delimiterIndex < 0) {
+ return rawTableName;
+ }
+
+ return rawTableName.substring(delimiterIndex + 1);
+ }
+
+ private void assertSparkAnalysisFailure(Throwable throwable, String... expectedMessageParts) {
+ Assertions.assertTrue(
+ hasCause(throwable, AnalysisException.class),
+ String.format(
+ "Expected AnalysisException in cause chain, but got %s with message: %s",
+ throwable.getClass().getName(), throwable.getMessage()));
+ Assertions.assertTrue(
+ containsAnyMessagePart(throwable, expectedMessageParts),
+ String.format(
+ "Expected error message to contain one of %s, but message was: %s",
+ Arrays.toString(expectedMessageParts), throwable.getMessage()));
+ }
+
+ private void assertFailureContainsAll(Throwable throwable, String... expectedMessageParts) {
+ for (String expectedMessagePart : expectedMessageParts) {
+ Assertions.assertTrue(
+ containsMessagePart(throwable, expectedMessagePart),
+ String.format(
+ "Expected error message to contain \"%s\", but message was: %s",
+ expectedMessagePart, throwable.getMessage()));
+ }
+ }
+
+ private void assertFailureContainsAny(Throwable throwable, String... expectedMessageParts) {
+ Assertions.assertTrue(
+ containsAnyMessagePart(throwable, expectedMessageParts),
+ String.format(
+ "Expected error message to contain one of %s, but message was: %s",
+ Arrays.toString(expectedMessageParts), throwable.getMessage()));
+ }
+
+ private boolean hasCause(Throwable throwable, Class<? extends Throwable> expectedType) {
+ for (Throwable current = throwable; current != null; current = current.getCause()) {
+ if (expectedType.isInstance(current)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private boolean containsAnyMessagePart(Throwable throwable, String... expectedMessageParts) {
+ for (String expectedMessagePart : expectedMessageParts) {
+ if (containsMessagePart(throwable, expectedMessagePart)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private boolean containsMessagePart(Throwable throwable, String expectedMessagePart) {
+ String expected = expectedMessagePart.toLowerCase(Locale.ROOT);
+ for (Throwable current = throwable; current != null; current = current.getCause()) {
+ String message = current.getMessage();
+ if (message == null) {
+ continue;
+ }
+
+ String normalizedMessage = message.toLowerCase(Locale.ROOT);
+ if (normalizedMessage.contains(expected)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private Exception appendFailure(Exception failure, Exception candidate) {
+ if (failure == null) {
+ return candidate;
+ }
+
+ failure.addSuppressed(candidate);
+ return failure;
+ }
+
+ private String getLanceRestServiceUrl() {
+ return String.format("http://localhost:%d/lance", getLanceRESTServerPort());
+ }
+
+ private static String normalizeLocation(String location) {
+ if (location.endsWith("/")) {
+ return location.substring(0, location.length() - 1);
+ }
+
+ return location;
+ }
+
+ private static class LanceSparkBundleClassLoader extends URLClassLoader {
+
+ private LanceSparkBundleClassLoader(URL bundleJarUrl, ClassLoader parent) {
+ super(new URL[] {bundleJarUrl}, parent);
+ }
+
+ @Override
+ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ synchronized (getClassLoadingLock(name)) {
+ Class<?> loadedClass = findLoadedClass(name);
+ if (loadedClass == null) {
+ loadedClass = loadUnresolvedClass(name);
+ }
+
+ if (resolve) {
+ resolveClass(loadedClass);
+ }
+
+ return loadedClass;
+ }
+ }
+
+ @Override
+ public URL getResource(String name) {
+ if (isLanceNativeResource(name)) {
+ URL resource = findResource(name);
+ if (resource != null) {
+ return resource;
+ }
+ }
+
+ return super.getResource(name);
+ }
+
+ @Override
+ public Enumeration<URL> getResources(String name) throws IOException {
+ if (!isLanceNativeResource(name)) {
+ return super.getResources(name);
+ }
+
+ List<URL> resources = new ArrayList<>();
+ resources.addAll(Collections.list(findResources(name)));
+
+ ClassLoader parent = getParent();
+ Enumeration<URL> parentResources =
+ parent == null ? ClassLoader.getSystemResources(name) : parent.getResources(name);
+ resources.addAll(Collections.list(parentResources));
+
+ return Collections.enumeration(resources);
+ }
+
+ private Class<?> loadUnresolvedClass(String name) throws ClassNotFoundException {
+ if (isLanceBundleClass(name)) {
+ try {
+ return findClass(name);
+ } catch (ClassNotFoundException e) {
+ return super.loadClass(name, false);
+ }
+ }
+
+ return super.loadClass(name, false);
+ }
+
+ private boolean isLanceBundleClass(String name) {
+ return name.startsWith(LANCE_CLASS_PREFIX)
+ || name.startsWith(LANCE_NATIVE_LOADER_CLASS_PREFIX);
+ }
+
+ private boolean isLanceNativeResource(String name) {
+ return name.startsWith(LANCE_NATIVE_RESOURCE_PREFIX);
+ }
+ }
+}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestGravitinoLanceTableOperations.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestGravitinoLanceTableOperations.java
index 2e7047f98a..10c9b6bf32 100644
--- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestGravitinoLanceTableOperations.java
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestGravitinoLanceTableOperations.java
@@ -21,11 +21,6 @@ package org.apache.gravitino.lance.service.rest;
import static org.apache.gravitino.lance.common.utils.LanceConstants.LANCE_TABLE_VERSION;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsResponse;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsResponse;
-import com.lancedb.lance.namespace.model.ColumnAlteration;
import java.util.List;
import java.util.Map;
import org.apache.gravitino.lance.common.ops.gravitino.GravitinoLanceTableAlterHandler.AlterColumnsGravitinoLance;
@@ -34,6 +29,11 @@ import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableChange;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.lance.namespace.model.AlterColumnsEntry;
+import org.lance.namespace.model.AlterTableAlterColumnsRequest;
+import org.lance.namespace.model.AlterTableAlterColumnsResponse;
+import org.lance.namespace.model.AlterTableDropColumnsRequest;
+import org.lance.namespace.model.AlterTableDropColumnsResponse;
import org.mockito.Mockito;
class TestGravitinoLanceTableOperations {
@@ -58,8 +58,8 @@ class TestGravitinoLanceTableOperations {
@Test
void testAlterColumnsHandlerBuildsChangesAndSetsVersion() {
AlterTableAlterColumnsRequest request = new AlterTableAlterColumnsRequest();
- ColumnAlteration alteration = new ColumnAlteration();
- alteration.setColumn("c1");
+ AlterColumnsEntry alteration = new AlterColumnsEntry();
+ alteration.setPath("c1");
alteration.setRename("c1_new");
request.setAlterations(List.of(alteration));
@@ -74,4 +74,22 @@ class TestGravitinoLanceTableOperations {
AlterTableAlterColumnsResponse response = handler.handle(table, request);
Assertions.assertEquals(3L, response.getVersion());
}
+
+ @Test
+ void testAlterColumnsHandlerRejectsUnsupportedFields() {
+ AlterTableAlterColumnsRequest request = new AlterTableAlterColumnsRequest();
+ AlterColumnsEntry alteration = new AlterColumnsEntry();
+ alteration.setPath("c1");
+ alteration.setRename("c1_new");
+ alteration.setNullable(Boolean.TRUE);
+ request.setAlterations(List.of(alteration));
+
+ AlterColumnsGravitinoLance handler = new AlterColumnsGravitinoLance();
+
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> handler.buildGravitinoTableChange(request));
+ Assertions.assertEquals(
+ "Only RENAME alteration is supported currently.", exception.getMessage());
+ }
}
diff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestLanceNamespaceOperations.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestLanceNamespaceOperations.java
index 388977b0df..2d8000fc1b 100644
--- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestLanceNamespaceOperations.java
+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/service/rest/TestLanceNamespaceOperations.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.lance.service.rest;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
@@ -26,34 +27,14 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
-import com.lancedb.lance.namespace.LanceNamespaceException;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableAlterColumnsResponse;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsRequest;
-import com.lancedb.lance.namespace.model.AlterTableDropColumnsResponse;
-import com.lancedb.lance.namespace.model.ColumnAlteration;
-import com.lancedb.lance.namespace.model.CreateEmptyTableRequest;
-import com.lancedb.lance.namespace.model.CreateEmptyTableResponse;
-import com.lancedb.lance.namespace.model.CreateNamespaceRequest;
-import com.lancedb.lance.namespace.model.CreateNamespaceResponse;
-import com.lancedb.lance.namespace.model.CreateTableResponse;
-import com.lancedb.lance.namespace.model.DeregisterTableRequest;
-import com.lancedb.lance.namespace.model.DeregisterTableResponse;
-import com.lancedb.lance.namespace.model.DescribeNamespaceResponse;
-import com.lancedb.lance.namespace.model.DescribeTableRequest;
-import com.lancedb.lance.namespace.model.DescribeTableResponse;
-import com.lancedb.lance.namespace.model.DropNamespaceRequest;
-import com.lancedb.lance.namespace.model.DropNamespaceResponse;
-import com.lancedb.lance.namespace.model.DropTableResponse;
-import com.lancedb.lance.namespace.model.ErrorResponse;
-import com.lancedb.lance.namespace.model.ListNamespacesResponse;
-import com.lancedb.lance.namespace.model.RegisterTableRequest;
-import com.lancedb.lance.namespace.model.RegisterTableResponse;
import java.io.IOException;
import java.util.List;
+import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.client.Entity;
@@ -65,6 +46,7 @@ import org.apache.gravitino.lance.common.ops.LanceTableOperations;
import org.apache.gravitino.lance.common.ops.NamespaceWrapper;
import org.apache.gravitino.lance.common.utils.LanceConstants;
import org.apache.gravitino.rest.RESTUtils;
+import org.glassfish.jersey.CommonProperties;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
@@ -72,8 +54,34 @@ import org.glassfish.jersey.test.TestProperties;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.lance.namespace.errors.TableNotFoundException;
+import org.lance.namespace.model.AlterColumnsEntry;
+import org.lance.namespace.model.AlterTableAlterColumnsRequest;
+import org.lance.namespace.model.AlterTableAlterColumnsResponse;
+import org.lance.namespace.model.AlterTableDropColumnsRequest;
+import org.lance.namespace.model.AlterTableDropColumnsResponse;
+import org.lance.namespace.model.CreateEmptyTableRequest;
+import org.lance.namespace.model.CreateEmptyTableResponse;
+import org.lance.namespace.model.CreateNamespaceRequest;
+import org.lance.namespace.model.CreateNamespaceResponse;
+import org.lance.namespace.model.CreateTableResponse;
+import org.lance.namespace.model.DeclareTableRequest;
+import org.lance.namespace.model.DeclareTableResponse;
+import org.lance.namespace.model.DeregisterTableRequest;
+import org.lance.namespace.model.DeregisterTableResponse;
+import org.lance.namespace.model.DescribeNamespaceResponse;
+import org.lance.namespace.model.DescribeTableRequest;
+import org.lance.namespace.model.DescribeTableResponse;
+import org.lance.namespace.model.DropNamespaceRequest;
+import org.lance.namespace.model.DropNamespaceResponse;
+import org.lance.namespace.model.DropTableResponse;
+import org.lance.namespace.model.ErrorResponse;
+import org.lance.namespace.model.ListNamespacesResponse;
+import org.lance.namespace.model.RegisterTableRequest;
+import org.lance.namespace.model.RegisterTableResponse;
import org.mockito.Mockito;
+@SuppressWarnings("deprecation")
public class TestLanceNamespaceOperations extends JerseyTest {
private static class MockServletRequestFactory extends ServletRequestFactoryBase {
@Override
@@ -99,6 +107,17 @@ public class TestLanceNamespaceOperations extends JerseyTest {
}
ResourceConfig resourceConfig = new ResourceConfig();
+ // Disable Jersey's auto-discovery (including JacksonAutoDiscoverable) which would
+ // auto-register a Jackson provider that calls ObjectMapper.findAndRegisterModules().
+ // When jackson-module-scala is on the classpath (pulled in by spark-sql), the
+ // auto-discovered provider deserializes JSON objects as Scala Maps instead of
+ // java.util.Map, breaking extractPropertiesFromBody().
+ resourceConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
+ resourceConfig.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
+ ObjectMapper mapper = new ObjectMapper();
+ JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
+ provider.setMapper(mapper);
+ resourceConfig.register(provider);
resourceConfig.register(LanceNamespaceOperations.class);
resourceConfig.register(org.apache.gravitino.lance.service.rest.LanceTableOperations.class);
resourceConfig.register(
@@ -158,6 +177,20 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(listNamespacesResp.getNamespaces(), respEntity.getNamespaces());
Assertions.assertEquals(listNamespacesResp.getPageToken(), respEntity.getPageToken());
+ // list namespaces via root endpoint
+ resp =
+ target("/v1/namespace/list")
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .get();
+
+ Mockito.verify(namespaceOps).listNamespaces(eq(""), eq(Pattern.quote(delimiter)), any(), any());
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+ respEntity = resp.readEntity(ListNamespacesResponse.class);
+ Assertions.assertEquals(listNamespacesResp.getNamespaces(), respEntity.getNamespaces());
+ Assertions.assertEquals(listNamespacesResp.getPageToken(), respEntity.getPageToken());
+
// test throw exception
when(namespaceOps.listNamespaces(any(), any(), any(), any()))
.thenThrow(new RuntimeException("Test exception"));
@@ -172,12 +205,22 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(500, errorResp.getCode());
+ Assertions.assertEquals(18, errorResp.getCode());
Assertions.assertEquals("Test exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
Assertions.assertEquals("ns1.ns2", errorResp.getInstance());
Assertions.assertNotNull(errorResp.getDetail());
Assertions.assertTrue(errorResp.getDetail().contains("Test exception"));
+
+ // root endpoint should use explicit root identifier instead of delimiter in error instance
+ resp =
+ target("/v1/namespace/list")
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .get();
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp.getStatus());
+ errorResp = resp.readEntity(ErrorResponse.class);
+ Assertions.assertEquals("", errorResp.getInstance());
}
@Test
@@ -216,9 +259,19 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(500, errorResp.getCode());
+ Assertions.assertEquals(18, errorResp.getCode());
Assertions.assertEquals("Test exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
+ }
+
+ @Test
+ public void testDescribeNamespaceOnRootUnsupported() {
+ Mockito.clearInvocations(namespaceOps);
+
+ Response resp =
+ target("/v1/namespace/describe").request(MediaType.APPLICATION_JSON_TYPE).post(null);
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp.getStatus());
+ Mockito.verifyNoInteractions(namespaceOps);
}
@Test
@@ -243,7 +296,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
.createNamespace(
eq(namespaceId),
eq(Pattern.quote(delimiter)),
- eq(CreateNamespaceRequest.ModeEnum.CREATE),
+ eq("create"),
eq(createNamespaceReq.getProperties()));
Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
@@ -265,9 +318,8 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(500, errorResp.getCode());
+ Assertions.assertEquals(18, errorResp.getCode());
Assertions.assertEquals("Test exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -300,9 +352,8 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(404, errorResp.getCode());
+ Assertions.assertEquals(1, errorResp.getCode());
Assertions.assertEquals("Not found", errorResp.getError());
- Assertions.assertEquals(NoSuchCatalogException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -321,11 +372,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
.post(Entity.entity(dropNamespaceReq, MediaType.APPLICATION_JSON_TYPE));
Mockito.verify(namespaceOps)
- .dropNamespace(
- eq(namespaceId),
- eq(Pattern.quote(delimiter)),
- eq(DropNamespaceRequest.ModeEnum.FAIL),
- eq(DropNamespaceRequest.BehaviorEnum.RESTRICT));
+ .dropNamespace(eq(namespaceId), eq(Pattern.quote(delimiter)), eq("fail"), eq("restrict"));
Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
@@ -343,9 +390,8 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(500, errorResp.getCode());
+ Assertions.assertEquals(18, errorResp.getCode());
Assertions.assertEquals("Test exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -395,7 +441,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Runtime exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -406,7 +451,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
// Test normal
CreateEmptyTableResponse createTableResponse = new CreateEmptyTableResponse();
createTableResponse.setLocation("/path/to/table");
- createTableResponse.setProperties(ImmutableMap.of("key", "value"));
+ createTableResponse.setStorageOptions(ImmutableMap.of("key", "value"));
when(tableOps.createEmptyTable(any(), any(), any(), any())).thenReturn(createTableResponse);
CreateEmptyTableRequest tableRequest = new CreateEmptyTableRequest();
@@ -422,7 +467,66 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
CreateEmptyTableResponse response = resp.readEntity(CreateEmptyTableResponse.class);
Assertions.assertEquals(createTableResponse.getLocation(), response.getLocation());
- Assertions.assertEquals(createTableResponse.getProperties(), response.getProperties());
+ Assertions.assertEquals(createTableResponse.getStorageOptions(), response.getStorageOptions());
+
+ Mockito.verify(tableOps)
+ .createEmptyTable(eq(tableIds), eq(delimiter), eq("/path/to/table"), eq(Map.of()));
+
+ // Backward compatibility: request-body properties should still be accepted.
+ Mockito.reset(tableOps);
+ when(tableOps.createEmptyTable(any(), any(), any(), any())).thenReturn(createTableResponse);
+ String bodyWithProperties =
+ "{"
+ + "\"id\":[\"catalog\",\"scheme\",\"create_empty_table\"],"
+ + "\"location\":\"/path/to/table\","
+ + "\"properties\":{\"k1\":\"v1\",\"k2\":2}"
+ + "}";
+ resp =
+ target(String.format("/v1/table/%s/create-empty", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(bodyWithProperties, MediaType.APPLICATION_JSON_TYPE));
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Mockito.verify(tableOps)
+ .createEmptyTable(
+ eq(tableIds),
+ eq(delimiter),
+ eq("/path/to/table"),
+ argThat(
+ (Map<String, String> props) ->
+ "v1".equals(props.get("k1"))
+ && "2".equals(props.get("k2"))
+ && props.size() == 2));
+
+ // Header properties should override body properties on key conflicts.
+ Mockito.reset(tableOps);
+ when(tableOps.createEmptyTable(any(), any(), any(), any())).thenReturn(createTableResponse);
+ String bodyWithOverlappedProperties =
+ "{"
+ + "\"id\":[\"catalog\",\"scheme\",\"create_empty_table\"],"
+ + "\"location\":\"/path/to/table\","
+ + "\"properties\":{\"k1\":\"body\",\"k2\":\"body2\"}"
+ + "}";
+ resp =
+ target(String.format("/v1/table/%s/create-empty", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .header(
+ LanceConstants.LANCE_TABLE_PROPERTIES_PREFIX_HEADER,
+ "{\"k1\":\"header\",\"k3\":\"v3\"}")
+ .post(Entity.entity(bodyWithOverlappedProperties, MediaType.APPLICATION_JSON_TYPE));
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Mockito.verify(tableOps)
+ .createEmptyTable(
+ eq(tableIds),
+ eq(delimiter),
+ eq("/path/to/table"),
+ argThat(
+ (Map<String, String> props) ->
+ "header".equals(props.get("k1"))
+ && "body2".equals(props.get("k2"))
+ && "v3".equals(props.get("k3"))
+ && props.size() == 3));
Mockito.reset(tableOps);
// Test illegal argument
@@ -452,7 +556,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Runtime exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -468,7 +571,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
RegisterTableRequest tableRequest = new RegisterTableRequest();
tableRequest.setLocation("/path/to/registered_table");
- tableRequest.setMode(RegisterTableRequest.ModeEnum.CREATE);
+ tableRequest.setMode("create");
Response resp =
target(String.format("/v1/table/%s/register", tableIds))
@@ -509,7 +612,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Runtime exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -529,7 +631,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
RegisterTableRequest tableRequest = new RegisterTableRequest();
tableRequest.setLocation("/path/to/registered_table");
- tableRequest.setMode(RegisterTableRequest.ModeEnum.CREATE);
+ tableRequest.setMode("create");
tableRequest.setProperties(ImmutableMap.of("custom-key", "custom-value"));
Response resp =
@@ -544,7 +646,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Mockito.verify(tableOps)
.registerTable(
eq(tableIds),
- eq(RegisterTableRequest.ModeEnum.CREATE),
+ eq("create"),
eq(delimiter),
Mockito.argThat(
props ->
@@ -594,9 +696,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
// Test not found exception
Mockito.reset(tableOps);
when(tableOps.deregisterTable(any(), any()))
- .thenThrow(
- LanceNamespaceException.notFound(
- "Table not found", "NoSuchTableException", tableIds, ""));
+ .thenThrow(new TableNotFoundException("Table not found", "", tableIds));
resp =
target(String.format("/v1/table/%s/deregister", tableIds))
.queryParam("delimiter", delimiter)
@@ -619,7 +719,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Runtime exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -630,7 +729,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
// Test normal
DescribeTableResponse createTableResponse = new DescribeTableResponse();
createTableResponse.setLocation("/path/to/describe_table");
- createTableResponse.setProperties(ImmutableMap.of("key", "value"));
+ createTableResponse.setMetadata(ImmutableMap.of("key", "value"));
when(tableOps.describeTable(any(), any(), any())).thenReturn(createTableResponse);
DescribeTableRequest tableRequest = new DescribeTableRequest();
@@ -644,14 +743,12 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
DescribeTableResponse response = resp.readEntity(DescribeTableResponse.class);
Assertions.assertEquals(createTableResponse.getLocation(), response.getLocation());
- Assertions.assertEquals(createTableResponse.getProperties(), response.getProperties());
+ Assertions.assertEquals(createTableResponse.getMetadata(), response.getMetadata());
// Test not found exception
Mockito.reset(tableOps);
when(tableOps.describeTable(any(), any(), any()))
- .thenThrow(
- LanceNamespaceException.notFound(
- "Table not found", "NoSuchTableException", tableIds, ""));
+ .thenThrow(new TableNotFoundException("Table not found", "", tableIds));
resp =
target(String.format("/v1/table/%s/describe", tableIds))
.queryParam("delimiter", delimiter)
@@ -674,7 +771,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Runtime exception", errorResp.getError());
- Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp.getType());
}
@Test
@@ -693,9 +789,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
// test throw exception
- doThrow(
- LanceNamespaceException.notFound(
- "Table not found", "NoSuchTableException", tableIds, ""))
+ doThrow(new TableNotFoundException("Table not found", "", tableIds))
.when(tableOps)
.tableExists(any(), any());
resp =
@@ -708,9 +802,8 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(404, errorResp.getCode());
+ Assertions.assertEquals(4, errorResp.getCode());
Assertions.assertEquals("Table not found", errorResp.getError());
- Assertions.assertEquals("NoSuchTableException", errorResp.getType());
// Test runtime exception
Mockito.reset(tableOps);
@@ -749,9 +842,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(dropTableResponse.getLocation(), response.getLocation());
// test throw exception
- doThrow(
- LanceNamespaceException.notFound(
- "Table not found", "NoSuchTableException", tableIds, ""))
+ doThrow(new TableNotFoundException("Table not found", "", tableIds))
.when(tableOps)
.dropTable(any(), any());
resp =
@@ -764,9 +855,8 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
- Assertions.assertEquals(404, errorResp.getCode());
+ Assertions.assertEquals(4, errorResp.getCode());
Assertions.assertEquals("Table not found", errorResp.getError());
- Assertions.assertEquals("NoSuchTableException", errorResp.getType());
// Test runtime exception
Mockito.reset(tableOps);
@@ -817,7 +907,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Columns to drop cannot be empty.", errorResp.getError());
- Assertions.assertEquals(IllegalArgumentException.class.getSimpleName(), errorResp.getType());
// Test blank column names validation
AlterTableDropColumnsRequest blankColumnRequest = new AlterTableDropColumnsRequest();
@@ -831,7 +920,6 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
errorResp = resp.readEntity(ErrorResponse.class);
Assertions.assertEquals("Columns to drop cannot be blank.", errorResp.getError());
- Assertions.assertEquals(IllegalArgumentException.class.getSimpleName(), errorResp.getType());
// Test runtime exception
Mockito.reset(tableOps);
@@ -849,9 +937,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
// Test No such table exception
Mockito.reset(tableOps);
when(tableOps.alterTable(any(), any(), any(AlterTableDropColumnsRequest.class)))
- .thenThrow(
- LanceNamespaceException.notFound(
- "Table not found", "NoSuchTableException", tableIds, ""));
+ .thenThrow(new TableNotFoundException("Table not found", "", tableIds));
resp =
target(String.format("/v1/table/%s/drop_columns", tableIds))
.queryParam("delimiter", delimiter)
@@ -870,8 +956,8 @@ public class TestLanceNamespaceOperations extends JerseyTest {
AlterTableAlterColumnsRequest alterColumnsRequest = new AlterTableAlterColumnsRequest();
alterColumnsRequest.setId(List.of("catalog", "scheme", "alter_table_alter_columns"));
- ColumnAlteration columnAlteration = new ColumnAlteration();
- columnAlteration.setColumn("col1");
+ AlterColumnsEntry columnAlteration = new AlterColumnsEntry();
+ columnAlteration.setPath("col1");
columnAlteration.setRename("col1_new");
alterColumnsRequest.setAlterations(List.of(columnAlteration));
@@ -888,6 +974,39 @@ public class TestLanceNamespaceOperations extends JerseyTest {
AlterTableAlterColumnsResponse response = resp.readEntity(AlterTableAlterColumnsResponse.class);
Assertions.assertEquals(alterColumnsResponse.getVersion(), response.getVersion());
+ // Missing rename should return a clear validation message.
+ AlterTableAlterColumnsRequest missingRenameRequest = new AlterTableAlterColumnsRequest();
+ missingRenameRequest.setId(List.of("catalog", "scheme", "alter_table_alter_columns"));
+ AlterColumnsEntry missingRenameAlteration = new AlterColumnsEntry();
+ missingRenameAlteration.setPath("col1");
+ missingRenameAlteration.setRename(" ");
+ missingRenameRequest.setAlterations(List.of(missingRenameAlteration));
+ resp =
+ target(String.format("/v1/table/%s/alter_columns", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(missingRenameRequest, MediaType.APPLICATION_JSON_TYPE));
+ Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
+ ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
+ Assertions.assertEquals("Rename field must be specified.", errorResp.getError());
+
+ // Non-rename alteration fields should still be rejected separately.
+ AlterTableAlterColumnsRequest withUnsupportedFieldRequest = new AlterTableAlterColumnsRequest();
+ withUnsupportedFieldRequest.setId(List.of("catalog", "scheme", "alter_table_alter_columns"));
+ AlterColumnsEntry withUnsupportedFieldAlteration = new AlterColumnsEntry();
+ withUnsupportedFieldAlteration.setPath("col1");
+ withUnsupportedFieldAlteration.setRename("col1_new");
+ withUnsupportedFieldAlteration.setNullable(Boolean.TRUE);
+ withUnsupportedFieldRequest.setAlterations(List.of(withUnsupportedFieldAlteration));
+ resp =
+ target(String.format("/v1/table/%s/alter_columns", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(withUnsupportedFieldRequest, MediaType.APPLICATION_JSON_TYPE));
+ Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
+ errorResp = resp.readEntity(ErrorResponse.class);
+ Assertions.assertEquals("Only RENAME alteration is supported currently.", errorResp.getError());
+
Mockito.reset(tableOps);
when(tableOps.alterTable(any(), any(), any(AlterTableAlterColumnsRequest.class)))
.thenThrow(new RuntimeException("Runtime exception"));
@@ -902,9 +1021,7 @@ public class TestLanceNamespaceOperations extends JerseyTest {
Mockito.reset(tableOps);
when(tableOps.alterTable(any(), any(), any(AlterTableAlterColumnsRequest.class)))
- .thenThrow(
- LanceNamespaceException.notFound(
- "Table not found", "NoSuchTableException", tableIds, ""));
+ .thenThrow(new TableNotFoundException("Table not found", "", tableIds));
resp =
target(String.format("/v1/table/%s/alter_columns", tableIds))
.queryParam("delimiter", delimiter)
@@ -912,4 +1029,63 @@ public class TestLanceNamespaceOperations extends JerseyTest {
.post(Entity.entity(alterColumnsRequest, MediaType.APPLICATION_JSON_TYPE));
Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp.getStatus());
}
+
+ @Test
+ void testDeclareTable() {
+ String tableIds = "catalog.scheme.declare_table";
+ String delimiter = ".";
+
+ // Test normal
+ DeclareTableResponse declareTableResponse = new DeclareTableResponse();
+ declareTableResponse.setLocation("/path/to/table");
+ declareTableResponse.setStorageOptions(ImmutableMap.of("key", "value"));
+ when(tableOps.declareTable(any(), any(), any(), any())).thenReturn(declareTableResponse);
+
+ DeclareTableRequest tableRequest = new DeclareTableRequest();
+ tableRequest.setLocation("/path/to/table");
+
+ Response resp =
+ target(String.format("/v1/table/%s/declare", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(tableRequest, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+ DeclareTableResponse response = resp.readEntity(DeclareTableResponse.class);
+ Assertions.assertEquals(declareTableResponse.getLocation(), response.getLocation());
+ Assertions.assertEquals(declareTableResponse.getStorageOptions(), response.getStorageOptions());
+
+ Mockito.verify(tableOps)
+ .declareTable(eq(tableIds), eq(delimiter), eq("/path/to/table"), eq(Map.of()));
+
+ // Test illegal argument
+ Mockito.reset(tableOps);
+ when(tableOps.declareTable(any(), any(), any(), any()))
+ .thenThrow(new IllegalArgumentException("Illegal argument"));
+
+ resp =
+ target(String.format("/v1/table/%s/declare", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(tableRequest, MediaType.APPLICATION_JSON_TYPE));
+ Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+
+ // Test runtime exception
+ Mockito.reset(tableOps);
+ when(tableOps.declareTable(any(), any(), any(), any()))
+ .thenThrow(new RuntimeException("Runtime exception"));
+ resp =
+ target(String.format("/v1/table/%s/declare", tableIds))
+ .queryParam("delimiter", delimiter)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(tableRequest, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+ ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
+ Assertions.assertEquals("Runtime exception", errorResp.getError());
+ }
}