mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix: accept Lance-normalized schemas when reopening a table with exist_ok (#5036)
## Why Lance stores a fixed-size list of a primitive type without its child field and reads the child back as a nullable `item`. It also stores `Utf8View`/`BinaryView` as `Utf8`/`Binary`. A schema such as `DataType::new_fixed_size_list(DataType::Float32, n, false)` therefore never equals the stored schema. In Python, Rust and TypeScript, `exist_ok` fails with "Provided schema does not match existing table schema" on every run after the first. Part of #2570. This fixes reopening an existing table with `exist_ok` and the original schema. The first create still normalizes the child field, so `table.schema()` returns Lance's schema and the issue's `assert_eq!(table.schema(), schema)` still differs. ## What changed - `ListingDatabase::handle_table_exists` keeps the exact comparison. It also accepts a provided schema that converts through `lance::datatypes::Schema` to the table's schema, which is the same conversion `NativeTable::schema` uses. A schema Lance can't convert still returns `Error::Schema`. - The reopen now passes the create request's `location` into `OpenTableRequest` before the `exist_ok` callback runs. It used to open the default location, so `create_table(..., exist_ok, location)` could return a different table with the same name. - Out of scope: the remote client's `exist_ok` fallback (`remote/db.rs`) has the same strict `!=`. Whether it triggers depends on what the server's describe returns, so I left it unchanged. ## Verification - `test_create_table_exist_ok_with_lance_normalized_type` covers an FSL with a non-null child, an FSL whose child is named `element`, and `Utf8View`. A real difference (top-level nullability) still fails with `Error::Schema`. - `test_create_table_exist_ok_opens_requested_location` puts `id=10` at the default location and `id=20` at an explicit one. With the original and with the normalized schema, `exist_ok` with the explicit location must return that URI and read back `id=20`. - Each test fails without its fix and passes with it. `cargo test -p lancedb --lib` (2383 passed), `cargo clippy -p lancedb --tests -- -D warnings`, `cargo fmt --check` and typos are clean. The Python bindings are unchanged, and `python/tests/test_db.py` was not run locally. --------- Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
@@ -235,7 +235,8 @@ impl CreateTableBuilder {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use arrow_array::{
|
||||
Array, FixedSizeListArray, Float32Array, RecordBatch, RecordBatchIterator, record_batch,
|
||||
Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, RecordBatchIterator,
|
||||
cast::AsArray, record_batch, types::Int32Type,
|
||||
};
|
||||
use arrow_schema::{ArrowError, DataType, Field, Schema};
|
||||
use futures::TryStreamExt;
|
||||
@@ -492,6 +493,105 @@ mod tests {
|
||||
assert_eq!(other_schema, overwritten.schema().await.unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[rstest::rstest]
|
||||
#[case::non_nullable_list_item(DataType::new_fixed_size_list(DataType::Float32, 2, false))]
|
||||
#[case::renamed_list_item(DataType::FixedSizeList(
|
||||
Arc::new(Field::new("element", DataType::Float32, true)),
|
||||
2
|
||||
))]
|
||||
#[case::string_view(DataType::Utf8View)]
|
||||
async fn test_create_table_exist_ok_with_lance_normalized_type(#[case] data_type: DataType) {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let uri = tmp_dir.path().to_str().unwrap();
|
||||
let db = connect(uri).execute().await.unwrap();
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("x", data_type.clone(), false)]));
|
||||
db.create_empty_table("test", schema.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
db.create_empty_table("test", schema)
|
||||
.mode(CreateTableMode::exist_ok(|req| req))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let nullable_schema = Arc::new(Schema::new(vec![Field::new("x", data_type, true)]));
|
||||
let result = db
|
||||
.create_empty_table("test", nullable_schema)
|
||||
.mode(CreateTableMode::exist_ok(|req| req))
|
||||
.execute()
|
||||
.await;
|
||||
assert!(matches!(result, Err(Error::Schema { .. })));
|
||||
}
|
||||
|
||||
/// `exist_ok` must reopen the table at the requested location, not the one at the
|
||||
/// default location of a table with the same name.
|
||||
#[tokio::test]
|
||||
#[rstest::rstest]
|
||||
#[case::original_schema(false)]
|
||||
#[case::normalized_schema(true)]
|
||||
async fn test_create_table_exist_ok_opens_requested_location(#[case] nullable_item: bool) {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let db = connect(tmp_dir.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let location = tmp_dir.path().join("elsewhere").join("test.lance");
|
||||
let location = location.to_str().unwrap();
|
||||
|
||||
let item = Arc::new(Field::new("item", DataType::Float32, nullable_item));
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int32, false),
|
||||
Field::new("vector", DataType::FixedSizeList(item.clone(), 2), false),
|
||||
]));
|
||||
let batch_with_id = |id: i32| {
|
||||
let vector = FixedSizeListArray::new(
|
||||
item.clone(),
|
||||
2,
|
||||
Arc::new(Float32Array::from(vec![1.0, 2.0])),
|
||||
None,
|
||||
);
|
||||
RecordBatch::try_new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(Int32Array::from(vec![id])), Arc::new(vector)],
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
db.create_table("test", batch_with_id(10))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
db.create_table("test", batch_with_id(20))
|
||||
.location(location)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let table = db
|
||||
.create_empty_table("test", schema.clone())
|
||||
.location(location)
|
||||
.mode(CreateTableMode::exist_ok(|req| req))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(table.uri().await.unwrap(), location);
|
||||
let batches = table
|
||||
.query()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let ids = batches
|
||||
.iter()
|
||||
.flat_map(|batch| batch["id"].as_primitive::<Int32Type>().values().to_vec())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ids, [20]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[rstest::rstest]
|
||||
#[case(LanceFileVersion::Legacy)]
|
||||
|
||||
@@ -876,6 +876,7 @@ impl ListingDatabase {
|
||||
&self,
|
||||
table_name: &str,
|
||||
namespace_path: Vec<String>,
|
||||
location: Option<String>,
|
||||
mode: CreateTableMode,
|
||||
data_schema: &arrow_schema::Schema,
|
||||
) -> Result<Arc<dyn BaseTable>> {
|
||||
@@ -889,7 +890,7 @@ impl ListingDatabase {
|
||||
namespace_path: namespace_path.clone(),
|
||||
index_cache_size: None,
|
||||
lance_read_params: None,
|
||||
location: None,
|
||||
location,
|
||||
namespace_client: None,
|
||||
managed_versioning: None,
|
||||
};
|
||||
@@ -897,8 +898,13 @@ impl ListingDatabase {
|
||||
let table = self.open_table(req).await?;
|
||||
|
||||
let table_schema = table.schema().await?;
|
||||
// Lance doesn't store every Arrow detail (such as the name and nullability of a
|
||||
// fixed-size list's child), so also accept a schema that it stores as this one.
|
||||
let matches = table_schema.as_ref() == data_schema
|
||||
|| lance::datatypes::Schema::try_from(data_schema)
|
||||
.is_ok_and(|schema| arrow_schema::Schema::from(&schema) == *table_schema);
|
||||
|
||||
if table_schema.as_ref() != data_schema {
|
||||
if !matches {
|
||||
return Err(Error::Schema {
|
||||
message: "Provided schema does not match existing table schema".to_string(),
|
||||
});
|
||||
@@ -1093,6 +1099,7 @@ impl Database for ListingDatabase {
|
||||
self.handle_table_exists(
|
||||
&request.name,
|
||||
request.namespace_path.clone(),
|
||||
request.location,
|
||||
request.mode,
|
||||
&data_schema,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user