mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
feat(sdk): support bound parameters in data prewarm (#5076)
Data prewarm methods accept filter expressions but cannot bind their
values, which forces applications to build literal SQL themselves. This
adds optional positional and named parameters to data-prewarm submission
and typed previews across Rust, Python, and TypeScript. Values use the
existing typed Arrow SQL transport and remain separate from the filter
text. Existing calls and job-handle behavior are preserved;
parameterized filters require a compatible LanceDB Enterprise server.
This was accomplished with the following changes:
- Add `PrewarmDataOptions::parameters(RecordBatch)` and forward the
batch through SQL submission and `EXPLAIN PREWARM` requests.
- Reuse Python's `QueryParameters` conversion for
synchronous/asynchronous, legacy/job-returning, and typed preview
methods.
- Add TypeScript positional-array, named-object, and explicit Arrow
parameter inputs, with safe scalar encoding and native IPC forwarding.
- Keep parameter values out of Rust option debug output and reject
invalid input before submission where possible.
- Add transport and codec regression tests, including injection-shaped
strings, typed Arrow values, legacy method forwarding, and typed preview
bindings.
- Document bound filters in the cache-prewarm guide with Python,
TypeScript, and Rust examples; update generic SQL parameter
documentation.
### Usage and behaviour
```python
job = table.prewarm_data_async(
["payload"], filter="id >= $minimum", parameters={"minimum": 1000}
)
job.wait()
```
```typescript
const job = await table.prewarmDataAsync({
columns: ["payload"], filter: "id >= $1", parameters: [1000],
});
await job.wait();
```
Python accepts a sequence, mapping, or one-row Arrow batch/table.
TypeScript accepts scalar arrays/objects or one-row Arrow input; safe
integers and bigint use Int64, fractional numbers use Float64. Rust
accepts a one-row Arrow batch. Parameters bind filter values, while
table identity, branch, and concurrency keep their existing interfaces.
Submission-only methods also forward bindings and retain their existing
return behavior. Typed preview helpers accept the same parameters
without creating a job.
### Testing
Python prewarm Flight transport tests pass (65 cases), Embedded
compatibility tests pass (6 cases), and focused Node parameter/prewarm
tests pass (45 cases, including ten codec and native-boundary cases).
Earlier matching-server verification passed 57 Python/SQL scenarios, 14
Node scenarios, and Rust SDK checks, covering selective and empty plans,
typed values, authorization, pinned branches, legacy methods, and
injection-shaped strings. A bound job also survives a full runtime
restart. The guide submission examples were also verified in Python,
TypeScript, and Rust; the TypeScript example type-checks. Live-server
checks used filesystem storage.
This commit is contained in:
@@ -381,7 +381,10 @@ impl ExecuteQueryAsyncBuilder {
|
||||
///
|
||||
/// Every placeholder needs a value and every parameter must be used by a
|
||||
/// placeholder. Parameters are supported in queries (`SELECT`, and
|
||||
/// `EXPLAIN` of one), not in DDL or DML, nor in table-function arguments.
|
||||
/// `EXPLAIN` of one) and, on compatible Enterprise servers, filter values in
|
||||
/// `PREWARM` and `EXPLAIN PREWARM`. Prewarm bindings must be scalars.
|
||||
/// Support for other statements depends on the server; table-function
|
||||
/// arguments do not accept parameters.
|
||||
/// Do not follow a named placeholder directly with `$`: `$a$` starts a
|
||||
/// dollar-quoted string.
|
||||
///
|
||||
|
||||
@@ -4789,7 +4789,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
.execute_prewarm(crate::database::ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: self.namespace.clone(),
|
||||
parameters: None,
|
||||
parameters: options.parameters,
|
||||
})
|
||||
.await
|
||||
.map_err(prewarm::map_error)?;
|
||||
@@ -4828,7 +4828,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
.execute_prewarm(crate::database::ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: self.namespace.clone(),
|
||||
parameters: None,
|
||||
parameters: options.parameters,
|
||||
})
|
||||
.await
|
||||
.map_err(prewarm::map_explain_error)?;
|
||||
|
||||
@@ -20,6 +20,14 @@ pub(super) fn statement(
|
||||
if options.concurrency == Some(0) {
|
||||
return Err(invalid("prewarm concurrency must be greater than 0"));
|
||||
}
|
||||
if let Some(parameters) = &options.parameters {
|
||||
if options.filter.is_none() {
|
||||
return Err(invalid("prewarm parameters require a filter"));
|
||||
}
|
||||
if parameters.num_rows() != 1 {
|
||||
return Err(invalid("prewarm parameters must contain exactly one row"));
|
||||
}
|
||||
}
|
||||
if let Some(filter) = &options.filter {
|
||||
if filter.trim().is_empty() {
|
||||
return Err(invalid("prewarm filter must not be empty"));
|
||||
@@ -293,6 +301,31 @@ mod tests {
|
||||
assert!(plan(&[batch(&valid), batch(&valid)]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bound_values_are_never_rendered_into_sql() {
|
||||
let value = "training' OR TRUE; DROP TABLE clips; --";
|
||||
let parameters = RecordBatch::try_from_iter(vec![(
|
||||
"tag",
|
||||
Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let options = PrewarmDataOptions::new()
|
||||
.filter("tag = $tag")
|
||||
.parameters(parameters);
|
||||
let sql = statement("clips", Some("experiment"), &options).unwrap();
|
||||
assert!(sql.ends_with("WHERE tag = $tag"));
|
||||
assert!(!sql.contains(value));
|
||||
assert!(!format!("{options:?}").contains(value));
|
||||
assert!(
|
||||
statement(
|
||||
"clips",
|
||||
None,
|
||||
&PrewarmDataOptions::new().parameters(options.parameters.unwrap())
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_paths_branch_and_filter_without_changing_options() {
|
||||
let options = PrewarmDataOptions::new()
|
||||
|
||||
@@ -3,22 +3,40 @@
|
||||
|
||||
//! Options, previews, and results for data-cache prewarm.
|
||||
|
||||
/// Data prewarm settings for [`super::Table::prewarm_data_async`].
|
||||
/// Data prewarm settings for [`super::Table::prewarm_data_async`] and
|
||||
/// [`super::Table::explain_prewarm_data`].
|
||||
///
|
||||
/// The table handle supplies the database, namespace, and branch. Omitted
|
||||
/// columns warm all fields. The filter selects conservative metadata ranges;
|
||||
/// it does not execute a row-filter scan or change the source data.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[derive(Clone, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct PrewarmDataOptions {
|
||||
/// Lance field paths, including nested paths such as `attrs.score`.
|
||||
pub columns: Vec<String>,
|
||||
/// An optional SQL predicate for metadata pruning.
|
||||
pub filter: Option<String>,
|
||||
/// One row of typed filter values. Column i binds `$<i + 1>` and a
|
||||
/// nonnumeric column name also binds `$name`. Requires server support.
|
||||
pub parameters: Option<arrow_array::RecordBatch>,
|
||||
/// Positive per-executor warming concurrency. Omit for the server default.
|
||||
pub concurrency: Option<u32>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PrewarmDataOptions {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PrewarmDataOptions")
|
||||
.field("columns", &self.columns)
|
||||
.field("filter", &self.filter)
|
||||
.field("concurrency", &self.concurrency)
|
||||
.field(
|
||||
"parameter_count",
|
||||
&self.parameters.as_ref().map(|batch| batch.num_columns()),
|
||||
)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl PrewarmDataOptions {
|
||||
/// Use server defaults and warm every column.
|
||||
pub fn new() -> Self {
|
||||
@@ -37,6 +55,25 @@ impl PrewarmDataOptions {
|
||||
self
|
||||
}
|
||||
|
||||
/// Bind scalar filter values without interpolating them into SQL text.
|
||||
///
|
||||
/// ```
|
||||
/// # use lancedb::table::PrewarmDataOptions;
|
||||
/// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
|
||||
/// # use std::sync::Arc;
|
||||
/// let values = RecordBatch::try_from_iter(vec![(
|
||||
/// "minimum", Arc::new(Int64Array::from(vec![100])) as ArrayRef,
|
||||
/// )]).unwrap();
|
||||
/// let options = PrewarmDataOptions::new()
|
||||
/// .columns(["payload"])
|
||||
/// .filter("id >= $minimum")
|
||||
/// .parameters(values);
|
||||
/// ```
|
||||
pub fn parameters(mut self, parameters: arrow_array::RecordBatch) -> Self {
|
||||
self.parameters = Some(parameters);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set positive per-executor warming concurrency.
|
||||
pub fn concurrency(mut self, concurrency: u32) -> Self {
|
||||
self.concurrency = Some(concurrency);
|
||||
|
||||
Reference in New Issue
Block a user