mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix: preserve index names and isolate unsafe legacy listings
This commit is contained in:
@@ -355,8 +355,7 @@ Indices on scalar columns will speed up filtering (in both
|
|||||||
vector and non-vector searches)
|
vector and non-vector searches)
|
||||||
|
|
||||||
The index name defaults to `${column}_idx`. Set [IndexOptions.name](../interfaces/IndexOptions.md#name)
|
The index name defaults to `${column}_idx`. Set [IndexOptions.name](../interfaces/IndexOptions.md#name)
|
||||||
to use a custom name containing 1–128 ASCII letters, digits, dashes,
|
to use a custom name.
|
||||||
underscores, or periods, excluding `.` and `..`.
|
|
||||||
See [IndexOptions.name](../interfaces/IndexOptions.md#name) for legacy-name cleanup guidance.
|
See [IndexOptions.name](../interfaces/IndexOptions.md#name) for legacy-name cleanup guidance.
|
||||||
|
|
||||||
On LanceDB Embedded tables the index is built before the returned promise
|
On LanceDB Embedded tables the index is built before the returned promise
|
||||||
@@ -957,6 +956,9 @@ abstract listIndices(): Promise<IndexConfig[]>
|
|||||||
|
|
||||||
List all indices that have been created with [Table.createIndex](Table.md#createindex)
|
List all indices that have been created with [Table.createIndex](Table.md#createindex)
|
||||||
|
|
||||||
|
On older Enterprise servers, this method omits indices named `.`, `..` or
|
||||||
|
the empty string because their statistics cannot be requested safely.
|
||||||
|
|
||||||
On LanceDB Enterprise tables, an index whose build hasn't finished may be
|
On LanceDB Enterprise tables, an index whose build hasn't finished may be
|
||||||
missing (vector indices) or listed with 0 indexed rows (scalar and FTS
|
missing (vector indices) or listed with 0 indexed rows (scalar and FTS
|
||||||
indices), and `numUnindexedRows` may be undefined. Use
|
indices), and `numUnindexedRows` may be undefined. Use
|
||||||
|
|||||||
@@ -34,9 +34,6 @@ optional name: string;
|
|||||||
|
|
||||||
Optional custom name for the index.
|
Optional custom name for the index.
|
||||||
|
|
||||||
Custom names must contain 1–128 ASCII letters, digits, dashes, underscores,
|
|
||||||
or periods, excluding `.` and `..`.
|
|
||||||
|
|
||||||
If not provided, a default name will be generated based on the column name.
|
If not provided, a default name will be generated based on the column name.
|
||||||
Existing and generated names remain addressable through index operations,
|
Existing and generated names remain addressable through index operations,
|
||||||
except that remote tables reject empty names, `.` and `..` to prevent URL
|
except that remote tables reject empty names, `.` and `..` to prevent URL
|
||||||
|
|||||||
@@ -340,18 +340,15 @@ The `{column}_idx` suffix is the default naming convention.
|
|||||||
Pass `name=...` to `create_index()` to override it. Once set, the custom name will be reflected in `list_indices()`, `index_stats(name)`, and `wait_for_index([name])`.
|
Pass `name=...` to `create_index()` to override it. Once set, the custom name will be reflected in `list_indices()`, `index_stats(name)`, and `wait_for_index([name])`.
|
||||||
|
|
||||||
{/*
|
{/*
|
||||||
Draft for the index-name validation release (#5007). Publish this guidance
|
Draft for the Enterprise index-route safety fix (#5007). Publish this guidance
|
||||||
after the SDK changes ship.
|
after the SDK changes ship.
|
||||||
|
|
||||||
Custom index names must contain 1–128 ASCII letters, digits, dashes,
|
|
||||||
underscores, or periods, excluding `.` and `..`. These restrictions apply
|
|
||||||
when you supply a name to `create_index()`; generated names still use the
|
|
||||||
column name and remain usable through index operations.
|
|
||||||
|
|
||||||
Remote tables reject empty names, `.` and `..` in index operations to prevent
|
Remote tables reject empty names, `.` and `..` in index operations to prevent
|
||||||
URL path normalization. Existing indexes named `.` or `..` require
|
URL path normalization. Existing indexes named `.` or `..` require
|
||||||
server-side cleanup on managed tables, or a native connection with direct
|
server-side cleanup on managed tables, or a native connection with direct
|
||||||
access to the dataset. Other existing names remain usable.
|
access to the dataset. Other existing names remain usable. On older Enterprise
|
||||||
|
servers, index listings omit these unaddressable entries so they do not prevent
|
||||||
|
listing or waiting for other indices.
|
||||||
*/}
|
*/}
|
||||||
|
|
||||||
<CodeGroup>
|
<CodeGroup>
|
||||||
|
|||||||
@@ -949,9 +949,6 @@ export interface IndexOptions {
|
|||||||
/**
|
/**
|
||||||
* Optional custom name for the index.
|
* Optional custom name for the index.
|
||||||
*
|
*
|
||||||
* Custom names must contain 1–128 ASCII letters, digits, dashes, underscores,
|
|
||||||
* or periods, excluding `.` and `..`.
|
|
||||||
*
|
|
||||||
* If not provided, a default name will be generated based on the column name.
|
* If not provided, a default name will be generated based on the column name.
|
||||||
* Existing and generated names remain addressable through index operations,
|
* Existing and generated names remain addressable through index operations,
|
||||||
* except that remote tables reject empty names, `.` and `..` to prevent URL
|
* except that remote tables reject empty names, `.` and `..` to prevent URL
|
||||||
|
|||||||
@@ -471,8 +471,7 @@ export abstract class Table {
|
|||||||
* vector and non-vector searches)
|
* vector and non-vector searches)
|
||||||
*
|
*
|
||||||
* The index name defaults to `${column}_idx`. Set {@link IndexOptions.name}
|
* The index name defaults to `${column}_idx`. Set {@link IndexOptions.name}
|
||||||
* to use a custom name containing 1–128 ASCII letters, digits, dashes,
|
* to use a custom name.
|
||||||
* underscores, or periods, excluding `.` and `..`.
|
|
||||||
* See {@link IndexOptions.name} for legacy-name cleanup guidance.
|
* See {@link IndexOptions.name} for legacy-name cleanup guidance.
|
||||||
*
|
*
|
||||||
* On LanceDB Embedded tables the index is built before the returned promise
|
* On LanceDB Embedded tables the index is built before the returned promise
|
||||||
@@ -1236,6 +1235,9 @@ export abstract class Table {
|
|||||||
/**
|
/**
|
||||||
* List all indices that have been created with {@link Table.createIndex}
|
* List all indices that have been created with {@link Table.createIndex}
|
||||||
*
|
*
|
||||||
|
* On older Enterprise servers, this method omits indices named `.`, `..` or
|
||||||
|
* the empty string because their statistics cannot be requested safely.
|
||||||
|
*
|
||||||
* On LanceDB Enterprise tables, an index whose build hasn't finished may be
|
* On LanceDB Enterprise tables, an index whose build hasn't finished may be
|
||||||
* missing (vector indices) or listed with 0 indexed rows (scalar and FTS
|
* missing (vector indices) or listed with 0 indexed rows (scalar and FTS
|
||||||
* indices), and `numUnindexedRows` may be undefined. Use
|
* indices), and `numUnindexedRows` may be undefined. Use
|
||||||
|
|||||||
@@ -1953,9 +1953,7 @@ class Table(ABC):
|
|||||||
LanceDB Enterprise only: how long to wait for the index build to finish.
|
LanceDB Enterprise only: how long to wait for the index build to finish.
|
||||||
If not set, the call returns once the build is scheduled.
|
If not set, the call returns once the build is scheduled.
|
||||||
name : str, optional
|
name : str, optional
|
||||||
Custom name for the index: 1–128 ASCII letters, digits, dashes,
|
Custom name for the index.
|
||||||
underscores, or periods, excluding ``.`` and ``..``. If omitted,
|
|
||||||
a default name is generated from the column name.
|
|
||||||
train : bool, default True
|
train : bool, default True
|
||||||
Whether to train the index with existing data.
|
Whether to train the index with existing data.
|
||||||
|
|
||||||
@@ -2121,8 +2119,6 @@ class Table(ABC):
|
|||||||
The timeout to wait if indexing is asynchronous.
|
The timeout to wait if indexing is asynchronous.
|
||||||
name: str, optional
|
name: str, optional
|
||||||
The name of the index. If not provided, a default name will be generated.
|
The name of the index. If not provided, a default name will be generated.
|
||||||
Custom names must contain 1–128 ASCII letters, digits, dashes,
|
|
||||||
underscores, or periods, excluding ``.`` and ``..``.
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
|
|
||||||
@@ -2282,8 +2278,6 @@ class Table(ABC):
|
|||||||
The timeout to wait if indexing is asynchronous.
|
The timeout to wait if indexing is asynchronous.
|
||||||
name: str, optional
|
name: str, optional
|
||||||
The name of the index. If not provided, a default name will be generated.
|
The name of the index. If not provided, a default name will be generated.
|
||||||
Custom names must contain 1–128 ASCII letters, digits, dashes,
|
|
||||||
underscores, or periods, excluding ``.`` and ``..``.
|
|
||||||
|
|
||||||
Notes
|
Notes
|
||||||
-----
|
-----
|
||||||
@@ -3096,6 +3090,10 @@ class Table(ABC):
|
|||||||
List all indices that have been created with
|
List all indices that have been created with
|
||||||
[Table.create_index][lancedb.table.Table.create_index]
|
[Table.create_index][lancedb.table.Table.create_index]
|
||||||
|
|
||||||
|
On older Enterprise servers, this method omits indices named ``.``,
|
||||||
|
``..`` or the empty string because their statistics cannot be requested
|
||||||
|
safely.
|
||||||
|
|
||||||
On LanceDB Enterprise tables, an index whose build hasn't finished may
|
On LanceDB Enterprise tables, an index whose build hasn't finished may
|
||||||
be missing (vector indices) or listed with 0 indexed rows (scalar and
|
be missing (vector indices) or listed with 0 indexed rows (scalar and
|
||||||
FTS indices), and ``num_unindexed_rows`` may be ``None``. Use
|
FTS indices), and ``num_unindexed_rows`` may be ``None``. Use
|
||||||
@@ -4456,9 +4454,7 @@ class LanceTable(Table):
|
|||||||
wait_timeout : timedelta, optional
|
wait_timeout : timedelta, optional
|
||||||
Timeout to wait for async indexing to complete.
|
Timeout to wait for async indexing to complete.
|
||||||
name : str, optional
|
name : str, optional
|
||||||
Custom name for the index: 1–128 ASCII letters, digits, dashes,
|
Custom name for the index.
|
||||||
underscores, or periods, excluding ``.`` and ``..``. If omitted,
|
|
||||||
a default name is generated from the column name.
|
|
||||||
train : bool, default True
|
train : bool, default True
|
||||||
Whether to train the index with existing data.
|
Whether to train the index with existing data.
|
||||||
|
|
||||||
@@ -6906,8 +6902,6 @@ class AsyncTable:
|
|||||||
If not set, the call returns once the build is scheduled.
|
If not set, the call returns once the build is scheduled.
|
||||||
name: str, optional
|
name: str, optional
|
||||||
The name of the index. If not provided, a default name will be generated.
|
The name of the index. If not provided, a default name will be generated.
|
||||||
Custom names must contain 1–128 ASCII letters, digits, dashes,
|
|
||||||
underscores, or periods, excluding ``.`` and ``..``.
|
|
||||||
exist_ok: bool, default False
|
exist_ok: bool, default False
|
||||||
Preserve an existing index with the requested or derived name. This
|
Preserve an existing index with the requested or derived name. This
|
||||||
takes precedence over replace and keeps its definition and build.
|
takes precedence over replace and keeps its definition and build.
|
||||||
@@ -8926,6 +8920,10 @@ class AsyncTable:
|
|||||||
"""
|
"""
|
||||||
List all indices that have been created with Self::create_index
|
List all indices that have been created with Self::create_index
|
||||||
|
|
||||||
|
On older Enterprise servers, this method omits indices named ``.``,
|
||||||
|
``..`` or the empty string because their statistics cannot be requested
|
||||||
|
safely.
|
||||||
|
|
||||||
On LanceDB Enterprise tables, an index whose build hasn't finished may
|
On LanceDB Enterprise tables, an index whose build hasn't finished may
|
||||||
be missing (vector indices) or listed with 0 indexed rows (scalar and
|
be missing (vector indices) or listed with 0 indexed rows (scalar and
|
||||||
FTS indices), and ``num_unindexed_rows`` may be ``None``. Use
|
FTS indices), and ``num_unindexed_rows`` may be ``None``. Use
|
||||||
|
|||||||
@@ -663,3 +663,27 @@ async def test_named_index_exist_ok_checks_before_column_validation(
|
|||||||
await result.wait()
|
await result.wait()
|
||||||
assert await some_table.version() == version
|
assert await some_table.version() == version
|
||||||
assert [index.name for index in await some_table.list_indices()] == ["kept"]
|
assert [index.name for index in await some_table.list_indices()] == ["kept"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize("name", ["Customer lookup", "café_idx"])
|
||||||
|
@pytest.mark.parametrize("background", [False, True])
|
||||||
|
async def test_custom_index_names_preserve_exist_ok(some_table, name, background):
|
||||||
|
method = some_table.create_index_async if background else some_table.create_index
|
||||||
|
job = await method("id", config=BTree(), name=name, exist_ok=True)
|
||||||
|
if background:
|
||||||
|
await job.wait()
|
||||||
|
version = await some_table.version()
|
||||||
|
original = await some_table.list_indices()
|
||||||
|
# A second call keeps the existing definition and version.
|
||||||
|
job = await method("id", config=Bitmap(), name=name, exist_ok=True)
|
||||||
|
if background:
|
||||||
|
await job.wait()
|
||||||
|
assert await some_table.version() == version
|
||||||
|
indices = await some_table.list_indices()
|
||||||
|
assert len(indices) == 1
|
||||||
|
assert indices[0].name == name
|
||||||
|
assert indices[0].index_type == original[0].index_type == "BTree"
|
||||||
|
assert (await some_table.index_stats(name)).num_indexed_rows == NROWS
|
||||||
|
await some_table.drop_index(name)
|
||||||
|
assert await some_table.list_indices() == []
|
||||||
|
|||||||
@@ -252,10 +252,6 @@ impl IndexBuilder {
|
|||||||
|
|
||||||
/// The name of the index. If not set, a default name will be generated.
|
/// The name of the index. If not set, a default name will be generated.
|
||||||
///
|
///
|
||||||
/// Custom names must contain 1 to 128 ASCII alphanumeric characters,
|
|
||||||
/// dashes, underscores, or periods, and cannot be `.` or `..`.
|
|
||||||
/// Invalid names are rejected when executing the builder.
|
|
||||||
///
|
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ use crate::utils::background_cache::BackgroundCache;
|
|||||||
use crate::utils::{
|
use crate::utils::{
|
||||||
MaxBatchLengthStream, TimeoutStream, public_fts_field_path_by_id, resolve_arrow_field_path,
|
MaxBatchLengthStream, TimeoutStream, public_fts_field_path_by_id, resolve_arrow_field_path,
|
||||||
resolve_arrow_fts_field_path, supported_btree_data_type, supported_vector_data_type,
|
resolve_arrow_fts_field_path, supported_btree_data_type, supported_vector_data_type,
|
||||||
validate_fts_field, validate_index_name,
|
validate_fts_field,
|
||||||
};
|
};
|
||||||
use crate::{DistanceType, Error};
|
use crate::{DistanceType, Error};
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -99,7 +99,7 @@ const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-m
|
|||||||
const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version");
|
const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version");
|
||||||
const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot";
|
const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot";
|
||||||
|
|
||||||
/// Encode an existing or server-generated name without applying custom creation rules.
|
/// Encode an index name as one safe path segment.
|
||||||
fn encode_index_name(name: &str) -> Result<Cow<'_, str>> {
|
fn encode_index_name(name: &str) -> Result<Cow<'_, str>> {
|
||||||
// Percent-encoding preserves dot segments, which URL parsing would normalize
|
// Percent-encoding preserves dot segments, which URL parsing would normalize
|
||||||
// into another route. All other name characters are safe after encoding.
|
// into another route. All other name characters are safe after encoding.
|
||||||
@@ -713,9 +713,6 @@ impl<S: HttpSend> RemoteTable<S> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn submit_create_index(&self, mut index: IndexBuilder) -> Result<Option<String>> {
|
async fn submit_create_index(&self, mut index: IndexBuilder) -> Result<Option<String>> {
|
||||||
if let Some(name) = &index.name {
|
|
||||||
validate_index_name(name)?;
|
|
||||||
}
|
|
||||||
self.check_mutable().await?;
|
self.check_mutable().await?;
|
||||||
let mut request = self
|
let mut request = self
|
||||||
.client
|
.client
|
||||||
@@ -2488,7 +2485,8 @@ impl<S: HttpSend + 'static> RemoteTable<S> {
|
|||||||
/// When the server returns `index_type` inline, all enriched fields are
|
/// When the server returns `index_type` inline, all enriched fields are
|
||||||
/// used directly and no further requests are made. When `index_type` is
|
/// used directly and no further requests are made. When `index_type` is
|
||||||
/// absent (legacy servers), a `/index/{name}/stats/` call is made for each
|
/// absent (legacy servers), a `/index/{name}/stats/` call is made for each
|
||||||
/// index to retrieve the type.
|
/// addressable index to retrieve the type. Unsafe legacy names are omitted
|
||||||
|
/// because their type cannot be retrieved without changing the URL route.
|
||||||
async fn parse_index_list_response(
|
async fn parse_index_list_response(
|
||||||
&self,
|
&self,
|
||||||
body: &str,
|
body: &str,
|
||||||
@@ -2535,6 +2533,11 @@ impl<S: HttpSend + 'static> RemoteTable<S> {
|
|||||||
|
|
||||||
let mut futures = Vec::with_capacity(response.indexes.len());
|
let mut futures = Vec::with_capacity(response.indexes.len());
|
||||||
for entry in response.indexes {
|
for entry in response.indexes {
|
||||||
|
if entry.index_type.is_none() && encode_index_name(&entry.index_name).is_err() {
|
||||||
|
// Legacy entries need a stats request to determine their type.
|
||||||
|
// Skip unaddressable names without failing the entire listing.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let columns = entry
|
let columns = entry
|
||||||
.columns
|
.columns
|
||||||
.iter()
|
.iter()
|
||||||
@@ -13168,6 +13171,15 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let generated_name = native.list_indices().await.unwrap()[0].name.clone();
|
let generated_name = native.list_indices().await.unwrap()[0].name.clone();
|
||||||
assert_eq!(generated_name, "café_idx");
|
assert_eq!(generated_name, "café_idx");
|
||||||
|
let version = native.version().await.unwrap();
|
||||||
|
native
|
||||||
|
.create_index(&["café"], Index::Auto)
|
||||||
|
.name(generated_name.clone())
|
||||||
|
.exist_ok(true)
|
||||||
|
.execute()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(native.version().await.unwrap(), version);
|
||||||
|
|
||||||
for enriched in [true, false] {
|
for enriched in [true, false] {
|
||||||
let schema = schema.clone();
|
let schema = schema.clone();
|
||||||
@@ -13237,76 +13249,126 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[rstest]
|
#[rstest]
|
||||||
#[case(false)]
|
#[case("..", false)]
|
||||||
#[case(true)]
|
#[case(".", false)]
|
||||||
|
#[case("", false)]
|
||||||
|
#[case("..", true)]
|
||||||
|
#[case(".", true)]
|
||||||
|
#[case("", true)]
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_invalid_custom_index_names_never_send_requests(#[case] exist_ok: bool) {
|
async fn test_list_indices_with_legacy_index_name(
|
||||||
let table = Table::new_with_handler("my_table", |request| -> http::Response<String> {
|
#[case] legacy_name: &'static str,
|
||||||
panic!("Invalid index name sent a request to {}", request.url());
|
#[case] enriched: bool,
|
||||||
});
|
) {
|
||||||
|
let table = Table::new_with_handler("my_table", move |request| {
|
||||||
for name in [
|
let body = match request.url().path() {
|
||||||
"..",
|
"/v1/table/my_table/describe/" => {
|
||||||
".",
|
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
|
||||||
"",
|
describe_response(&schema)
|
||||||
"my/index",
|
}
|
||||||
"my\\index",
|
"/v1/table/my_table/index/list/" => {
|
||||||
"%2e%2e",
|
let mut entries = vec![
|
||||||
"my/index?a#b c",
|
json!({"index_name": legacy_name, "columns": ["a"]}),
|
||||||
"café_idx",
|
json!({"index_name": "Customer lookup", "columns": ["a"]}),
|
||||||
] {
|
json!({"index_name": "café_idx", "columns": ["a"]}),
|
||||||
for result in [
|
];
|
||||||
table
|
if enriched {
|
||||||
.create_index(&["a"], Index::BTree(Default::default()))
|
for entry in &mut entries {
|
||||||
.name(name.to_string())
|
|
||||||
.exist_ok(exist_ok)
|
|
||||||
.execute()
|
|
||||||
.await,
|
|
||||||
table
|
|
||||||
.create_index(&["a"], Index::BTree(Default::default()))
|
|
||||||
.name(name.to_string())
|
|
||||||
.exist_ok(exist_ok)
|
|
||||||
.execute_async()
|
|
||||||
.await
|
|
||||||
.map(|_| ()),
|
|
||||||
] {
|
|
||||||
assert!(
|
|
||||||
matches!(result, Err(Error::InvalidInput { .. })),
|
|
||||||
"Expected invalid input for {name:?}, got {result:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_list_indices_with_legacy_index_name() {
|
|
||||||
for enriched in [false, true] {
|
|
||||||
let table = Table::new_with_handler("my_table", move |request| {
|
|
||||||
let body = match request.url().path() {
|
|
||||||
"/v1/table/my_table/describe/" => {
|
|
||||||
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
|
|
||||||
describe_response(&schema)
|
|
||||||
}
|
|
||||||
"/v1/table/my_table/index/list/" => {
|
|
||||||
let mut entry = json!({"index_name": "..", "columns": ["a"]});
|
|
||||||
if enriched {
|
|
||||||
entry["index_type"] = json!("BTREE");
|
entry["index_type"] = json!("BTREE");
|
||||||
}
|
}
|
||||||
json!({"indexes": [entry]}).to_string()
|
|
||||||
}
|
}
|
||||||
path => panic!("Legacy index name caused an unexpected request to {path}"),
|
json!({"indexes": entries}).to_string()
|
||||||
};
|
}
|
||||||
http::Response::builder().status(200).body(body).unwrap()
|
"/v1/table/my_table/index/Customer%20lookup/stats/"
|
||||||
});
|
| "/v1/table/my_table/index/caf%C3%A9_idx/stats/" => json!({
|
||||||
let result = table.list_indices().await;
|
"num_indexed_rows": 1,
|
||||||
if enriched {
|
"num_unindexed_rows": 0,
|
||||||
// Names from the server remain discoverable when no per-index
|
"index_type": "BTREE"
|
||||||
// stats request is needed.
|
})
|
||||||
assert_eq!(result.unwrap()[0].name, "..");
|
.to_string(),
|
||||||
|
path => panic!("Legacy index name caused an unexpected request to {path}"),
|
||||||
|
};
|
||||||
|
http::Response::builder().status(200).body(body).unwrap()
|
||||||
|
});
|
||||||
|
let indices = table.list_indices().await.unwrap();
|
||||||
|
let expected = if enriched {
|
||||||
|
vec![legacy_name, "Customer lookup", "café_idx"]
|
||||||
|
} else {
|
||||||
|
vec!["Customer lookup", "café_idx"]
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
indices
|
||||||
|
.iter()
|
||||||
|
.map(|index| index.name.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
table
|
||||||
|
.wait_for_index(&["Customer lookup", "café_idx"], Duration::from_secs(1))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[case("Customer lookup", "Customer%20lookup", false)]
|
||||||
|
#[case("Customer lookup", "Customer%20lookup", true)]
|
||||||
|
#[case("café_idx", "caf%C3%A9_idx", false)] // spellchecker:disable-line
|
||||||
|
#[case("café_idx", "caf%C3%A9_idx", true)] // spellchecker:disable-line
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_custom_index_names_remote_lifecycle(
|
||||||
|
#[case] name: &'static str,
|
||||||
|
#[case] encoded_name: &str,
|
||||||
|
#[case] background: bool,
|
||||||
|
) {
|
||||||
|
let prefix = format!("/v1/table/my_table/index/{encoded_name}");
|
||||||
|
let table = Table::new_with_handler("my_table", move |request| {
|
||||||
|
let body = match request.url().path() {
|
||||||
|
"/v1/table/my_table/describe/" => {
|
||||||
|
describe_response(&Schema::new(vec![Field::new("a", DataType::Int32, false)]))
|
||||||
|
}
|
||||||
|
"/v1/table/my_table/create_index/" => {
|
||||||
|
let body = request_body_json(&request);
|
||||||
|
assert_eq!(body["name"], name);
|
||||||
|
assert_eq!(body["replace"], false);
|
||||||
|
assert_eq!(request.url().query(), Some("exist_ok=true"));
|
||||||
|
"{}".to_string()
|
||||||
|
}
|
||||||
|
"/v1/table/my_table/index/list/" => json!({"indexes": [{
|
||||||
|
"index_name": name, "columns": ["a"], "index_type": "BTREE"
|
||||||
|
}]})
|
||||||
|
.to_string(),
|
||||||
|
path if path == format!("{prefix}/stats/") => json!({
|
||||||
|
"num_indexed_rows": 1, "num_unindexed_rows": 0, "index_type": "BTREE"
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
path if path == format!("{prefix}/drop/")
|
||||||
|
|| path == format!("{prefix}/prewarm/") =>
|
||||||
|
{
|
||||||
|
"{}".to_string()
|
||||||
|
}
|
||||||
|
path => panic!("Unexpected index route: {path}"),
|
||||||
|
};
|
||||||
|
http::Response::builder().status(200).body(body).unwrap()
|
||||||
|
});
|
||||||
|
for _ in 0..2 {
|
||||||
|
let builder = table
|
||||||
|
.create_index(&["a"], Index::Auto)
|
||||||
|
.name(name.to_string())
|
||||||
|
.exist_ok(true);
|
||||||
|
if background {
|
||||||
|
builder.execute_async().await.unwrap().wait().await.unwrap();
|
||||||
} else {
|
} else {
|
||||||
assert!(matches!(result, Err(Error::InvalidInput { .. })));
|
builder.execute().await.unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
assert_eq!(table.list_indices().await.unwrap()[0].name, name);
|
||||||
|
assert!(table.index_stats(name).await.unwrap().is_some());
|
||||||
|
table.prewarm_index(name).await.unwrap();
|
||||||
|
table
|
||||||
|
.wait_for_index(&[name], Duration::from_secs(1))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
table.drop_index(name).await.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rstest]
|
#[rstest]
|
||||||
|
|||||||
@@ -2753,7 +2753,11 @@ impl Table {
|
|||||||
self.inner.list_versions().await
|
self.inner.list_versions().await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// List all indices that have been created with [`Self::create_index`]
|
/// List all indices that have been created with [`Self::create_index`].
|
||||||
|
///
|
||||||
|
/// On older remote servers, indices named `.`, `..` or the empty string are
|
||||||
|
/// omitted because their statistics cannot be requested safely. Enriched
|
||||||
|
/// listings include these entries without requesting their statistics.
|
||||||
pub async fn list_indices(&self) -> Result<Vec<IndexConfig>> {
|
pub async fn list_indices(&self) -> Result<Vec<IndexConfig>> {
|
||||||
self.inner.list_indices().await
|
self.inner.list_indices().await
|
||||||
}
|
}
|
||||||
@@ -2938,8 +2942,7 @@ impl Table {
|
|||||||
/// Legacy indices named `.` or `..` can still be dropped through a native
|
/// Legacy indices named `.` or `..` can still be dropped through a native
|
||||||
/// connection with direct access to the dataset. On managed remote tables,
|
/// connection with direct access to the dataset. On managed remote tables,
|
||||||
/// these indices require server-side cleanup. Other existing and generated
|
/// these indices require server-side cleanup. Other existing and generated
|
||||||
/// names remain addressable, even when they do not meet the custom-name
|
/// names remain addressable.
|
||||||
/// rules in [`IndexBuilder::name`].
|
|
||||||
///
|
///
|
||||||
/// This does not delete the index from disk, it just removes it from the table.
|
/// This does not delete the index from disk, it just removes it from the table.
|
||||||
/// To delete the index, run [`Self::optimize()`] after dropping the index.
|
/// To delete the index, run [`Self::optimize()`] after dropping the index.
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ use crate::index::vector::{VectorIndex, suggested_num_sub_vectors};
|
|||||||
use crate::utils::{
|
use crate::utils::{
|
||||||
resolve_lance_fts_field_path, supported_bitmap_data_type, supported_btree_data_type,
|
resolve_lance_fts_field_path, supported_bitmap_data_type, supported_btree_data_type,
|
||||||
supported_fm_data_type, supported_label_list_data_type, supported_vector_data_type,
|
supported_fm_data_type, supported_label_list_data_type, supported_vector_data_type,
|
||||||
supported_zonemap_data_type, validate_fts_field, validate_index_name,
|
supported_zonemap_data_type, validate_fts_field,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::NativeTable;
|
use super::NativeTable;
|
||||||
@@ -116,9 +116,6 @@ impl NativeTable {
|
|||||||
&self,
|
&self,
|
||||||
opts: &crate::index::IndexBuilder,
|
opts: &crate::index::IndexBuilder,
|
||||||
) -> Result<Option<PreparedIndex>> {
|
) -> Result<Option<PreparedIndex>> {
|
||||||
if let Some(name) = &opts.name {
|
|
||||||
validate_index_name(name)?;
|
|
||||||
}
|
|
||||||
self.dataset.ensure_mutable()?;
|
self.dataset.ensure_mutable()?;
|
||||||
let dataset = self.dataset.get().await?;
|
let dataset = self.dataset.get().await?;
|
||||||
if opts.exist_ok
|
if opts.exist_ok
|
||||||
@@ -1432,10 +1429,15 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[rstest::rstest]
|
#[rstest::rstest]
|
||||||
#[case(false)]
|
#[case("Customer lookup", false)]
|
||||||
#[case(true)]
|
#[case("Customer lookup", true)]
|
||||||
|
#[case("café_idx", false)]
|
||||||
|
#[case("café_idx", true)]
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_create_index_rejects_invalid_index_names(#[case] exist_ok: bool) {
|
async fn test_custom_index_names_preserve_exist_ok(
|
||||||
|
#[case] name: &str,
|
||||||
|
#[case] background: bool,
|
||||||
|
) {
|
||||||
let conn = connect("memory://").execute().await.unwrap();
|
let conn = connect("memory://").execute().await.unwrap();
|
||||||
let batch = record_batch!(("i", Int32, [1])).unwrap();
|
let batch = record_batch!(("i", Int32, [1])).unwrap();
|
||||||
let table = conn
|
let table = conn
|
||||||
@@ -1444,40 +1446,38 @@ mod tests {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
for name in ["..", ".", "", "my/index", "my\\index", "%2e%2e"] {
|
let builder = table
|
||||||
let result = table
|
.create_index(&["i"], Index::Auto)
|
||||||
.create_index(&["i"], Index::Auto)
|
.name(name.to_string())
|
||||||
.name(name.to_string())
|
.exist_ok(true);
|
||||||
.exist_ok(exist_ok)
|
if background {
|
||||||
.execute()
|
builder.execute_async().await.unwrap().wait().await.unwrap();
|
||||||
.await;
|
} else {
|
||||||
assert!(
|
builder.execute().await.unwrap();
|
||||||
matches!(result, Err(crate::Error::InvalidInput { .. })),
|
|
||||||
"Expected invalid input for {name:?}, got {result:?}"
|
|
||||||
);
|
|
||||||
let result = table
|
|
||||||
.create_index(&["i"], Index::Auto)
|
|
||||||
.name(name.to_string())
|
|
||||||
.exist_ok(exist_ok)
|
|
||||||
.execute_async()
|
|
||||||
.await;
|
|
||||||
assert!(
|
|
||||||
matches!(result, Err(crate::Error::InvalidInput { .. })),
|
|
||||||
"Expected invalid input for {name:?}, got {result:?}"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
let indices = table.list_indices().await.unwrap();
|
||||||
|
assert_eq!(indices.len(), 1);
|
||||||
|
assert_eq!(indices[0].name, name);
|
||||||
|
let version = table.version().await.unwrap();
|
||||||
|
let identity = indices[0].index_uuid.clone();
|
||||||
|
// A second call with a different definition must preserve the index.
|
||||||
|
let builder = table
|
||||||
|
.create_index(&["i"], Index::Bitmap(Default::default()))
|
||||||
|
.name(name.to_string())
|
||||||
|
.exist_ok(true);
|
||||||
|
if background {
|
||||||
|
builder.execute_async().await.unwrap().wait().await.unwrap();
|
||||||
|
} else {
|
||||||
|
builder.execute().await.unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(table.version().await.unwrap(), version);
|
||||||
|
let indices = table.list_indices().await.unwrap();
|
||||||
|
assert_eq!(indices[0].index_uuid, identity);
|
||||||
|
assert_eq!(indices[0].index_type, crate::index::IndexType::BTree);
|
||||||
|
assert!(table.index_stats(name).await.unwrap().is_some());
|
||||||
|
table.drop_index(name).await.unwrap();
|
||||||
assert!(table.list_indices().await.unwrap().is_empty());
|
assert!(table.list_indices().await.unwrap().is_empty());
|
||||||
|
assert_eq!(table.count_rows(None).await.unwrap(), 1);
|
||||||
for name in ["i_idx-1..v2", "..."] {
|
|
||||||
table
|
|
||||||
.create_index(&["i"], Index::Auto)
|
|
||||||
.name(name.to_string())
|
|
||||||
.execute()
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(table.list_indices().await.unwrap()[0].name, name);
|
|
||||||
table.drop_index(name).await.unwrap();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -23,9 +23,6 @@ use datafusion_physical_plan::SendableRecordBatchStream;
|
|||||||
/// object store.
|
/// object store.
|
||||||
const MAX_TABLE_NAME_CHARS: usize = 128;
|
const MAX_TABLE_NAME_CHARS: usize = 128;
|
||||||
|
|
||||||
/// The maximum length of a custom index name, which is also used in remote URLs.
|
|
||||||
const MAX_INDEX_NAME_CHARS: usize = 128;
|
|
||||||
|
|
||||||
/// The maximum length of a component of a namespace.
|
/// The maximum length of a component of a namespace.
|
||||||
const MAX_NAMESPACE_NAME_CHARS: usize = 64;
|
const MAX_NAMESPACE_NAME_CHARS: usize = 64;
|
||||||
|
|
||||||
@@ -139,11 +136,6 @@ pub fn validate_table_name(name: &str) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validate a custom index name before creation.
|
|
||||||
pub(crate) fn validate_index_name(name: &str) -> Result<()> {
|
|
||||||
validate_view_or_namespace_or_secret(name, "index name", MAX_INDEX_NAME_CHARS)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Validate that an input string contains alphanumerics, or dashes, underscores, and periods.
|
/// Validate that an input string contains alphanumerics, or dashes, underscores, and periods.
|
||||||
fn validate_view_or_namespace_or_secret(input: &str, kind: &str, max_len: usize) -> Result<()> {
|
fn validate_view_or_namespace_or_secret(input: &str, kind: &str, max_len: usize) -> Result<()> {
|
||||||
if input.is_empty() || input == "." || input == ".." {
|
if input.is_empty() || input == "." || input == ".." {
|
||||||
@@ -1100,37 +1092,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_validate_index_name() {
|
|
||||||
for name in [
|
|
||||||
"my_index",
|
|
||||||
"index-1.2",
|
|
||||||
"index..v2",
|
|
||||||
"...",
|
|
||||||
&"a".repeat(128),
|
|
||||||
] {
|
|
||||||
assert!(validate_index_name(name).is_ok(), "rejected {name:?}");
|
|
||||||
}
|
|
||||||
for name in [
|
|
||||||
"",
|
|
||||||
".",
|
|
||||||
"..",
|
|
||||||
"my/index",
|
|
||||||
"my\\index",
|
|
||||||
"%2e%2e",
|
|
||||||
"index?query",
|
|
||||||
"index#fragment",
|
|
||||||
"name with space",
|
|
||||||
"café",
|
|
||||||
&"a".repeat(129),
|
|
||||||
] {
|
|
||||||
assert!(
|
|
||||||
matches!(validate_index_name(name), Err(Error::InvalidInput { .. })),
|
|
||||||
"accepted {name:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_validate_namespace_component() {
|
fn test_validate_namespace_component() {
|
||||||
// Valid namespace names
|
// Valid namespace names
|
||||||
|
|||||||
Reference in New Issue
Block a user