fix(sql)!: request JSON for view descriptions

Apply the reviewed view change.
This commit is contained in:
Jack Ye
2026-11-26 17:29:44 -08:00
committed by GitHub
parent 1c0118015c
commit a8971c1811
3 changed files with 157 additions and 12 deletions
+106
View File
@@ -154,6 +154,43 @@ pub(super) fn string_lists(batches: &[RecordBatch], name: &str) -> Result<Vec<St
Ok(values)
}
pub(in crate::remote) fn description<T: DeserializeOwned>(batches: Vec<RecordBatch>) -> Result<T> {
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
return Err(Error::Runtime {
message: "DESCRIBE FORMAT JSON must return exactly one document".into(),
});
}
for batch in &batches {
if batch.num_columns() != 1
|| batch
.schema()
.metadata()
.get("lancedb.describe.format")
.map(String::as_str)
!= Some("json")
|| batch
.column_by_name("description")
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
.is_none()
{
return Err(Error::Runtime { message: "DESCRIBE FORMAT JSON requires one UTF8 description column with JSON format metadata".into() });
}
}
let mut documents = strings(&batches, "description")?;
let document: serde_json::Value =
serde_json::from_str(&documents.remove(0)).map_err(|error| Error::Runtime {
message: format!("Invalid DESCRIBE JSON document: {error}"),
})?;
if !document.is_object() {
return Err(Error::Runtime {
message: "DESCRIBE FORMAT JSON requires an object document".into(),
});
}
serde_json::from_value(document).map_err(|error| Error::Runtime {
message: format!("Invalid DESCRIBE metadata: {error}"),
})
}
pub(super) fn definition<T: DeserializeOwned>(batches: Vec<RecordBatch>) -> Result<T> {
let values = strings(&batches, "definition")?;
let [value]: [String; 1] = values.try_into().map_err(|_| Error::Runtime {
@@ -275,3 +312,72 @@ mod tests {
assert!(string_lists(&[non_list], "warnings").is_err());
}
}
#[cfg(test)]
mod description_tests {
use super::*;
#[test]
fn descriptions_require_one_explicit_json_document() {
let document = serde_json::json!({"name":"saved", "schema":{"fields":[]}, "nullable":null});
let batch = RecordBatch::try_new(
Arc::new(
arrow_schema::Schema::new(vec![arrow_schema::Field::new(
"description",
arrow_schema::DataType::Utf8,
false,
)])
.with_metadata(std::collections::HashMap::from([(
"lancedb.describe.format".into(),
"json".into(),
)])),
),
vec![Arc::new(StringArray::from(vec![document.to_string()]))],
)
.unwrap();
assert_eq!(
description::<serde_json::Value>(vec![batch.clone()]).unwrap(),
document
);
assert!(description::<serde_json::Value>(vec![]).is_err());
assert!(description::<serde_json::Value>(vec![batch.clone(), batch.clone()]).is_err());
let invalid = RecordBatch::try_new(
batch.schema(),
vec![Arc::new(StringArray::from(vec!["View\nname: saved"]))],
)
.unwrap();
assert!(description::<serde_json::Value>(vec![invalid]).is_err());
let text = RecordBatch::try_new(
Arc::new(batch.schema().as_ref().clone().with_metadata(
std::collections::HashMap::from([(
"lancedb.describe.format".into(),
"text".into(),
)]),
)),
batch.columns().to_vec(),
)
.unwrap();
assert!(description::<serde_json::Value>(vec![text]).is_err());
for value in ["[]", "null", "1", "\"text\""] {
let scalar = RecordBatch::try_new(
batch.schema(),
vec![Arc::new(StringArray::from(vec![value]))],
)
.unwrap();
assert!(description::<serde_json::Value>(vec![scalar]).is_err());
}
let null = RecordBatch::try_new(
Arc::new(
arrow_schema::Schema::new(vec![arrow_schema::Field::new(
"description",
arrow_schema::DataType::Utf8,
true,
)])
.with_metadata(batch.schema().metadata().clone()),
),
vec![Arc::new(StringArray::from(vec![None::<&str>]))],
)
.unwrap();
assert!(description::<serde_json::Value>(vec![null]).is_err());
}
}
+33 -11
View File
@@ -1,7 +1,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use super::{SqlClient, materialized_view::quote_identifier, objects::strings};
use super::{
SqlClient,
materialized_view::quote_identifier,
objects::{description, strings},
};
use crate::{
database::ExecuteQueryRequest,
error::{Error, Result},
@@ -40,7 +44,7 @@ impl ViewDefinition {
}
}
fn view_description(
fn created_view_definition(
batches: Vec<arrow_array::RecordBatch>,
namespace: Vec<String>,
) -> Result<ViewDefinition> {
@@ -53,11 +57,29 @@ fn view_description(
}
Ok(values.remove(0))
};
let name = one("name")?;
let json: JsonArrowSchema =
serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime {
message: format!("View '{name}' has invalid schema JSON: {error}"),
})?;
let metadata = ViewMetadata {
name: one("name")?,
query: one("query")?,
schema: serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime {
message: format!("View metadata has invalid schema JSON: {error}"),
})?,
};
view_definition(metadata, namespace)
}
#[derive(serde::Deserialize)]
struct ViewMetadata {
name: String,
query: String,
schema: JsonArrowSchema,
}
fn view_definition(metadata: ViewMetadata, namespace: Vec<String>) -> Result<ViewDefinition> {
let ViewMetadata {
name,
query,
schema: json,
} = metadata;
let schema = lance_namespace::schema::convert_json_arrow_schema(&json).map_err(|error| {
Error::Runtime {
message: format!("View '{name}' has an undecodable schema: {error}"),
@@ -84,7 +106,7 @@ fn view_description(
Ok(ViewDefinition {
name,
namespace,
query: one("query")?,
query,
default_database,
default_namespace: default_namespace_path,
schema: json,
@@ -113,7 +135,7 @@ impl SqlClient {
parameters: None,
options: Default::default(),
},
move |batches| view_description(batches, namespace_path),
move |batches| created_view_definition(batches, namespace_path),
)
.await?
.wait()
@@ -130,12 +152,12 @@ impl SqlClient {
let namespace_path = namespace.to_vec();
self.object_job(
ExecuteQueryRequest {
query: format!("DESCRIBE VIEW {}", quote_identifier(name)),
query: format!("DESCRIBE VIEW {} FORMAT JSON", quote_identifier(name)),
default_namespace_path: namespace.to_vec(),
parameters: None,
options: Default::default(),
},
move |batches| view_description(batches, namespace_path),
move |batches| view_definition(description(batches)?, namespace_path),
)
.await?
.wait()
+18 -1
View File
@@ -765,6 +765,17 @@ impl FlightService for TestSqlService {
}
}
fn description_batch(document: serde_json::Value) -> RecordBatch {
let schema = Schema::new(vec![Field::new("description", DataType::Utf8, false)]).with_metadata(
HashMap::from([("lancedb.describe.format".into(), "json".into())]),
);
RecordBatch::try_new(
Arc::new(schema),
vec![Arc::new(StringArray::from(vec![document.to_string()]))],
)
.unwrap()
}
fn parameter_row() -> RecordBatch {
let vector = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
[Some([0.1_f32, 1e-45, -0.0].map(Some))],
@@ -4220,6 +4231,12 @@ async fn view_create_and_describe_return_metadata_through_sql() {
adaptive: true,
defer,
result,
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([(
"DESCRIBE VIEW \"adults\" FORMAT JSON".into(),
description_batch(
serde_json::json!({"name":"adults", "query":"SELECT name FROM people", "schema":serde_json::from_str::<serde_json::Value>(schema).unwrap()}),
),
)]))),
..Default::default()
};
let statements = service.statements.clone();
@@ -4256,7 +4273,7 @@ async fn view_create_and_describe_return_metadata_through_sql() {
[
"CREATE VIEW \"adults\" AS SELECT name FROM people",
"CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people",
"DESCRIBE VIEW \"adults\""
"DESCRIBE VIEW \"adults\" FORMAT JSON"
]
);
assert!(