From 1765747f916d6eb7f3fbbcc105591e5835ea3684 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 11:02:07 -0800 Subject: [PATCH 1/9] fix: allow updates to Function input columns (#4985) Updating an input column on a table with a Function binding currently fails before the write, although the write path already preserves freshness for bindings whose inputs are unchanged. Allow input updates through the normal update builder while retaining supported binding-metadata validation and the guard against writing computed or internal assignment outputs directly. Lance rewrites only the matched rows. Their affected Function outputs keep their previous values and their changed input signatures make them eligible for refresh; unchanged fragments retain their freshness. Rewrites affecting only unrelated inputs keep the existing freshness-preservation path. For a table whose Function reads `title`, this update now succeeds while retaining the previous computed values until refresh: ```python table.update(where="id = 7", values={"title": "revised"}) ``` Server consumers need this crate update before remote input updates gain the behavior. Adds regressions for a one-row input update, retained output values, freshness scope, independent binding preservation, and atomic rejection of mixed input/output writes. Local builds and tests are disabled by request; CI runs the regressions. --- rust/lancedb/src/table/computed_columns.rs | 54 ++++++++- rust/lancedb/src/table/freshness.rs | 122 +++++++++++++++++++++ rust/lancedb/src/table/update.rs | 33 +++--- 3 files changed, 192 insertions(+), 17 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index d09a790a3..64e90b246 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -1757,10 +1757,20 @@ pub(crate) fn ensure_not_written<'a>( schema: &ArrowSchema, written: impl IntoIterator, ) -> Result<()> { - let declared: Vec = computed_columns(schema) + ensure_supported_function_metadata(schema)?; + let mut declared: Vec = computed_columns(schema) .into_iter() .map(|declaration| declaration.name) .collect(); + declared.extend( + function_bindings(schema)? + .into_iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.clone()) + }), + ); for name in written { if declared.iter().any(|declared| *declared == root(name)) { return Err(Error::InvalidInput { @@ -2532,10 +2542,15 @@ pub(crate) mod test_support { )]) .await .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; + let schema = dataset.schema(); let outputs = bindings .iter() .flat_map(|binding| { + let inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); let assignment = binding.assignment().map(|assignment| { ( assignment.output_name.clone(), @@ -2547,9 +2562,9 @@ pub(crate) mod test_support { .iter() .map(|output| (output.output_name.clone(), output.output_ordinal)) .chain(assignment) - .map(|(name, ordinal)| { + .map(move |(name, ordinal)| { ( - dataset.schema().field(&name).unwrap().id as u32, + schema.field(&name).unwrap().id as u32, function_computed_column_metadata( binding.binding_id(), ordinal, @@ -4144,6 +4159,37 @@ mod tests { ArrowSchema::new(fields) } + #[test] + fn input_writes_preserve_the_assignment_column_guard() { + let mut raw: Value = serde_json::to_value(test_support::text_features_binding("")).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": "__function_assignment_fb_01K3TEXT", "output_field_id": -1, + }); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["outputs"][1]["nullable"] = Value::Bool(true); + raw["output_schema"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "__function_assignment_fb_01K3TEXT", "nullable": true, "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let schema = ArrowSchema::new_with_metadata( + valid_function_binding_schema(true, true, &binding) + .fields() + .to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.into(), + function_bindings_metadata(&[binding]).unwrap(), + )]), + ); + ensure_not_written(&schema, ["title", "body"]).unwrap(); + for output in [ + "search_text", + "search_token_count", + "__function_assignment_fb_01K3TEXT", + ] { + assert!(ensure_not_written(&schema, [output]).is_err(), "{output}"); + } + } + #[test] fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { let binding = FunctionBinding::from_json(include_str!( diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 645653a46..563a2a4e5 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -2646,6 +2646,8 @@ mod tests { use lance_file::version::ConcreteFileVersion; use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; @@ -3126,6 +3128,126 @@ mod tests { } } + #[tokio::test] + async fn input_update_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let result = table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + assert_eq!(result.rows_updated, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_update_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 55980c5ff..93e8a08ea 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -103,11 +103,6 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; crate::materialized_view::ensure_not_a_view(&table.name, &dataset.schema().metadata, "update")?; - super::computed_columns::ensure_not_function_bound( - &arrow_schema::Schema::from(dataset.schema()), - "update", - update.columns.iter().map(|(name, _)| name.as_str()), - )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), update.columns.iter().map(|(name, _)| name.as_str()), @@ -473,26 +468,38 @@ mod tests { assert_eq!(0, tbl.count_rows(Some("i == 0".to_string())).await.unwrap()); } - /// A Function binding protects only the columns it reads or writes; any - /// other column updates as on a plain table. #[tokio::test] - async fn update_on_a_function_table_refuses_only_bound_columns() { + async fn update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table().await; - let result = table.update().column("spare", "7").execute().await.unwrap(); + let result = table + .update() + .column("title", "'changed'") + .execute() + .await + .unwrap(); assert_eq!(result.rows_updated, 1); - for column in ["title", "search_text"] { + assert_eq!( + table + .count_rows(Some("title = 'changed' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 + ); + for column in ["search_text", "search_token_count"] { + let version = table.version().await.unwrap(); let err = table .update() - .column(column, "'x'") + .column("title", "'must not commit'") + .column(column, "NULL") .execute() .await .unwrap_err(); assert!( matches!(&err, crate::Error::InvalidInput { message } - if message.contains(&format!("update of '{column}'")) - && message.contains("a Function binding reads or writes it")), + if message.contains("is computed") && message.contains("cannot be written directly")), "{column}: {err:?}" ); + assert_eq!(table.version().await.unwrap(), version); } } } From 3a980054a19dc51f53979a04142468f57478d156 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:24:55 -0800 Subject: [PATCH 2/9] docs: standardize Realtime Engine naming (#4969) The Enterprise feature name was inconsistently written as "Real Time Engine" and "real time engine". Standardize it to **Realtime Engine** in eight website guides, including page and sidebar titles, descriptions, prose, link labels, cards, and search keywords. The remaining MemWAL references describe Lance's open source format or literal API/job identifiers, including `memwal_compaction` and `memwal_catchup_`, and are preserved. Only `docs/web/*.mdx` pages change; SDK source, generated API reference, code examples, URL destinations, and section anchors are unchanged. Validation: - `git diff --check` passes. - Reviewed all MemWAL and Realtime Engine references under `docs/`. - Verified each changed file differs only by the intended naming substitutions and preserves code blocks, inline code, links, anchors, and MemWAL identifiers. - Confirmed no split or hyphenated "real time engine" names remain in website guides. - No snippets needed regeneration because code examples are unchanged. Vale and Mintlify are not installed locally, so their checks were not run locally. --- docs/web/basics/sdk.mdx | 2 +- docs/web/enterprise/distributed-real-time-read.mdx | 2 +- docs/web/enterprise/distributed-real-time-write.mdx | 4 ++-- docs/web/enterprise/realtime-engine-compaction.mdx | 12 ++++++------ docs/web/ingestion/realtime-write.mdx | 8 ++++---- docs/web/search/realtime-read.mdx | 8 ++++---- docs/web/sql/ddl/table.mdx | 2 +- docs/web/tables/realtime-engine.mdx | 10 +++++----- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index 2ff1a4ba7..0274c039a 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -53,7 +53,7 @@ without a LanceDB SDK. For SQL queries, connect through LanceDB's Java client builds on this Lance Namespace Java core: table creation, listing and most other catalog operations go through the generated `LanceNamespace` interface talking to Enterprise's Namespace endpoint. -The [real time engine](/tables/realtime-engine) is the one area with its own, +The [Realtime Engine](/tables/realtime-engine) is the one area with its own, LanceDB-specific Java client on top, since RTE's LSM write path is not part of the Lance Namespace Client SDK Specification. diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx index 1b6a582c4..7442474ec 100644 --- a/docs/web/enterprise/distributed-real-time-read.mdx +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -1,7 +1,7 @@ --- title: "Distributed RTE Read" sidebarTitle: "Distributed RTE Read" -description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine." +description: "How a query combines the Realtime Engine's fresh tier with the ordinary distributed query-serving path, machine to machine." icon: "network-wired" availability: embedded: unavailable diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index ac91e2d0d..e75497360 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -3,7 +3,7 @@ title: "Distributed RTE Write" sidebarTitle: "Distributed RTE Write" description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it." icon: "bolt" -keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"] +keywords: ["rte", "realtime engine", "shard", "sharding", "horizontal scaling", "write throughput"] availability: embedded: unavailable enterprise: available @@ -128,7 +128,7 @@ throughput than this provides. Enable RTE and write to a table; the same call on Embedded or Enterprise. - + MemWAL, shards, memtables and SSTables -- the shared architecture. diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx index e04429ab8..fb1a68481 100644 --- a/docs/web/enterprise/realtime-engine-compaction.mdx +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -1,7 +1,7 @@ --- -title: "Real Time Engine compaction" +title: "Realtime Engine compaction" sidebarTitle: "RTE Compaction" -description: "How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up." +description: "How Enterprise automatically folds a Realtime Engine shard's SSTables into the base table and catches its indexes up." icon: "compress" availability: embedded: unavailable @@ -11,7 +11,7 @@ availability: [Distributed Compaction](/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/maintenance/compaction) describes for LanceDB Embedded. A -table with the [real time engine](/tables/realtime-engine) enabled has a +table with the [Realtime Engine](/tables/realtime-engine) enabled has a second, unrelated compaction: folding a shard's accumulated SSTables into the base table and catching the base table's indexes up over the rows that just landed. This produces two job types, `memwal_compaction` and @@ -176,9 +176,9 @@ manifest update in step 6 is the single point where a row's SSTable copy stops being listed, and it only commits after `merge_insert` has already written that row into the base table. -A table queried *without* the real time engine's live path only sees data +A table queried *without* the Realtime Engine's live path only sees data once it has been folded into the base table, so its staleness bound tracks -whichever trigger fires -- wider either way than the real time engine's +whichever trigger fires -- wider either way than the Realtime Engine's own millisecond-scale freshness. A shard under steady write pressure compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` plus the compaction job's own runtime. A shard that never gathers enough @@ -197,7 +197,7 @@ for what a live RTE read sees instead. ## What to read next {#next} - + The MemWAL format, shards, and WAL nodes this page assumes. diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index 5b61e67bc..21b6eb2fa 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,15 +1,15 @@ --- title: "RTE Write (Upsert)" sidebarTitle: "RTE Write (Upsert)" -description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." +description: "Enable the Realtime Engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] availability: embedded: available enterprise: available --- -The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in +The [Realtime Engine](/tables/realtime-engine) puts an LSM-style write tier in front of a table, turning many small writes into a few large commits. This page covers enabling it and writing to a table; for querying an RTE table, see [RTE reads](/search/realtime-read). @@ -239,6 +239,6 @@ for the numbers. - [RTE reads](/search/realtime-read) — query an RTE table - [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Merge insert](/ingestion/merge-insert) - [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index 19c5bc2ab..d87d98c81 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -1,15 +1,15 @@ --- title: "RTE reads" sidebarTitle: "RTE Read" -description: "Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." +description: "Query a table with the Realtime Engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." icon: "magnifying-glass" -keywords: ["rte", "real time engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] +keywords: ["rte", "realtime engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] availability: embedded: available enterprise: available --- -A table with the [real time engine](/tables/realtime-engine) enabled queries +A table with the [Realtime Engine](/tables/realtime-engine) enabled queries the same way as any other table — nothing about `search`, filtering, or SQL changes. This page covers what you get back; for enabling RTE and writing to a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise @@ -79,6 +79,6 @@ available. - [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table - [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Hybrid search](/search/hybrid-search) - [Vector search](/search/vector-search) diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 6e751667e..ab0ff64bf 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -176,7 +176,7 @@ ALTER TABLE t UNSET RTE ``` -The [real time engine](/tables/realtime-engine) puts a write-ahead log in front +The [Realtime Engine](/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index 5c6983cc5..09e933894 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,21 +1,21 @@ --- -title: "Real Time engine (RTE)" -sidebarTitle: "Real Time Engine (RTE)" +title: "Realtime Engine (RTE)" +sidebarTitle: "Realtime Engine (RTE)" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] +keywords: ["rte", "realtime engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] availability: embedded: available enterprise: available --- -## What is the real time engine? {#what-is-rte} +## What is the Realtime Engine? {#what-is-rte} Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. -The real time engine (RTE) puts an LSM-style write tier in front of the table. +The Realtime Engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. From 7d50d2d28f84559672d15f8d91e06bf55cc2fa3d Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 13 Nov 2026 11:44:40 -0800 Subject: [PATCH 3/9] chore(deps): bump Rust deps flagged by security scans (#5035) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Bumps the Rust dependencies flagged by Aikido that have a semver-compatible fix available. Supersedes #5009 (rustls in the docs lockfile is included here). Root `Cargo.lock`: | Crate | From | To | | --- | --- | --- | | mio | 1.2.0 | 1.2.5 | | smallvec | 1.15.1 | 1.16.5 | | thread_local | 1.1.9 | 1.1.10 | | tinyvec | 1.11.0 | 1.13.3 | | zerocopy / zerocopy-derive | 0.8.48 | 0.8.63 | | event-listener | 5.4.1 | 5.4.2 | | arrayvec | 0.7.6 | 0.7.8 | | wasm-bindgen (+ js-sys, web-sys) | 0.2.121 | 0.2.130 | | getrandom 0.4 | 0.4.2 | 0.4.3 (drops wasip3 → wasmparser 0.244) | | brotli | 3.5.0 | 9.1.1 (via `random_word` dev-dep 0.4.3 → 1.0.0) | `docs/web-tests/rs/Cargo.lock` gets the same crates plus rustls, hyper, h2, moka, bytes, crossbeam-epoch and anyhow. That crate is not a workspace member, so cargo refused to resolve it; it now has an empty `[workspace]` table. Still open, blocked upstream: quick-xml 0.41 (lance-io), rand 0.9 (datafusion/lance/candle), heapless 0.8 (rstar via geo), paste, unsafe-libyaml (rattler_conda_types, lindera), fast-float/smartstring (polars 0.39), number_prefix (needs hf-hub 1.0 migration), zstd 0.13 (arrow-ipc). ## Merge Risk **Door:** two-way. Lockfile patch/minor bumps and a dev-only dependency. **Blast Radius:** none expected; no source changes. The docs crate is not built in CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 282 +++++++------------------------- docs/web-tests/rs/Cargo.lock | 301 ++++++++--------------------------- docs/web-tests/rs/Cargo.toml | 4 + rust/lancedb/Cargo.toml | 2 +- 4 files changed, 127 insertions(+), 462 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index efe0338cd..22b0f1e6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,15 +63,15 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "2.0.4" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ "alloc-no-stdlib", ] @@ -221,9 +221,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -1474,9 +1474,9 @@ dependencies = [ [[package]] name = "brotli" -version = "3.5.0" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1485,9 +1485,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.1" +version = "6.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -2261,7 +2261,7 @@ checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ "cpubits", "ctutils", - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "num-traits", "rand_core 0.10.1", @@ -2285,7 +2285,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "rand_core 0.10.1", ] @@ -3504,11 +3504,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -4248,17 +4247,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if 1.0.4", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -4939,12 +4936,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -5275,13 +5266,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if 1.0.4", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -6243,12 +6233,6 @@ dependencies = [ "spin 0.9.9", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -6704,9 +6688,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -8550,16 +8534,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - [[package]] name = "primefield" version = "0.14.0" @@ -8870,7 +8844,7 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.1", "rand_pcg", @@ -8973,7 +8947,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -9061,15 +9035,13 @@ dependencies = [ [[package]] name = "random_word" -version = "0.4.3" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07eed67a16dde2cc3c7f65c072acd8d5b2e53d4aab95067c320db851c7651f29" +checksum = "5d9299243acac3cb4f35c9f78d5ad29c87e70cd916a70f293d8526e54049c340" dependencies = [ "ahash", "brotli", - "once_cell", - "paste", - "rand 0.8.6", + "rand 0.10.1", "unicase", ] @@ -10528,9 +10500,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -11014,7 +10986,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", @@ -11113,9 +11085,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if 1.0.4", ] @@ -11183,18 +11155,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokenizers" @@ -11744,12 +11707,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unicode_categories" version = "0.1.1" @@ -11836,7 +11793,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -11919,16 +11876,7 @@ version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] @@ -11942,12 +11890,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if 1.0.4", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -11955,19 +11902,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11975,48 +11923,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -12043,23 +11969,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.11.1", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -12579,100 +12493,12 @@ version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.11.1", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "wkb" version = "0.9.2" @@ -12775,7 +12601,7 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.2", + "getrandom 0.4.3", "heapify", "itertools 0.14.0", "lz4_flex 0.13.1", @@ -12912,18 +12738,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -12999,7 +12825,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487" dependencies = [ "crc32fast", - "getrandom 0.4.2", + "getrandom 0.4.3", "indexmap 2.14.0", "libc", "memchr", diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock index 6e288950e..85384c8af 100644 --- a/docs/web-tests/rs/Cargo.lock +++ b/docs/web-tests/rs/Cargo.lock @@ -87,9 +87,9 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "ar_archive_writer" @@ -129,9 +129,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -683,9 +683,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cast" @@ -1019,9 +1019,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] @@ -1904,7 +1904,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1993,7 +1993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2004,11 +2004,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -2289,17 +2288,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -2317,9 +2314,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "h2" -version = "0.4.12" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2475,9 +2472,9 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hyper" -version = "1.8.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -2490,7 +2487,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -2699,12 +2695,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -2808,7 +2798,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2876,7 +2866,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2917,11 +2907,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -3607,12 +3598,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -3925,9 +3910,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -3936,9 +3921,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.12.11" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8261cd88c312e0004c1d51baad2980c66528dfdb2bee62003e643a4d8f86b077" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" dependencies = [ "async-lock", "crossbeam-channel", @@ -3949,7 +3934,6 @@ dependencies = [ "futures-util", "parking_lot", "portable-atomic", - "rustc_version", "smallvec", "tagptr", "uuid", @@ -4062,7 +4046,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4919,7 +4903,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "itertools 0.14.0", "log", "multimap", @@ -5020,7 +5004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.3", "rand_pcg", @@ -5046,7 +5030,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -5113,7 +5097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5520,14 +5504,14 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.11.0", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -5861,9 +5845,9 @@ checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "smartstring" @@ -5900,7 +5884,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -5912,7 +5896,7 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f103c50866b8743da9429b8a581d81a27c2d3a9c4ac7df8f8571c1dd7896eda" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -6247,7 +6231,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.2", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6301,9 +6285,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] @@ -6371,18 +6355,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" @@ -6646,12 +6621,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -6700,7 +6669,7 @@ version = "1.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -6731,9 +6700,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -6750,26 +6719,16 @@ version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen 0.46.0", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -6777,22 +6736,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.56" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ - "cfg-if", "js-sys", - "once_cell", + "tokio", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6800,48 +6757,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.6", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -6855,23 +6790,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.10.0", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -6909,7 +6832,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7254,94 +7177,6 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.10.0", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "writeable" version = "0.6.2" @@ -7388,18 +7223,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", diff --git a/docs/web-tests/rs/Cargo.toml b/docs/web-tests/rs/Cargo.toml index 8bc594c3c..1e1de2e45 100644 --- a/docs/web-tests/rs/Cargo.toml +++ b/docs/web-tests/rs/Cargo.toml @@ -1,3 +1,7 @@ +# Standalone crate pinned to a published lancedb release, not part of the root +# workspace. Without this, cargo commands here fail to resolve the workspace. +[workspace] + [package] name = "rs" version = "0.1.0" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 737c385c1..ef5da44c5 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -118,7 +118,7 @@ lance-testing = { workspace = true } # production remote feature so Python wheels do not resolve its Axum 0.7 stack. lance-namespace-impls = { workspace = true, features = ["rest-adapter"] } tempfile = { workspace = true } -random_word = { version = "0.4.3", features = ["en"] } +random_word = { version = "1.0.0", features = ["en"] } tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } uuid = { workspace = true } walkdir = "2" From b061c3627c46ec3d310cddb0aa45f022f8c4aad2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:52 -0800 Subject: [PATCH 4/9] feat(python): support exist_ok when creating views (#4984) Add `exist_ok=False` to synchronous and asynchronous Python view creation. Passing `True` sends `CREATE VIEW IF NOT EXISTS` and returns the existing view's stored query and schema unchanged; the default continues to fail on an existing name. ```python view = db.create_view("recent_orders", query, exist_ok=True) view = await async_db.create_view("recent_orders", query, exist_ok=True) ``` Requires a SQL server supporting `CREATE VIEW IF NOT EXISTS`. Rust gains an awaitable builder with `.exist_ok(true)`. Existing `.create_view(...).await` calls continue to work; callers requiring `Future` must convert the builder, and custom `Database` implementations must accept the new `exist_ok` argument. Includes Python round-trip coverage and Rust coverage for direct/deferred results and metadata preservation. --- docs/web/sql/ddl/view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 36 ++++++++--- python/python/lancedb/remote/db.py | 11 +++- python/python/tests/test_view_creation.py | 71 ++++++++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 24 +++++--- rust/lancedb/src/connection/create_view.rs | 62 +++++++++++++++++++ rust/lancedb/src/database.rs | 1 + rust/lancedb/src/remote/db.rs | 3 +- rust/lancedb/src/remote/sql/view.rs | 7 ++- rust/lancedb/src/remote/sql_test.rs | 28 ++++++++- 12 files changed, 239 insertions(+), 25 deletions(-) create mode 100644 python/python/tests/test_view_creation.py create mode 100644 rust/lancedb/src/connection/create_view.rs diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index e039fc43a..3d94292ab 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -23,6 +23,16 @@ catalog removal; physical cleanup can continue afterward. ## CREATE VIEW {#create} +{/* Draft for the view exist_ok release. + +`CREATE VIEW IF NOT EXISTS` creates a missing view and returns an existing +view's stored query and schema unchanged. Without `IF NOT EXISTS`, an existing +name is an error. In Python, use `db.create_view(name, query, exist_ok=True)`; +in Rust, use `db.create_view(name, query, &namespace).exist_ok(true).await?`. +Returning an existing view requires `SELECT` on that view. + +*/} + ```sql SQL icon="database" CREATE VIEW "recent_matches" AS diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5897ddd0c..56b644abb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -253,7 +253,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> Tuple[str, int, int]: ... async def create_view( - self, name: str, query: str, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ... async def describe_view( self, name: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 7d690abe3..020c79be0 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1273,7 +1273,12 @@ class DBConnection(EnforceOverrides): ) def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -1281,9 +1286,10 @@ class DBConnection(EnforceOverrides): is refused now rather than at the first read. A view holds no rows, and its readers see its sources as they are at read time. - There is no replace: a name already taken is an error, and changing a - view is a drop followed by a create. LanceDB Embedded connections raise - ``NotImplementedError``. + A name already taken is an error unless ``exist_ok=True``, which returns + the existing view's stored query and schema without changing them. + Changing a view is a drop followed by a create. LanceDB Embedded + connections raise ``NotImplementedError``. >>> import lancedb >>> db = lancedb.connect("db://my_database") # doctest: +SKIP @@ -2592,10 +2598,17 @@ class LanceDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override @@ -4107,7 +4120,12 @@ class AsyncConnection(object): ) async def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -4115,7 +4133,9 @@ class AsyncConnection(object): [DBConnection.create_view][lancedb.DBConnection.create_view]. """ return _view_description( - await self._inner.create_view(name, query, list(namespace_path or [])) + await self._inner.create_view( + name, query, list(namespace_path or []), exist_ok=exist_ok + ) ) async def describe_view( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index db3ab554c..ea9468331 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1197,10 +1197,17 @@ class RemoteDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override diff --git a/python/python/tests/test_view_creation.py b/python/python/tests/test_view_creation.py new file mode 100644 index 000000000..410356da0 --- /dev/null +++ b/python/python/tests/test_view_creation.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_create_view_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + original_query = "SELECT 'original' AS original" + submitted_query = ( + "SELECT 'replacement' AS replacement" if existing else original_query + ) + schema = { + "fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}], + "metadata": { + "lancedb::view::default_db": "analytics", + "lancedb::view::default_namespace": "team", + }, + } + result = pa.table( + {"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]} + ) + + class ViewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with ViewServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + if asynchronous: + db = await lancedb.connect_async("db://analytics", **connection_options) + view = await db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + else: + db = lancedb.connect("db://analytics", **connection_options) + view = db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + (request,) = server.requests + + prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW" + assert f'{prefix} "saved" AS {submitted_query}'.encode() in request + assert view.name == "saved" + assert view.namespace_path == ["team"] + assert view.default_namespace_path == ["team"] + assert view.query == original_query + assert view.schema.names == ["original"] diff --git a/python/src/connection.rs b/python/src/connection.rs index a32c00be1..ffa59fd02 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1158,18 +1158,20 @@ impl Connection { }) } - #[pyo3(signature = (name, query, namespace_path=None))] + #[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))] pub fn create_view( self_: PyRef<'_, Self>, name: String, query: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { let view = inner .create_view(name, query, &namespace_path) + .exist_ok(exist_ok) .await .infer_error()?; view_description_to_py(view) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index cc398e32b..c7a058502 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -53,6 +53,9 @@ use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; mod create_secret; mod create_table; +mod create_view; + +pub use create_view::CreateViewBuilder; pub use create_secret::CreateSecretBuilder; @@ -976,9 +979,10 @@ impl Connection { /// refused now rather than at the first read. A view holds no rows, and /// its readers see its sources as they are at read time. /// - /// There is no replace: a name already taken is an error, and changing a - /// view is a drop followed by a create, each authorized against what it - /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. + /// A name already taken is an error unless [`CreateViewBuilder::exist_ok`] is + /// true, which returns the stored definition and schema without changing them. + /// Changing a view is a drop followed by a create, each authorized against what + /// it actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -1011,16 +1015,18 @@ impl Connection { /// # Ok(()) /// # } /// ``` - pub async fn create_view( + pub fn create_view( &self, name: impl AsRef, query: impl AsRef, namespace_path: &[String], - ) -> Result { - validate_view_reference(name.as_ref(), namespace_path)?; - self.internal - .create_view(name.as_ref(), query.as_ref(), namespace_path) - .await + ) -> CreateViewBuilder { + CreateViewBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + query.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// What this database records about one view: its defining query and the diff --git a/rust/lancedb/src/connection/create_view.rs b/rust/lancedb/src/connection/create_view.rs new file mode 100644 index 000000000..bd80ca6e7 --- /dev/null +++ b/rust/lancedb/src/connection/create_view.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_view_reference; +use crate::view::ViewDescription; + +/// Configure creation of a view with [`super::Connection::create_view`]. +#[must_use] +pub struct CreateViewBuilder { + database: Arc, + name: String, + query: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateViewBuilder { + pub(super) fn new( + database: Arc, + name: String, + query: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + query, + namespace_path, + exist_ok: false, + } + } + + /// Return the existing view without changing its definition if it exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the view or return the existing view when `exist_ok` is true. + pub async fn execute(self) -> Result { + validate_view_reference(&self.name, &self.namespace_path)?; + self.database + .create_view(&self.name, &self.query, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateViewBuilder { + type Output = Result; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 23ed9fc3d..39e361a39 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -693,6 +693,7 @@ pub trait Database: _name: &str, _query: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result { view_ops_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 92523ec34..a05bb07b7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1099,11 +1099,12 @@ impl Database for RemoteDatabase { name: &str, query: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .create_view(name, query, namespace_path) + .create_view(name, query, namespace_path, exist_ok) .await } async fn describe_view( diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 0c2229684..513113187 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -99,13 +99,18 @@ impl SqlClient { name: &str, query: &str, namespace: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace)?; let namespace_path = namespace.to_vec(); + let if_not_exists = if exist_ok { " IF NOT EXISTS" } else { "" }; self.object_job( ExecuteQueryRequest { - query: format!("CREATE VIEW {} AS {query}", quote_identifier(name)), + query: format!( + "CREATE VIEW{if_not_exists} {} AS {query}", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d25c72830..6a3f30390 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -24,6 +24,7 @@ use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::Connection; use crate::database::Database; +use crate::embeddings::MemoryRegistry; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; @@ -3710,26 +3711,49 @@ async fn view_create_and_describe_return_metadata_through_sql() { ..Default::default() }; let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { panic!("unexpected REST request"); }) .with_sql_client(client); - let created = db + let connection = Connection::new(Arc::new(db), Arc::new(MemoryRegistry::new())); + let created = connection .create_view("adults", "SELECT name FROM people", &["team".into()]) .await .unwrap(); - let described = db.describe_view("adults", &["team".into()]).await.unwrap(); + let existing = connection + .create_view( + "adults", + "SELECT replacement FROM other_people", + &["team".into()], + ) + .exist_ok(true) + .await + .unwrap(); + let described = connection + .describe_view("adults", &["team".into()]) + .await + .unwrap(); assert_eq!(created, described); + assert_eq!(existing, described); assert_eq!(created.schema.fields()[0].name(), "name"); assert_eq!(created.default_namespace_path, ["team"]); assert_eq!( statements.lock().unwrap().as_slice(), [ "CREATE VIEW \"adults\" AS SELECT name FROM people", + "CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people", "DESCRIBE VIEW \"adults\"" ] ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); shutdown.send(()).unwrap(); } } From 2c3c30dbdf02a4dc9f725b00701b995954e228b1 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:54 -0800 Subject: [PATCH 5/9] feat(python): support exist_ok for Function creation (#4992) Adds `exist_ok=False` to Python Function creation and job submission. `exist_ok=True` sends `CREATE FUNCTION IF NOT EXISTS` and returns the stored immutable version, preserving its code, credentials and execution settings. The default retains the current version-creation behavior. ```python version = db.create_function(analyze_caption, exist_ok=True) ``` The option also exists on the Rust registration request and is kept out of the canonical Function definition payload. Includes sync/async/background protocol and stored-version coverage. Requires matching SQL server support. BREAKING CHANGE: Rust `FunctionRegistrationRequest` struct literals must initialize `exist_ok`; legacy serialized requests default to false. No local builds or tests were run, as requested. --- docs/web/management/function.mdx | 13 ++++ docs/web/sql/ddl/function.mdx | 9 +++ python/python/lancedb/_lancedb.pyi | 6 +- python/python/lancedb/db.py | 25 +++++++- python/python/lancedb/remote/db.py | 6 +- python/python/tests/test_function_creation.py | 63 +++++++++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/function.rs | 7 +++ rust/lancedb/src/remote/sql/function.rs | 11 +++- rust/lancedb/src/remote/sql_test.rs | 20 +++++- 10 files changed, 155 insertions(+), 11 deletions(-) create mode 100644 python/python/tests/test_function_creation.py diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 04c146bb1..aae67ceb9 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -111,6 +111,19 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +{/* Draft for the function exist_ok release. + +Use `exist_ok=True` on `create_function` or `create_function_async` to return +the existing named version without changing its code, credentials or settings. +This requires a deployment that supports the option. The default retains the +current behavior of registering a new version. + +```python +version = db.create_function(embed, exist_ok=True) +``` + +*/} + The SQL command submits an internal `create_function` image-build job and waits for publication. The SDK returns the SQL query handle. Query handles diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 95c2d4d6e..55e2d6fe7 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -16,6 +16,15 @@ availability: ## CREATE FUNCTION {#create} +{/* Draft for the function exist_ok release. + +`CREATE FUNCTION IF NOT EXISTS` preserves an existing named Function version, +including its code, credentials and execution settings. In Python, pass +`exist_ok=True` to `create_function` or `create_function_async`. The default +retains the existing version-creation behavior. + +*/} + ```sql SQL icon="database" CREATE FUNCTION f(x int64) RETURNS int64 diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 56b644abb..44523fd42 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -188,7 +188,11 @@ class Connection(object): async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( - self, request_json: str, namespace_path: Optional[List[str]] = None + self, + request_json: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Job: ... async def get_function( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 020c79be0..050b20727 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1004,10 +1004,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. + ``exist_ok=True`` returns the existing named Function version unchanged. + By default, registration retains its existing version-creation behavior. + The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. LanceDB Embedded connections raise ``NotImplementedError``. @@ -1040,7 +1044,10 @@ class DBConnection(EnforceOverrides): ``` """ return self.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ).wait() def create_function_async( @@ -1048,10 +1055,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -2396,11 +2407,15 @@ class LanceDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) @@ -3732,10 +3747,14 @@ class AsyncConnection(object): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -3749,7 +3768,7 @@ class AsyncConnection(object): raise TypeError("create_function_async requires a @function definition") request = definition.bind_secrets(secrets) inner = await self._inner.create_function_async( - request.to_canonical_json(), namespace_path + request.to_canonical_json(), namespace_path, exist_ok=exist_ok ) return _typed_job(inner, FunctionVersion.from_json) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ea9468331..870b85b1e 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -992,11 +992,15 @@ class RemoteDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) diff --git a/python/python/tests/test_function_creation.py b/python/python/tests/test_function_creation.py new file mode 100644 index 000000000..823dba7b9 --- /dev/null +++ b/python/python/tests/test_function_creation.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.functions import function + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"]) +@pytest.mark.parametrize("exist_ok", [None, False, True]) +async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/first_class_functions/v1" + / "remote_function_version.canonical.json" + ) + stored = json.loads(fixture.read_text()) + result = pa.table({"definition": [json.dumps(stored)]}) + + @function(name=stored["name"]) + def replacement(value: float) -> float: + return value * 2 + + class FunctionServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with FunctionServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs["namespace_path"] = ["team"] + if entry == "async_job": + db = await lancedb.connect_async("db://analytics", **options) + job = await db.create_function_async(replacement, **kwargs) + version = await job.wait() + else: + db = lancedb.connect("db://analytics", **options) + if entry == "sync_job": + version = db.create_function_async(replacement, **kwargs).wait() + else: + version = db.create_function(replacement, **kwargs) + (request,) = server.requests + + prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION" + assert f'{prefix} "{stored["name"]}" FROM '.encode() in request + assert b'"exist_ok"' not in request + assert json.loads(version.to_canonical_json()) == stored diff --git a/python/src/connection.rs b/python/src/connection.rs index ffa59fd02..dabecc048 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -903,15 +903,17 @@ impl Connection { }) } - #[pyo3(signature = (request_json, namespace_path=None))] + #[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))] pub fn create_function_async( self_: PyRef<'_, Self>, request_json: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); - let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) + let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) .infer_error()?; + request.exist_ok = exist_ok; let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index e3d47948e..d1b63f2ad 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -834,6 +834,9 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s /// database already holds, which Sophon resolves inside the remote runtime. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Preserve an existing named Function version instead of registering a new one. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, /// Default retries of failed user-code calls. Enterprise only. #[serde(default, skip_serializing_if = "Option::is_none")] pub retry_policy: Option, @@ -876,6 +879,10 @@ pub struct FunctionRegistrationRequest { pub models: Vec, } +fn is_false(value: &bool) -> bool { + !*value +} + impl FunctionRegistrationRequest { /// Decode a registration request supplied by an SDK language binding. pub fn from_json(json: &str) -> Result { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index c2b5aba06..19a1a6cbc 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -34,13 +34,22 @@ impl SqlClient { validate_function_name(&request.name)?; validate_namespace(namespace)?; let name = quote_identifier(&request.name); + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let mut body = serde_json::to_value(request).map_err(|error| Error::Runtime { message: error.to_string(), })?; body.as_object_mut().unwrap().remove("name"); + body.as_object_mut().unwrap().remove("exist_ok"); self.object_job( ExecuteQueryRequest { - query: format!("CREATE FUNCTION {name} FROM {}", literal(&body.to_string())), + query: format!( + "CREATE FUNCTION{if_not_exists} {name} FROM {}", + literal(&body.to_string()) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 6a3f30390..e1780f118 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3087,7 +3087,16 @@ async fn function_creation_and_description_use_sql_query_handles() { const REQUEST: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" ); - for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { + for (defer, with_models, exist_ok) in [ + (false, false, false), + (false, true, false), + (true, false, false), + (true, true, false), + (false, false, true), + (false, true, true), + (true, false, true), + (true, true, true), + ] { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); request_json["max_concurrency"] = serde_json::json!(4); @@ -3113,9 +3122,11 @@ async fn function_creation_and_description_use_sql_query_handles() { let expected_models = version_json["image"].get("models"); let mut expected_request = request_json.clone(); expected_request.as_object_mut().unwrap().remove("name"); - let request = + let mut request = crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) .unwrap(); + assert!(!request.exist_ok); + request.exist_ok = exist_ok; let result = RecordBatch::try_from_iter(vec![( "definition", Arc::new(StringArray::from(vec![version_json.to_string()])) as ArrayRef, @@ -3151,7 +3162,10 @@ async fn function_creation_and_description_use_sql_query_handles() { { let seen = statements.lock().unwrap(); let encoded = seen[0] - .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .strip_prefix(&format!( + "CREATE FUNCTION{} \"normalize_score\" FROM '", + if exist_ok { " IF NOT EXISTS" } else { "" } + )) .unwrap() .strip_suffix('\'') .unwrap(); From a0eb6b4b71d7b59a5047387a32563b098e349418 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:37:08 -0800 Subject: [PATCH 6/9] feat(python): support exist_ok for storage integrations (#4986) Adds `exist_ok=False` to sync and async Python storage integration creation. `exist_ok=True` sends `CREATE STORAGE INTEGRATION IF NOT EXISTS` and returns the server's stored configuration, preserving the prefix, credentials and external ID. ```python integration = db.create_storage_integration( "raw", storage_provider="S3", storage_prefix="s3://customer-bucket/raw/", aws_role_arn="arn:aws:iam::123456789012:role/access", exist_ok=True, ) ``` The non-exhaustive Rust request also supports `.exist_ok(true)` for every provider. Requires a SQL server supporting this syntax. Includes protocol and provider SQL coverage. No local builds or tests were run, as requested. --- docs/web/sql/ddl/storage-integration.mdx | 10 +++ python/python/lancedb/db.py | 13 +++ python/python/lancedb/remote/db.py | 2 + .../test_storage_integration_creation.py | 85 +++++++++++++++++++ .../lancedb/src/remote/storage_integration.rs | 53 +++++++++++- rust/lancedb/src/storage_integration.rs | 26 ++++++ 6 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 python/python/tests/test_storage_integration_creation.py diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 37351f971..9444824ac 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -28,6 +28,16 @@ CREATE STORAGE INTEGRATION ``` +{/* Draft for the storage-integration exist_ok release. + +`IF NOT EXISTS` returns an existing integration unchanged, including its provider, +storage prefix, credential references and external ID. In the Python SDK, pass +`exist_ok=True` to `create_storage_integration`. The default reports an error when +the name already exists. +Returning an existing integration requires `USAGE` on that integration. + +*/} + `STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. `STORAGE_PREFIX` is the URI prefix the integration covers -- a query only matches an integration whose prefix is a prefix of the URI it reads. diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 050b20727..39c9eb1d5 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -432,8 +432,12 @@ class DBConnection(EnforceOverrides): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: + """Register storage access, preserving existing configuration with + ``exist_ok=True``. Existing names are errors by default. + """ raise NotImplementedError def describe_storage_integration( @@ -2503,6 +2507,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -2520,6 +2525,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) @@ -3888,6 +3894,7 @@ class AsyncConnection(object): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: """Register cloud storage access using database-owned credential Secrets. @@ -3902,6 +3909,10 @@ class AsyncConnection(object): optionally set ``huggingface_token_secret`` to a Secret containing the token; omitting it selects anonymous access at the default rate limits. Registration returns setup instructions without verifying storage access. + + ``exist_ok=True`` returns the stored configuration unchanged when the + integration exists, preserving its provider, prefix and credential + bindings. Existing names are errors by default. """ azure_options = ( azure_tenant_id_secret, @@ -4010,6 +4021,8 @@ class AsyncConnection(object): "aws_access_key_id_secret": reference(aws_access_key_id_secret), "aws_secret_access_key_secret": reference(aws_secret_access_key_secret), } + if exist_ok: + request["exist_ok"] = True info = await self._inner.create_storage_integration( validate_secret_name(name), json.dumps(request), diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 870b85b1e..9221c7ceb 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1091,6 +1091,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -1108,6 +1109,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) diff --git a/python/python/tests/test_storage_integration_creation.py b/python/python/tests/test_storage_integration_creation.py new file mode 100644 index 000000000..13b94d741 --- /dev/null +++ b/python/python/tests/test_storage_integration_creation.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_storage_integration_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/storage_integration.json" + ) + stored = json.loads(fixture.read_text()) + stored["namespace_path"] = ["team"] + columns = {} + for key, value in stored.items(): + if isinstance(value, (dict, list)): + value = json.dumps(value) + columns[key] = pa.array([None], type=pa.string()) if value is None else [value] + result = pa.table(columns) + prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"] + role = ( + "arn:aws:iam::999999999999:role/replacement" + if existing + else stored["aws_role_arn"] + ) + + class IntegrationServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with IntegrationServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs.update( + storage_provider="S3", + storage_prefix=prefix, + aws_role_arn=role, + namespace_path=["team"], + ) + uri = f"db://{stored['database']}" + if asynchronous: + db = await lancedb.connect_async(uri, **connection_options) + info = await db.create_storage_integration(stored["name"], **kwargs) + else: + db = lancedb.connect(uri, **connection_options) + info = db.create_storage_integration(stored["name"], **kwargs) + (request,) = server.requests + + command = ( + "CREATE STORAGE INTEGRATION IF NOT EXISTS" + if exist_ok + else "CREATE STORAGE INTEGRATION" + ) + assert f'{command} "raw"'.encode() in request + assert prefix.encode() in request + assert role.encode() in request + assert info.storage_prefix == stored["storage_prefix"] + assert info.aws_role_arn == stored["aws_role_arn"] + assert info.aws_external_id == stored["aws_external_id"] + assert info.created_at_millis == stored["created_at_millis"] + assert info.namespace_path == ["team"] diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index bdba4f1df..48dab4c6a 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -54,6 +54,11 @@ pub(super) fn create_sql( namespace: &[String], request: &CreateStorageIntegrationRequest, ) -> Result { + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; if request.storage_provider != StorageProvider::HuggingFace && request.huggingface_token_secret.is_some() { @@ -77,7 +82,7 @@ pub(super) fn create_sql( )); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -115,7 +120,7 @@ pub(super) fn create_sql( .as_ref() .ok_or_else(|| invalid("GCP integrations require gcp_credentials_json_secret"))?; return Ok(format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", object_name(name, namespace)?, literal(&request.storage_prefix), secret_name(reference)? @@ -135,7 +140,7 @@ pub(super) fn create_sql( .filter(|account| !account.is_empty()) .ok_or_else(|| invalid("Azure integrations require azure_storage_account"))?; let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", object_name(name, namespace)?, literal(&request.storage_prefix), literal(account) @@ -169,7 +174,7 @@ pub(super) fn create_sql( return Err(invalid("S3 integrations cannot contain Azure options")); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -283,6 +288,46 @@ mod tests { use super::*; + #[test] + fn create_if_not_exists_preserves_provider_options() { + let secret = SecretReference::new("credential"); + let requests = [ + CreateStorageIntegrationRequest::s3("s3://bucket/", "role"), + CreateStorageIntegrationRequest::s3_with_secrets( + "s3://bucket/", + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::azure( + "az://container/", + "account", + secret.clone(), + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::gcp("gs://bucket/", secret), + CreateStorageIntegrationRequest::huggingface("hf://datasets/acme/data/"), + ]; + for request in requests { + let legacy_json = serde_json::to_value(&request).unwrap(); + assert!(legacy_json.get("exist_ok").is_none()); + let decoded: CreateStorageIntegrationRequest = + serde_json::from_value(legacy_json).unwrap(); + assert!(!decoded.exist_ok); + let strict = create_sql("raw", &[], &request).unwrap(); + let guarded = request.exist_ok(true); + assert_eq!(serde_json::to_value(&guarded).unwrap()["exist_ok"], true); + assert_eq!( + create_sql("raw", &[], &guarded).unwrap(), + strict.replacen( + "CREATE STORAGE INTEGRATION ", + "CREATE STORAGE INTEGRATION IF NOT EXISTS ", + 1, + ) + ); + } + } + #[test] fn sql_quotes_values_and_keeps_secret_root_namespace_explicit() { let role = CreateStorageIntegrationRequest::s3("s3://bucket/it's/", "role'value"); diff --git a/rust/lancedb/src/storage_integration.rs b/rust/lancedb/src/storage_integration.rs index 50bfc0aca..587528037 100644 --- a/rust/lancedb/src/storage_integration.rs +++ b/rust/lancedb/src/storage_integration.rs @@ -40,6 +40,9 @@ impl SecretReference { #[derive(Debug, Clone, Serialize, Deserialize)] #[non_exhaustive] pub struct CreateStorageIntegrationRequest { + /// Return the stored configuration unchanged when the integration already exists. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, pub storage_provider: StorageProvider, pub storage_prefix: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -77,12 +80,31 @@ pub enum StorageProvider { HuggingFace, } +fn is_false(value: &bool) -> bool { + !*value +} + impl CreateStorageIntegrationRequest { + /// Return an existing integration without changing its configuration. + /// Defaults to false, which reports an error for an existing name. + /// + /// ``` + /// use lancedb::storage_integration::CreateStorageIntegrationRequest; + /// let config = CreateStorageIntegrationRequest::huggingface( + /// "hf://datasets/acme/data/", + /// ).exist_ok(true); + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Register a prefix and the customer-owned IAM role authorized to access it. pub fn s3(storage_prefix: impl Into, aws_role_arn: impl Into) -> Self { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: Some(aws_role_arn.into()), aws_access_key_id_secret: None, aws_secret_access_key_secret: None, @@ -105,6 +127,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: None, aws_access_key_id_secret: Some(access_key), aws_secret_access_key_secret: Some(secret_key), @@ -138,6 +161,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Azure, storage_prefix: storage_prefix.into(), + exist_ok: false, azure_storage_account: Some(storage_account.into()), azure_tenant_id_secret: Some(tenant_id), azure_client_id_secret: Some(client_id), @@ -163,6 +187,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Gcp, storage_prefix: storage_prefix.into(), + exist_ok: false, gcp_credentials_json_secret: Some(credentials_json), huggingface_token_secret: None, aws_role_arn: None, @@ -189,6 +214,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::HuggingFace, storage_prefix: storage_prefix.into(), + exist_ok: false, huggingface_token_secret: None, gcp_credentials_json_secret: None, aws_role_arn: None, From 4db0d5c7f50a61d1c01a9ef409c11e3ba09d04eb Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:48:26 -0800 Subject: [PATCH 7/9] feat(python): support exist_ok when cloning tables (#4990) Adds `exist_ok=False` to Python table cloning and `.exist_ok(true)` to the Rust clone builder. An existing target is returned with its data and version history unchanged; strict duplicate errors remain the default. ```python snapshot = db.clone_table("snapshot", source_uri, exist_ok=True) ``` Embedded cloning skips source reads for an existing target and handles typed creation conflicts. Remote cloning forwards the option to the server. Includes sync/async preservation and remote request coverage, plus SQL syntax documentation for `CREATE TABLE IF NOT EXISTS target CLONE source`. Requires a server supporting the option for remote clones. BREAKING CHANGE: Rust `CloneTableRequest` struct literals must initialize the new `exist_ok` field; `CloneTableRequest::new` remains compatible. No local builds or tests were run, as requested. --- docs/web/management/table.mdx | 12 ++++ docs/web/sql/ddl/table.mdx | 10 ++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 8 +++ python/python/lancedb/remote/db.py | 4 ++ python/python/tests/test_clone_creation.py | 36 ++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/connection.rs | 30 +++++++++- rust/lancedb/src/database.rs | 3 + rust/lancedb/src/database/listing.rs | 65 ++++++++++++++-------- rust/lancedb/src/remote/db.rs | 16 +++++- 11 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 python/python/tests/test_clone_creation.py diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index bf6bf3edd..8031a4c49 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -270,6 +270,18 @@ Renaming is not supported on a local directory connection. In LanceDB Enterprise whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. +{/* Draft for the table-clone exist_ok release. + +Pass `exist_ok=True` to keep an existing target table, including its data and +version history, instead of reporting a duplicate. The source is used only when +the target is missing. Remote use requires a deployment that supports this option. + +```python +db.clone_table("docs_snapshot", source_uri="s3://bucket/db/documents.lance", exist_ok=True) +``` + +*/} + A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index ab0ff64bf..c8c42d4e0 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -205,6 +205,16 @@ Dropping, renaming, or retyping a column is an SDK operation ## CLONE {#clone} +{/* Draft for the table-clone exist_ok release. + +Use `CREATE TABLE IF NOT EXISTS target CLONE source` to preserve an existing +target unchanged. The Python equivalent is +`db.clone_table("target", source_uri, exist_ok=True)`. Omitting the option reports +an error for an existing target. A skipped clone does not copy rows or change +the target's version history. + +*/} + ```sql SQL icon="database" CREATE TABLE docs_snapshot CLONE documents diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 44523fd42..d5c024959 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -347,6 +347,8 @@ class Connection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + *, + exist_ok: bool = False, ) -> Table: ... async def rename_table( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 39c9eb1d5..18ca9cf6f 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2271,6 +2271,7 @@ class LanceDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> LanceTable: """Clone a table from a source table. @@ -2295,6 +2296,8 @@ class LanceDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -2310,6 +2313,7 @@ class LanceDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return LanceTable.open( @@ -3595,6 +3599,7 @@ class AsyncConnection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> AsyncTable: """Clone a table from a source table. @@ -3619,6 +3624,8 @@ class AsyncConnection(object): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -3633,6 +3640,7 @@ class AsyncConnection(object): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) return AsyncTable(table) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 9221c7ceb..69b691004 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -576,6 +576,7 @@ class RemoteDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> Table: """Clone a table from a source table. @@ -595,6 +596,8 @@ class RemoteDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -612,6 +615,7 @@ class RemoteDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return RemoteTable( diff --git a/python/python/tests/test_clone_creation.py b/python/python/tests/test_clone_creation.py new file mode 100644 index 000000000..6c12420c5 --- /dev/null +++ b/python/python/tests/test_clone_creation.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous): + source_uri = str(tmp_path / "source.lance") + if asynchronous: + db = await lancedb.connect_async(tmp_path) + await db.create_table("source", [{"id": 1}]) + table = await db.clone_table("target", source_uri, exist_ok=True) + assert (await table.to_arrow()).to_pylist() == [{"id": 1}] + await table.add([{"id": 2}]) + version = await table.version() + with pytest.raises(ValueError, match="already exists"): + await db.clone_table("target", source_uri) + kept = await db.clone_table("target", "missing.lance", exist_ok=True) + assert await kept.version() == version + assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}] + else: + db = lancedb.connect(tmp_path) + db.create_table("source", [{"id": 1}]) + table = db.clone_table("target", source_uri, exist_ok=True) + assert table.to_arrow().to_pylist() == [{"id": 1}] + table.add([{"id": 2}]) + version = table.version + with pytest.raises(ValueError, match="already exists"): + db.clone_table("target", source_uri) + kept = db.clone_table("target", "missing.lance", exist_ok=True) + assert kept.version == version + assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}] diff --git a/python/src/connection.rs b/python/src/connection.rs index dabecc048..8763822cc 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -457,7 +457,8 @@ impl Connection { }) } - #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))] pub fn clone_table( self_: PyRef<'_, Self>, target_table_name: String, @@ -466,6 +467,7 @@ impl Connection { source_version: Option, source_tag: Option, is_shallow: bool, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); @@ -477,7 +479,7 @@ impl Connection { if let Some(tag) = source_tag { builder = builder.source_tag(tag); } - builder = builder.is_shallow(is_shallow); + builder = builder.is_shallow(is_shallow).exist_ok(exist_ok); future_into_py(self_.py(), async move { let table = builder.execute().await.infer_error()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index c7a058502..6dacbbbea 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -433,6 +433,21 @@ impl CloneTableBuilder { } } + /// Preserve an existing target without reading or cloning the source. + /// Defaults to false, which reports a duplicate-name error. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let table = db.clone_table("snapshot", "s3://bucket/source.lance") + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.request.exist_ok = exist_ok; + self + } + /// Set the source version to clone from pub fn source_version(mut self, version: u64) -> Self { self.request.source_version = Some(version); @@ -633,7 +648,8 @@ impl Connection { /// Creates a new table by cloning from an existing source table. /// By default, this performs a shallow clone where the new table shares /// the underlying data files with the source table. - /// The target table name must be unused. An existing table is left unchanged. + /// The target table name must be unused by default. Use + /// [`CloneTableBuilder::exist_ok`] to open an existing target unchanged. /// /// # Parameters /// - `target_table_name`: The name of the new table to create @@ -2787,6 +2803,14 @@ mod tests { "unexpected clone error: {err:?}" ); + let preserved = db + .clone_table(target, "missing-source.lance") + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(preserved.name(), target); + // Reopen both tables to verify that the failed clone left their data and versions intact. for (name, expected_data) in [("source", source_data), ("target", target_data)] { let table = db.open_table(name).execute().await.unwrap(); @@ -2804,8 +2828,9 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { let tmp_dir = tempdir().unwrap(); let uri = tmp_dir.path().to_str().unwrap(); let db = connect(uri).execute().await.unwrap(); @@ -2830,6 +2855,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table("cloned_table", source_uri) + .exist_ok(exist_ok) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 39e361a39..638ae0dd5 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -163,6 +163,8 @@ impl CreateTableRequest { /// sharing the same data, deletion, and index files. #[derive(Clone, Debug)] pub struct CloneTableRequest { + /// Preserve an existing target rather than returning a duplicate-name error. + pub exist_ok: bool, /// The name of the target table to create pub target_table_name: String, /// The namespace path for the target table. Empty list represents root namespace. @@ -184,6 +186,7 @@ pub struct CloneTableRequest { impl CloneTableRequest { pub fn new(target_table_name: String, source_uri: String) -> Self { Self { + exist_ok: false, target_table_name, target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index d5749f974..765c8af3d 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1119,40 +1119,47 @@ impl Database for ListingDatabase { }; let target_uri = self.table_uri(&request.target_table_name)?; - match DatasetBuilder::from_uri(&target_uri) + let exists = match DatasetBuilder::from_uri(&target_uri) .with_read_params(read_params.clone()) .load() .await { - Ok(_) => { + Ok(_) if !request.exist_ok => { return Err(Error::TableAlreadyExists { name: request.target_table_name, }); } - Err(lance::Error::DatasetNotFound { .. }) => {} + Ok(_) => true, + Err(lance::Error::DatasetNotFound { .. }) => false, Err(err) => return Err(err.into()), + }; + + if !exists { + let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) + .with_read_params(read_params.clone()) + .load() + .await + .map_err(|e| -> Error { e.into() })?; + + let version_ref = match (request.source_version, request.source_tag) { + (Some(v), None) => Ok(Ref::Version(None, Some(v))), + (None, Some(tag)) => Ok(Ref::Tag(tag)), + (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), + _ => Err(Error::InvalidInput { + message: "Cannot specify both source_version and source_tag".to_string(), + }), + }?; + + match source_dataset + .shallow_clone(&target_uri, version_ref, Some(storage_params)) + .await + { + Ok(_) => {} + Err(lance::Error::DatasetAlreadyExists { .. }) if request.exist_ok => {} + Err(error) => return Err(error.into()), + } } - let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) - .with_read_params(read_params.clone()) - .load() - .await - .map_err(|e| -> Error { e.into() })?; - - let version_ref = match (request.source_version, request.source_tag) { - (Some(v), None) => Ok(Ref::Version(None, Some(v))), - (None, Some(tag)) => Ok(Ref::Tag(tag)), - (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), - _ => Err(Error::InvalidInput { - message: "Cannot specify both source_version and source_tag".to_string(), - }), - }?; - - source_dataset - .shallow_clone(&target_uri, version_ref, Some(storage_params)) - .await - .map_err(|e| -> Error { e.into() })?; - let cloned_table = NativeTable::open_with_params( &target_uri, &request.target_table_name, @@ -2252,6 +2259,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_table".to_string(), target_namespace_path: vec![], source_uri: source_uri.clone(), @@ -2313,6 +2321,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_with_data".to_string(), target_namespace_path: vec![], source_uri, @@ -2375,6 +2384,7 @@ mod tests { // Clone should work with storage options let cloned = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2412,6 +2422,7 @@ mod tests { // Try deep clone (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2453,6 +2464,7 @@ mod tests { // Try clone with namespace (should fail for listing database) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec!["namespace".to_string()], // Non-empty namespace source_uri, @@ -2494,6 +2506,7 @@ mod tests { // Try clone with invalid target name let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "invalid/name".to_string(), // Invalid name with slash target_namespace_path: vec![], source_uri, @@ -2514,6 +2527,7 @@ mod tests { // Try to clone from non-existent source let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri: "/nonexistent/table.lance".to_string(), @@ -2551,6 +2565,7 @@ mod tests { // Try clone with both version and tag (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2625,6 +2640,7 @@ mod tests { // Clone from the initial version (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_version".to_string(), target_namespace_path: vec![], source_uri, @@ -2704,6 +2720,7 @@ mod tests { // Clone from the tag (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_tag".to_string(), target_namespace_path: vec![], source_uri, @@ -2756,6 +2773,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "independent_clone".to_string(), target_namespace_path: vec![], source_uri, @@ -2849,6 +2867,7 @@ mod tests { // Clone without specifying version or tag (should get latest) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_latest".to_string(), target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a05bb07b7..300cd6b09 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1612,10 +1612,13 @@ impl Database for RemoteDatabase { is_shallow: Some(request.is_shallow), }; - let req = self + let mut req = self .client .post(&format!("/v1/table/{}/clone", table_identifier.clone())) .json(&remote_request); + if request.exist_ok { + req = req.query(&[("exist_ok", true)]); + } let (request_id, rsp) = self.client.send(req).await?; @@ -3651,9 +3654,10 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { - let conn = Connection::new_with_handler(|request| { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { + let conn = Connection::new_with_handler(move |request| { assert_eq!(request.method(), &reqwest::Method::POST); assert_eq!(request.url().path(), "/v1/table/cloned_table/clone"); assert_eq!( @@ -3665,12 +3669,18 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(body).unwrap(); assert_eq!(body["source_location"], "s3://bucket/source_table"); assert_eq!(body["is_shallow"], true); + if exist_ok { + assert_eq!(request.url().query(), Some("exist_ok=true")); + } else { + assert!(request.url().query().is_none()); + } http::Response::builder().status(200).body("").unwrap() }); let table = conn .clone_table("cloned_table", "s3://bucket/source_table") + .exist_ok(exist_ok) .execute() .await .unwrap(); From 81d04b8c361b596b29f4f7988aab7df0eb9f84ca Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:29 -0800 Subject: [PATCH 8/9] feat(python): support exist_ok for materialized views (#4991) --- docs/web/sql/ddl/materialized-view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 25 ++++++ python/python/lancedb/namespace.py | 8 ++ python/python/lancedb/remote/db.py | 4 + .../tests/test_materialized_view_creation.py | 84 +++++++++++++++++++ .../python/tests/test_materialized_views.py | 2 + python/src/connection.rs | 10 ++- rust/lancedb/src/materialized_view.rs | 49 ++++++++++- rust/lancedb/src/remote/db.rs | 11 ++- .../src/remote/sql/materialized_view.rs | 15 ++++ rust/lancedb/src/remote/sql_test.rs | 60 +++++++++++++ rust/lancedb/src/remote/table.rs | 7 ++ 13 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 python/python/tests/test_materialized_view_creation.py diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index 2f9173ecd..a2453ba01 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -27,6 +27,16 @@ CREATE MATERIALIZED VIEW AS SELECT ... ``` +{/* Draft for the materialized-view exist_ok release. + +`IF NOT EXISTS` preserves an existing materialized view's definition, data and +refresh settings without refreshing it. The Python equivalent is +`db.create_materialized_view("saved", "source", exist_ok=True)`. A skipped +asynchronous creation returns a completed job without submitting a refresh job. +Existing names are errors by default. + +*/} + Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see [Materialized views](/management/materialized-view#create). diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index d5c024959..e3f00557c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -369,6 +369,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Table: ... async def create_materialized_view_async( self, @@ -382,6 +383,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 18ca9cf6f..b84e4d581 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -710,11 +710,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -780,11 +784,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: """Submit materialized-view creation and return its job. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + The job may already be complete in LanceDB Embedded. In LanceDB Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL server and the returned ``id`` is the registry job ID. That ID can be @@ -2150,11 +2158,15 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -2185,6 +2197,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -2202,6 +2215,7 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -2214,6 +2228,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -3453,11 +3468,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -3480,6 +3499,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, @@ -3496,11 +3516,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + Wait for the returned job before opening or querying the view. In LanceDB Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. @@ -3521,6 +3545,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 72dc78c8b..67fcc61f7 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -705,6 +705,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -723,6 +724,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ).name ) @@ -741,6 +743,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> Job[None]: job = LOOP.run( self._inner.create_materialized_view_async( @@ -753,6 +756,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ) return Job(job) @@ -1352,6 +1356,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( @@ -1364,6 +1369,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1381,6 +1387,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" return await self._inner.create_materialized_view_async( @@ -1393,6 +1400,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 69b691004..b9928d278 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -803,6 +803,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: @@ -817,6 +818,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -841,6 +843,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -853,6 +856,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) diff --git a/python/python/tests/test_materialized_view_creation.py b/python/python/tests/test_materialized_view_creation.py new file mode 100644 index 000000000..0d9a4c2b4 --- /dev/null +++ b/python/python/tests/test_materialized_view_creation.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("defining_query", [False, True]) +async def test_exist_ok_preserves_materialized_data( + tmp_path, asynchronous, background, namespace, defining_query +): + source_args = ( + {"query": "SELECT * FROM source"} if defining_query else {"source": "source"} + ) + replacement_args = { + **( + {"query": "SELECT * FROM missing"} + if defining_query + else {"source": "missing"} + ), + "auto_refresh_enabled": True, + "auto_refresh_interval_seconds": 1, + } + options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}} + if asynchronous: + db = ( + lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options) + if namespace + else await lancedb.connect_async(tmp_path, **options) + ) + source = await db.create_table("source", [{"id": 1}]) + original = await db.create_materialized_view( + "saved", **source_args, exist_ok=True + ) + definition = await original.definition() + version = await original.table.version() + await source.add([{"id": 2}]) + if background: + job = await db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + await job.wait() + kept = await db.open_materialized_view("saved") + else: + kept = await db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert (await kept.definition()).query == definition.query + assert await kept.table.version() == version + assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + await db.create_materialized_view("saved", **source_args) + else: + db = ( + lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options) + if namespace + else lancedb.connect(tmp_path, **options) + ) + source = db.create_table("source", [{"id": 1}]) + original = db.create_materialized_view("saved", **source_args, exist_ok=True) + definition = original.definition + version = original.table.version + source.add([{"id": 2}]) + if background: + job = db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + job.wait() + kept = db.open_materialized_view("saved") + else: + kept = db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert kept.definition.query == definition.query + assert kept.table.version == version + assert kept.table.to_arrow().to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + db.create_materialized_view("saved", **source_args) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 1ea0c1cb9..13950a39c 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -197,6 +197,7 @@ def test_sync_remote_create_uses_public_async_connection(query): where=None, limit=None, with_no_data=False, + exist_ok=False, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, ): @@ -729,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options "filter": None, "limit": None, "with_no_data": False, + "exist_ok": False, "auto_refresh_enabled": options.get("auto_refresh_enabled"), "auto_refresh_interval_seconds": options.get( "auto_refresh_interval_seconds" diff --git a/python/src/connection.rs b/python/src/connection.rs index 8763822cc..1a171032c 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -507,7 +507,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -519,6 +519,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -529,7 +530,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -552,7 +553,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -564,6 +565,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -574,7 +576,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 9920cd893..4b2a61f2c 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -287,6 +287,8 @@ pub struct MaterializedViewInfo { #[doc(hidden)] #[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { + /// Preserve an existing materialized view without refreshing it. + pub exist_ok: bool, /// Name of the new view. pub name: String, /// Namespace in which to create the view. @@ -1586,6 +1588,7 @@ pub struct CreateMaterializedViewBuilder { filter: Option, limit: Option, with_no_data: bool, + exist_ok: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, } @@ -1626,6 +1629,7 @@ impl CreateMaterializedViewBuilder { filter: None, limit: None, with_no_data: false, + exist_ok: false, auto_refresh_enabled: None, auto_refresh_interval_seconds: None, } @@ -1678,6 +1682,35 @@ impl CreateMaterializedViewBuilder { self } + /// Preserve an existing view's definition, data and refresh settings. + /// Defaults to false. A skipped creation does not refresh the view. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("saved", "source").exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + async fn existing_view(&self) -> Result> { + match self + .connection + .open_table(&self.name) + .namespace(self.namespace.clone()) + .execute() + .await + { + Ok(table) => MaterializedView::from_table(table).await.map(Some), + Err(Error::TableNotFound { .. }) => Ok(None), + Err(error) => Err(error), + } + } + /// Enable or disable automatic refresh in LanceDB Enterprise. /// When omitted, the server determines whether automatic refresh is enabled. /// LanceDB Embedded does not support automatic refresh. @@ -1759,6 +1792,7 @@ impl CreateMaterializedViewBuilder { .connection .database() .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: self.exist_ok, name: self.name.clone(), namespace_path: self.namespace.clone(), query: self.query()?, @@ -1793,6 +1827,11 @@ impl CreateMaterializedViewBuilder { async fn execute_native(self) -> Result { crate::require_experimental_functions()?; + if self.exist_ok + && let Some(view) = self.existing_view().await? + { + return Ok(view); + } if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires LanceDB Enterprise" @@ -1826,7 +1865,15 @@ impl CreateMaterializedViewBuilder { prepare_definition(&source, definition).await? } }; - let view = prepared.create_in(&self.namespace, &self.name).await?; + let view = match prepared.create_in(&self.namespace, &self.name).await { + Ok(view) => view, + Err(Error::TableAlreadyExists { .. }) if self.exist_ok => { + return self.existing_view().await?.ok_or_else(|| Error::Runtime { + message: "materialized view disappeared after concurrent creation".into(), + }); + } + Err(error) => return Err(error), + }; if !self.with_no_data { view.refresh().execute().await?; } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 300cd6b09..7100e1b04 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -803,16 +803,24 @@ impl Database for RemoteDatabase { } else { format!(" WITH ({})", options.join(", ")) }; + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let submission = client .submit_materialized_view_job( format!( - "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + "CREATE MATERIALIZED VIEW{if_not_exists} \"{name}\"{options} AS {}", request.query ), request.namespace_path, ) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Ok(Job::new_done()) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new(Box::new(RemoteJob::new( @@ -4865,6 +4873,7 @@ mod tests { for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { let result = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec![], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index 4eaad5156..e982afac7 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -39,6 +39,7 @@ fn strings(batch: &RecordBatch, name: &str) -> Result> { } pub(in crate::remote) enum MaterializedViewJobSubmission { + AlreadyExists, Registry { job_id: String }, Query(Arc), } @@ -66,6 +67,7 @@ impl SqlClient { let mut reader: SendableRecordBatchStream = query.reader().await?; let mut rows = 0; let mut registry_job_id = None; + let mut already_exists = false; while let Some(batch) = reader.try_next().await? { rows += batch.num_rows(); if rows > 1 { @@ -74,6 +76,16 @@ impl SqlClient { .into(), }); } + if let Some(column) = batch.column_by_name("status") { + let values = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + already_exists = + values.len() == 1 && !values.is_null(0) && values.value(0) == "already_exists"; + } if let Some(column) = batch.column_by_name("job_id") { let values = column .as_any() @@ -100,6 +112,9 @@ impl SqlClient { message: "materialized-view submission must return exactly one status row".into(), }); } + if already_exists && registry_job_id.is_none() { + return Ok(MaterializedViewJobSubmission::AlreadyExists); + } let job_id = registry_job_id.ok_or_else(|| Error::Runtime { message: "server acknowledged an early materialized-view handle but returned no job_id" .into(), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index e1780f118..1c39eda19 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1220,6 +1220,7 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { ] { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1302,6 +1303,7 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1329,6 +1331,63 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry_job() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let statement = "CREATE MATERIALIZED VIEW IF NOT EXISTS \"adults\" AS SELECT * FROM people"; + service.result_overrides.lock().unwrap().insert( + statement.into(), + RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec!["already_exists"])) as arrow_array::ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![""])) as arrow_array::ArrayRef, + ), + ]) + .unwrap(), + ); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!( + "a skipped creation must not poll a registry job: {}", + request.url() + ); + }) + .with_sql_client(client); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: true, + name: "adults".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + if defer { + assert!(job.id().is_none()); + } else { + assert_eq!(job.job_type().as_deref(), Some("query")); + } + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert_eq!(*statements.lock().unwrap(), [statement]); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { @@ -1394,6 +1453,7 @@ async fn remote_create_registry_handle_reopens_describes_and_cancels() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 9b64ab56d..f4e5c1e4a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2658,6 +2658,13 @@ impl BaseTable for RemoteTable { .submit_materialized_view_job(statement, self.namespace.clone()) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Err(Error::Runtime { + message: + "REFRESH MATERIALIZED VIEW returned a create-only already_exists status" + .into(), + }) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new_typed(Box::new(MaterializedViewRefreshJob { From f6311ae7e9c34ab8fc5067282fec864bd9f3a558 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:50 -0800 Subject: [PATCH 9/9] feat: support exist_ok for index creation (#4993) --- docs/web/sql/ddl/index.mdx | 40 +++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/remote/table.py | 10 ++ python/python/lancedb/table.py | 71 ++++++++- python/python/tests/test_index.py | 42 ++++++ python/python/tests/test_remote_db.py | 52 +++++++ python/python/tests/test_table.py | 96 ++++++++++++ python/python/tests/test_table_signatures.py | 6 +- python/src/table.rs | 10 +- rust/lancedb/src/index.rs | 17 +++ rust/lancedb/src/remote/table.rs | 42 +++++- rust/lancedb/src/table.rs | 8 +- rust/lancedb/src/table/create_index.rs | 146 ++++++++++++++++++- 13 files changed, 525 insertions(+), 17 deletions(-) diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index 425af7376..035424b5f 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -38,6 +38,46 @@ runs as `create_` followed by the algorithm instead. See [Incremental Indexing](/indexing/incremental-indexing). +{/* Draft for the index exist_ok release. + +```sql +CREATE INDEX IF NOT EXISTS text_search ON documents USING fts (text) +``` + +Use `IF NOT EXISTS` to preserve the existing index with the same name. Without an +explicit name, the name is derived from the column (`title_idx`, or +`title_list_element_idx` for list-element FTS). Existing definitions and builds +are kept, even when the new request specifies different settings. + +The Python SDK exposes the same behavior through `exist_ok=True` on +`create_index` and `create_index_async`, including scalar and FTS wrappers. +This option takes precedence over `replace`, whose default behavior is unchanged. + +```python +from lancedb.index import BTree + +table.create_index("title", config=BTree(), name="title_idx", exist_ok=True) +``` + +```rust +use lancedb::index::Index; + +table.create_index(&["title"], Index::BTree(Default::default())) + .name("title_idx".to_string()) + .exist_ok(true) + .execute() + .await?; +``` + +The SDK option is available in Python and Rust. TypeScript support is a separate +follow-up. Remote use requires a server that supports the option. + +An existing background build continues running. A completed submission handle +for a skipped creation does not wait for that build; use `wait_for_index` when +its completion is required. + +*/} + ## DROP INDEX {#drop} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index e3f00557c..cbc62f772 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -591,6 +591,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ): ... async def create_index_async( self, @@ -615,6 +616,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ) -> Job: ... async def list_versions(self) -> List[Dict[str, Any]]: ... async def version(self) -> int: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6730e6694..dbfd127ee 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -369,6 +369,7 @@ class RemoteTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -395,6 +396,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -433,6 +435,7 @@ class RemoteTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -492,6 +495,7 @@ class RemoteTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -516,6 +520,7 @@ class RemoteTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -541,6 +546,7 @@ class RemoteTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -572,6 +578,7 @@ class RemoteTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -675,6 +682,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -690,6 +698,7 @@ class RemoteTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -702,6 +711,7 @@ class RemoteTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5f0af7a66..e0b96e476 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -168,6 +168,36 @@ def _validate_index_accelerator(accelerator: Any) -> None: raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err +def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options): + if exist_ok: + parts = _parse_field_path(options["column"]) + default_name = ".".join(parts) + if any("." in part for part in parts): + default_name = ".".join( + "`" + part.replace("`", "``") + "`" + if any( + not character.isalnum() and character != "_" for character in part + ) + else part + for part in parts + ) + name = name or f"{default_name}_idx" + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + options["replace"] = False + options["name"] = name + _validate_index_accelerator(options.get("accelerator")) + try: + dataset.create_index(**options) + except Exception: + if exist_ok: + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + raise + + def _polars_predicate_pushdown_barrier(frame: Any) -> Any: """Return a Polars frame unchanged while blocking predicate pushdown.""" return frame @@ -1834,6 +1864,7 @@ class Table(ABC): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -1859,6 +1890,7 @@ class Table(ABC): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -1890,6 +1922,7 @@ class Table(ABC): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -1913,6 +1946,9 @@ class Table(ABC): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional LanceDB Enterprise only: how long to wait for the index build to finish. If not set, the call returns once the build is scheduled. @@ -1968,6 +2004,7 @@ class Table(ABC): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -2060,6 +2097,7 @@ class Table(ABC): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -2144,6 +2182,7 @@ class Table(ABC): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on the table. @@ -4318,6 +4357,7 @@ class LanceTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -4343,6 +4383,7 @@ class LanceTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -4374,6 +4415,7 @@ class LanceTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -4397,6 +4439,9 @@ class LanceTable(Table): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional Timeout to wait for async indexing to complete. name : str, optional @@ -4465,8 +4510,10 @@ class LanceTable(Table): # Handle accelerator through pylance if accelerator is not None: dataset = self.to_lance() - _validate_index_accelerator(accelerator) - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=index_type, metric=metric, @@ -4492,7 +4539,6 @@ class LanceTable(Table): if acc is not None: # Dispatch to pylance for GPU acceleration dataset = self.to_lance() - _validate_index_accelerator(acc) index_type_map = { "IvfFlat": "IVF_FLAT", "IvfSq": "IVF_SQ", @@ -4509,7 +4555,10 @@ class LanceTable(Table): if num_bits is not None: quantization_kwargs["num_bits"] = num_bits - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=lance_index_type, metric=getattr(config, "distance_type", "l2"), @@ -4531,6 +4580,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4546,6 +4596,7 @@ class LanceTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -4564,6 +4615,7 @@ class LanceTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4684,6 +4736,7 @@ class LanceTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -4710,6 +4763,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4747,6 +4801,7 @@ class LanceTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -4808,6 +4863,7 @@ class LanceTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -6806,6 +6862,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ): """Create an index to speed up queries @@ -6836,6 +6893,9 @@ class AsyncTable: If not set, the call returns once the build is scheduled. name: str, optional The name of the index. If not provided, a default name will be generated. + exist_ok: bool, default False + Preserve an existing index with the requested or derived name. This + takes precedence over replace and keeps its definition and build. train: bool, default True Whether to train the index with existing data. Vector indices always train with existing data. @@ -6891,6 +6951,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, @@ -6928,6 +6989,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> AsyncJob: """Create an index, returning a handle to the indexing job. @@ -6946,6 +7008,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 738a791ad..e658d18e1 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values(): set(get_args(get_type_hints(IndexStatistics)["index_type"])) == expected_index_types ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))] +) +async def test_index_exist_ok_preserves_existing_index( + some_table, background, column, config +): + await some_table.create_index(column, config=config, exist_ok=True) + version = await some_table.version() + original = await some_table.list_indices() + if background: + job = await some_table.create_index_async( + column, config=config, replace=True, exist_ok=True + ) + await job.wait() + else: + await some_table.create_index( + column, config=config, replace=True, exist_ok=True + ) + assert await some_table.version() == version + assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [ + (i.name, i.index_type) for i in original + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +async def test_named_index_exist_ok_checks_before_column_validation( + some_table, background +): + await some_table.create_index("id", config=BTree(), name="kept") + version = await some_table.version() + method = some_table.create_index_async if background else some_table.create_index + result = await method("missing", config=BTree(), name="kept", exist_ok=True) + if background: + assert result.id is None + await result.wait() + assert await some_table.version() == version + assert [index.name for index in await some_table.list_indices()] == ["kept"] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ca2516fda..ea7f73c71 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -45,6 +45,7 @@ from lancedb.query import ( LanceVectorQueryBuilder, MatchQuery, ) +from lancedb.index import BTree from lancedb.remote import ClientConfig from lancedb.remote.errors import ( AlreadyExistsError, @@ -7420,3 +7421,54 @@ async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnati if use_async: await result assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("kwargs", [{}, {"exist_ok": False}, {"exist_ok": True}]) +async def test_remote_index_exist_ok_wire(is_async, background, kwargs): + received = [] + + def handler(request): + parsed = urlparse(request.path) + body = request.rfile.read(int(request.headers.get("Content-Length", 0))) + if parsed.path.endswith("/create_index/"): + received.append((parse_qs(parsed.query), json.loads(body))) + payload = {} + elif parsed.path.endswith("/describe/"): + payload = dict( + version=1, + schema=dict( + fields=[dict(name="id", type={"type": "int64"}, nullable=False)] + ), + ) + elif parsed.path.endswith("/create/"): + payload = {} + else: + raise AssertionError(request.path) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + method = "create_index_async" if background else "create_index" + if is_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.create_table("test", [{"id": 1}]) + result = await getattr(table, method)("id", config=BTree(), **kwargs) + if background: + await result.wait() + else: + with mock_lancedb_connection(handler) as db: + table = db.create_table("test", [{"id": 1}]) + result = getattr(table, method)("id", config=BTree(), **kwargs) + if background: + result.wait() + query, body = received[0] + assert query == ({"exist_ok": ["true"]} if kwargs.get("exist_ok") else {}) + assert "exist_ok" not in body + if kwargs.get("exist_ok"): + assert body["replace"] is False + else: + assert "replace" not in body diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e3b69ced1..604d6afb3 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1837,6 +1837,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Test with target_partition_size @@ -1862,6 +1863,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # target_partition_size has a default value, @@ -1886,6 +1888,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1902,6 +1905,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1922,6 +1926,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1942,6 +1947,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -2073,6 +2079,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_custom_index", train=True, + exist_ok=False, ) # Test with train=False @@ -2084,6 +2091,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name=None, train=False, + exist_ok=False, ) # Test with both name and train @@ -2095,6 +2103,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_index_name", train=True, + exist_ok=False, ) @@ -2132,6 +2141,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Scalar index via new API @@ -2143,6 +2153,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # FTS index via new API @@ -2154,6 +2165,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -6292,3 +6304,87 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): metadata = (await table.schema()).field("doubled").metadata assert metadata[b"computed_column.auto_refresh_enabled"] == b"true" assert b"computed_column.auto_refresh_interval_seconds" not in metadata + + +@pytest.mark.parametrize( + "method", + ["create_index", "create_index_async", "create_scalar_index", "create_fts_index"], +) +@pytest.mark.parametrize("name", [None, "kept_index"]) +def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name): + table = mem_db.create_table( + "keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)] + ) + column = "text" if method == "create_fts_index" else "id" + config = FTS() if column == "text" else BTree() + table.create_index(column, config=config, name=name, exist_ok=True) + before = table.version + original = table.list_indices() + kwargs = dict(name=name, exist_ok=True) + if method in ("create_index", "create_index_async"): + kwargs["config"] = config + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result = getattr(table, method)(column, **kwargs) + if method == "create_index_async": + result.wait() + assert table.version == before + assert [(index.name, index.index_type) for index in table.list_indices()] == [ + (index.name, index.index_type) for index in original + ] + with pytest.raises((ValueError, RuntimeError), match="already exists"): + table.create_index(column, config=config, name=name, replace=False) + table.create_index(column, config=config, name=name) + assert table.version > before + + +@pytest.mark.parametrize( + "column,name,existing", + [ + ("vector", "kept", "kept"), + ("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"), + ], +) +def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing): + dataset = MagicMock() + dataset.list_indices.return_value = [{"name": existing}] + with patch("lancedb.table._validate_index_accelerator") as validate: + table_module._create_accelerated_index( + dataset, column=column, accelerator="cuda", name=name, exist_ok=True + ) + validate.assert_not_called() + dataset.create_index.assert_not_called() + + +def test_accelerated_index_exist_ok_preserves_concurrent_winner(): + dataset = MagicMock() + dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]] + dataset.create_index.side_effect = RuntimeError("concurrent create") + with patch("lancedb.table._validate_index_accelerator"): + table_module._create_accelerated_index( + dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True + ) + assert dataset.create_index.call_args.kwargs["replace"] is False + assert dataset.create_index.call_args.kwargs["name"] == "vector_idx" + + +@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"]) +def test_index_exist_ok_matches_lance_default_name(mem_db, column): + table = mem_db.create_table( + "quoted_index", + [{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}], + ) + table.create_index(column, config=BTree()) + before = table.version + table.create_index(column, config=BTree(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 + + +def test_fts_exist_ok_matches_quoted_default_name(mem_db): + table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}]) + table.create_index("`body-text`", config=FTS()) + before = table.version + table.create_index("`body-text`", config=FTS(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 387a89f31..41a688068 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table): }.items(): assert getattr(config, name) == value assert kwargs == dict( - wait_timeout=timeout, name="custom_idx", replace=False, train=False + wait_timeout=timeout, + name="custom_idx", + replace=False, + train=False, + exist_ok=False, ) diff --git a/python/src/table.rs b/python/src/table.rs index 31cf8d25c..f77ff5a7f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1628,7 +1628,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index<'a>( self_: PyRef<'a, Self>, column: String, @@ -1637,6 +1638,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1645,6 +1647,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } @@ -1661,7 +1664,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index_async<'a>( self_: PyRef<'a, Self>, column: String, @@ -1670,6 +1674,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1678,6 +1683,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 87eff864d..91c941154 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -220,6 +220,7 @@ pub struct IndexBuilder { pub(crate) index: Index, pub(crate) columns: Vec, pub(crate) replace: bool, + pub(crate) exist_ok: bool, pub(crate) wait_timeout: Option, pub(crate) train: bool, pub(crate) name: Option, @@ -232,6 +233,7 @@ impl IndexBuilder { index, columns, replace: true, + exist_ok: false, train: true, wait_timeout: None, name: None, @@ -324,6 +326,21 @@ impl IndexBuilder { self } + /// Preserve an existing index with the requested name. Defaults to false. + /// This takes precedence over `replace`; a skipped creation does not rebuild. + /// + /// ```no_run + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// table.create_index(&["id"], lancedb::index::Index::Auto) + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Duration of time to wait for asynchronous indexing to complete. If not set, /// `create_index()` will not wait. /// diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f4e5c1e4a..a7cf3f80d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -701,9 +701,13 @@ impl RemoteTable { async fn submit_create_index(&self, mut index: IndexBuilder) -> Result> { self.check_mutable().await?; - let request = self + let mut request = self .client .post(&format!("/v1/table/{}/create_index/", self.identifier)); + if index.exist_ok { + request = request.query(&[("exist_ok", true)]); + index.replace = false; + } let column = match index.columns.len() { 0 => { @@ -18101,6 +18105,42 @@ mod tests { branch.restore().await.unwrap(); } + #[tokio::test] + async fn test_index_exist_ok_query_and_replacement_policy() { + for exist_ok in [false, true] { + for background in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/create_index/" => { + assert_eq!(request.url().query(), exist_ok.then_some("exist_ok=true")); + let body = request_body_json(&request); + assert_eq!( + body.get("replace"), + exist_ok.then_some(&serde_json::Value::Bool(false)) + ); + assert!(body.get("exist_ok").is_none()); + http::Response::builder() + .status(200) + .body("{}".into()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let builder = table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(exist_ok); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + } + } + } + #[tokio::test] async fn test_branch_create_index_carries_branch_in_body() { use lance::dataset::refs::Ref; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4959b2842..ff0ab8b94 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4145,14 +4145,18 @@ impl BaseTable for NativeTable { } async fn create_index(&self, opts: IndexBuilder) -> Result<()> { - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(()); + }; self.build_index(opts, prepared).await } async fn create_index_async(&self, opts: IndexBuilder) -> Result { // Prepare before spawning so bad input is reported by this call rather // than only by the job. - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(Job::new_done()); + }; let table = self.clone(); Ok(Job::spawned(tokio::spawn(async move { table.build_index(opts, prepared).await diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 5f9ae13b4..e0da64029 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -115,14 +115,24 @@ impl NativeTable { pub(super) async fn prepare_index( &self, opts: &crate::index::IndexBuilder, - ) -> Result { + ) -> Result> { + self.dataset.ensure_mutable()?; + let dataset = self.dataset.get().await?; + if opts.exist_ok + && let Some(name) = &opts.name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(None); + } if opts.columns.len() != 1 { return Err(Error::Schema { message: "Multi-column (composite) indices are not yet supported".to_string(), }); } - self.dataset.ensure_mutable()?; - let dataset = self.dataset.get().await?; let (column, field) = if let Index::FTS(params) = &opts.index { let resolved = resolve_lance_fts_field_path(dataset.schema(), &opts.columns[0])?; if params.get_document_granularity().is_list_element() && resolved.list_depth == 0 { @@ -137,9 +147,48 @@ impl NativeTable { } else { Self::resolve_index_field(dataset.schema(), &opts.columns[0])? }; + if let Some(name) = Self::guarded_index_name(opts, &column)? + && dataset + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(None); + } let params = self.make_index_params(&field, opts.index.clone()).await?; let index_type = self.get_index_type_for_field(&field, &opts.index); - Ok((column, params, index_type)) + Ok(Some((column, params, index_type))) + } + + fn guarded_index_name( + opts: &crate::index::IndexBuilder, + column: &str, + ) -> Result> { + let name = if opts.exist_ok { + Some(if let Some(name) = &opts.name { + name.clone() + } else { + let names = lance_core::datatypes::parse_field_path(column)?; + let default_name = if matches!(&opts.index, Index::FTS(_)) + || names.iter().any(|name| name.contains('.')) + { + column.to_string() + } else { + names.join(".") + }; + let suffix = if matches!(&opts.index, Index::FTS(params) if params.get_document_granularity().is_list_element()) + { + "_list_element_idx" + } else { + "_idx" + }; + format!("{default_name}{suffix}") + }) + } else { + None + }; + Ok(name) } /// Builds a prepared index and publishes the new dataset version. @@ -150,16 +199,42 @@ impl NativeTable { ) -> Result<()> { let (column, lance_idx_params, index_type) = prepared; let mut dataset = (*self.dataset.get().await?).clone(); + let guarded_name = Self::guarded_index_name(&opts, &column)?; + if let Some(name) = &guarded_name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(()); + } let columns = [column.as_str()]; let mut builder = dataset .create_index_builder(&columns, index_type, lance_idx_params.as_ref()) .train(opts.train) - .replace(opts.replace); + .replace(opts.replace && !opts.exist_ok); - if let Some(name) = opts.name { + if let Some(name) = guarded_name.clone().or(opts.name) { builder = builder.name(name); } - builder.await?; + if let Err(error) = builder.await { + if let Some(name) = guarded_name { + self.dataset.reload().await?; + if self + .dataset + .get() + .await? + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(()); + } + } + return Err(error.into()); + } // A writer already open was built before this index existed, so it has // to pick it up here or a read needing it is refused until it reopens. self.dataset @@ -568,6 +643,63 @@ mod tests { Ok(FixedSizeListArray::from(data)) } + #[tokio::test] + async fn test_concurrent_index_exist_ok_preserves_single_identity() { + let dir = tempdir().unwrap(); + let db = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("id", Int32, (0..512).collect::>())).unwrap(); + let table = db.create_table("t", batch).execute().await.unwrap(); + let second = db.open_table("t").execute().await.unwrap(); + let (left, right) = tokio::join!( + table + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute(), + second + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute() + ); + left.unwrap(); + right.unwrap(); + table.checkout_latest().await.unwrap(); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices.len(), 1); + let original_uuid = indices[0].uuid; + let version = table.version().await.unwrap(); + table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), version); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices[0].uuid, original_uuid); + } + #[tokio::test] async fn test_create_index() { use std::iter::repeat_with;