Elffuss BraidHub

kikocis/lancedb public

feat(rust): remote endpoints for schema, version, count_rows (#1644)

A handful of additional endpoints.
Changeset02db75e6608ed208ce9fdb1edf97fc30f8d39fb480121134c7b06101f72d834d
AuthorWill Jones <willjones127@gmail.com> · 2024-09-16 08:19 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-16 08:19 -07:00
Parentsedcc3dc20a6e

Browse the files at this changeset

4 files changed

modified rust/lancedb/src/remote.rs +2 −0
@@ -21,3 +21,5 @@
2121 pub mod db;
2222 pub mod table;
2323 pub mod util;
24+
25+const ARROW_STREAM_CONTENT_TYPE: &str = "application/vnd.apache.arrow.stream";
modified rust/lancedb/src/remote/db.rs +1 −2
@@ -31,8 +31,7 @@
3131 use super::client::{HttpSend, RestfulLanceDbClient, Sender};
3232 use super::table::RemoteTable;
3333 use super::util::batches_to_ipc_bytes;
34-
35-const ARROW_STREAM_CONTENT_TYPE: &str = "application/vnd.apache.arrow.stream";
34+use super::ARROW_STREAM_CONTENT_TYPE;
3635
3736 #[derive(Deserialize)]
3837 struct ListTablesResponse {
modified rust/lancedb/src/remote/table.rs +193 −8
@@ -1,12 +1,16 @@
11 use std::sync::Arc;
22
33 use crate::table::dataset::DatasetReadGuard;
4+use crate::Error;
45 use arrow_array::RecordBatchReader;
56 use arrow_schema::SchemaRef;
67 use async_trait::async_trait;
78 use datafusion_physical_plan::ExecutionPlan;
9+use http::StatusCode;
10+use lance::arrow::json::JsonSchema;
811 use lance::dataset::scanner::{DatasetRecordBatchStream, Scanner};
912 use lance::dataset::{ColumnAlteration, NewColumnTransform};
13+use serde::Deserialize;
1014
1115 use crate::{
1216 connection::NoData,
@@ -32,6 +36,31 @@
3236 pub fn new(client: RestfulLanceDbClient<S>, name: String) -> Self {
3337 Self { client, name }
3438 }
39+
40+ async fn describe(&self) -> Result<TableDescription> {
41+ let request = self.client.post(&format!("/table/{}/describe/", self.name));
42+ let response = self.client.send(request).await?;
43+
44+ if response.status() == StatusCode::NOT_FOUND {
45+ return Err(Error::TableNotFound {
46+ name: self.name.clone(),
47+ });
48+ }
49+
50+ let response = self.client.check_response(response).await?;
51+
52+ let body = response.text().await?;
53+
54+ serde_json::from_str(&body).map_err(|e| Error::Http {
55+ message: format!("Failed to parse table description: {}", e),
56+ })
57+ }
58+}
59+
60+#[derive(Deserialize)]
61+struct TableDescription {
62+ version: u64,
63+ schema: JsonSchema,
3564 }
3665
3766 impl<S: HttpSend> std::fmt::Display for RemoteTable<S> {
@@ -40,6 +69,24 @@
4069 }
4170 }
4271
72+#[cfg(all(test, feature = "remote"))]
73+mod test_utils {
74+ use super::*;
75+ use crate::remote::client::test_utils::client_with_handler;
76+ use crate::remote::client::test_utils::MockSender;
77+
78+ impl RemoteTable<MockSender> {
79+ pub fn new_mock<F, T>(name: String, handler: F) -> Self
80+ where
81+ F: Fn(reqwest::Request) -> http::Response<T> + Send + Sync + 'static,
82+ T: Into<reqwest::Body>,
83+ {
84+ let client = client_with_handler(handler);
85+ Self { client, name }
86+ }
87+ }
88+}
89+
4390 #[async_trait]
4491 impl<S: HttpSend> TableInternal for RemoteTable<S> {
4592 fn as_any(&self) -> &dyn std::any::Any {
@@ -52,22 +99,53 @@
5299 &self.name
53100 }
54101 async fn version(&self) -> Result<u64> {
55- todo!()
102+ self.describe().await.map(|desc| desc.version)
56103 }
57104 async fn checkout(&self, _version: u64) -> Result<()> {
58- todo!()
105+ Err(Error::NotSupported {
106+ message: "checkout is not supported on LanceDB cloud.".into(),
107+ })
59108 }
60109 async fn checkout_latest(&self) -> Result<()> {
61- todo!()
110+ Err(Error::NotSupported {
111+ message: "checkout is not supported on LanceDB cloud.".into(),
112+ })
62113 }
63114 async fn restore(&self) -> Result<()> {
64- todo!()
115+ Err(Error::NotSupported {
116+ message: "restore is not supported on LanceDB cloud.".into(),
117+ })
65118 }
66119 async fn schema(&self) -> Result<SchemaRef> {
67- todo!()
68- }
69- async fn count_rows(&self, _filter: Option<String>) -> Result<usize> {
70- todo!()
120+ let schema = self.describe().await?.schema;
121+ Ok(Arc::new(schema.try_into()?))
122+ }
123+ async fn count_rows(&self, filter: Option<String>) -> Result<usize> {
124+ let mut request = self
125+ .client
126+ .post(&format!("/table/{}/count_rows/", self.name));
127+
128+ if let Some(filter) = filter {
129+ request = request.json(&serde_json::json!({ "filter": filter }));
130+ } else {
131+ request = request.json(&serde_json::json!({}));
132+ }
133+
134+ let response = self.client.send(request).await?;
135+
136+ if response.status() == StatusCode::NOT_FOUND {
137+ return Err(Error::TableNotFound {
138+ name: self.name.clone(),
139+ });
140+ }
141+
142+ let response = self.client.check_response(response).await?;
143+
144+ let body = response.text().await?;
145+
146+ serde_json::from_str(&body).map_err(|e| Error::Http {
147+ message: format!("Failed to parse row count: {}", e),
148+ })
71149 }
72150 async fn add(
73151 &self,
@@ -140,3 +218,110 @@
140218 todo!()
141219 }
142220 }
221+
222+#[cfg(test)]
223+mod tests {
224+ use super::*;
225+
226+ use arrow_schema::{DataType, Field, Schema};
227+ use futures::{future::BoxFuture, TryFutureExt};
228+
229+ use crate::{Error, Table};
230+
231+ #[tokio::test]
232+ async fn test_not_found() {
233+ let table = Table::new_with_handler("my_table", |_| {
234+ http::Response::builder()
235+ .status(404)
236+ .body("table my_table not found")
237+ .unwrap()
238+ });
239+
240+ // All endpoints should translate 404 to TableNotFound.
241+ let results: Vec<BoxFuture<'_, Result<()>>> = vec![
242+ Box::pin(table.version().map_ok(|_| ())),
243+ Box::pin(table.schema().map_ok(|_| ())),
244+ Box::pin(table.count_rows(None).map_ok(|_| ())),
245+ // TODO: other endpoints.
246+ ];
247+
248+ for result in results {
249+ let result = result.await;
250+ assert!(result.is_err());
251+ assert!(matches!(result, Err(Error::TableNotFound { name }) if name == "my_table"));
252+ }
253+ }
254+
255+ #[tokio::test]
256+ async fn test_version() {
257+ let table = Table::new_with_handler("my_table", |request| {
258+ assert_eq!(request.method(), "POST");
259+ assert_eq!(request.url().path(), "/table/my_table/describe/");
260+
261+ http::Response::builder()
262+ .status(200)
263+ .body(r#"{"version": 42, "schema": { "fields": [] }}"#)
264+ .unwrap()
265+ });
266+
267+ let version = table.version().await.unwrap();
268+ assert_eq!(version, 42);
269+ }
270+
271+ #[tokio::test]
272+ async fn test_schema() {
273+ let table = Table::new_with_handler("my_table", |request| {
274+ assert_eq!(request.method(), "POST");
275+ assert_eq!(request.url().path(), "/table/my_table/describe/");
276+
277+ http::Response::builder()
278+ .status(200)
279+ .body(
280+ r#"{"version": 42, "schema": {"fields": [
281+ {"name": "a", "type": { "type": "int32" }, "nullable": false},
282+ {"name": "b", "type": { "type": "string" }, "nullable": true}
283+ ], "metadata": {"key": "value"}}}"#,
284+ )
285+ .unwrap()
286+ });
287+
288+ let expected = Arc::new(
289+ Schema::new(vec![
290+ Field::new("a", DataType::Int32, false),
291+ Field::new("b", DataType::Utf8, true),
292+ ])
293+ .with_metadata([("key".into(), "value".into())].into()),
294+ );
295+
296+ let schema = table.schema().await.unwrap();
297+ assert_eq!(schema, expected);
298+ }
299+
300+ #[tokio::test]
301+ async fn test_count_rows() {
302+ let table = Table::new_with_handler("my_table", |request| {
303+ assert_eq!(request.method(), "POST");
304+ assert_eq!(request.url().path(), "/table/my_table/count_rows/");
305+ assert_eq!(request.body().unwrap().as_bytes().unwrap(), br#"{}"#);
306+
307+ http::Response::builder().status(200).body("42").unwrap()
308+ });
309+
310+ let count = table.count_rows(None).await.unwrap();
311+ assert_eq!(count, 42);
312+
313+ let table = Table::new_with_handler("my_table", |request| {
314+ assert_eq!(request.method(), "POST");
315+ assert_eq!(request.url().path(), "/table/my_table/count_rows/");
316+ assert_eq!(
317+ request.body().unwrap().as_bytes().unwrap(),
318+ br#"{"filter":"a > 10"}"#
319+ );
320+
321+ http::Response::builder().status(200).body("42").unwrap()
322+ });
323+
324+ let count = table.count_rows(Some("a > 10".into())).await.unwrap();
325+ assert_eq!(count, 42);
326+ }
327+}
modified rust/lancedb/src/table.rs +25 −0
@@ -428,6 +428,31 @@
428428 embedding_registry: Arc<dyn EmbeddingRegistry>,
429429 }
430430
431+#[cfg(all(test, feature = "remote"))]
432+mod test_utils {
433+ use super::*;
434+
435+ impl Table {
436+ pub fn new_with_handler<T>(
437+ name: impl Into<String>,
438+ handler: impl Fn(reqwest::Request) -> http::Response<T> + Clone + Send + Sync + 'static,
439+ ) -> Self
440+ where
441+ T: Into<reqwest::Body>,
442+ {
443+ let inner = Arc::new(crate::remote::table::RemoteTable::new_mock(
444+ name.into(),
445+ handler,
446+ ));
447+ Self {
448+ inner,
449+ // Registry is unused.
450+ embedding_registry: Arc::new(MemoryRegistry::new()),
451+ }
452+ }
453+ }
454+}
455+
431456 impl std::fmt::Display for Table {
432457 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433458 write!(f, "{}", self.inner)