| 1 | use std::sync::Mutex; |
| 2 | |
| 3 | use lancedb::DistanceType; |
| 4 | use pyo3::{ |
| 5 | exceptions::{PyRuntimeError, PyValueError}, |
| 6 | pyfunction, PyResult, |
| 7 | }; |
| 8 | |
| 9 | /// A wrapper around a rust builder |
| 10 | /// |
| 11 | /// Rust builders are often implemented so that the builder methods |
| 12 | /// consume the builder and return a new one. This is not compatible |
| 13 | /// with the pyo3, which, being garbage collected, cannot easily obtain |
| 14 | /// ownership of an object. |
| 15 | /// |
| 16 | /// This wrapper converts the compile-time safety of rust into runtime |
| 17 | /// errors if any attempt to use the builder happens after it is consumed. |
| 18 | pub struct BuilderWrapper<T> { |
| 19 | name: String, |
| 20 | inner: Mutex<Option<T>>, |
| 21 | } |
| 22 | |
| 23 | impl<T> BuilderWrapper<T> { |
| 24 | pub fn new(name: impl AsRef<str>, inner: T) -> Self { |
| 25 | Self { |
| 26 | name: name.as_ref().to_string(), |
| 27 | inner: Mutex::new(Some(inner)), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub fn consume<O>(&self, mod_fn: impl FnOnce(T) -> O) -> PyResult<O> { |
| 32 | let mut inner = self.inner.lock().unwrap(); |
| 33 | let inner_builder = inner.take().ok_or_else(|| { |
| 34 | PyRuntimeError::new_err(format!("{} has already been consumed", self.name)) |
| 35 | })?; |
| 36 | let result = mod_fn(inner_builder); |
| 37 | Ok(result) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | pub fn parse_distance_type(distance_type: impl AsRef<str>) -> PyResult<DistanceType> { |
| 42 | match distance_type.as_ref().to_lowercase().as_str() { |
| 43 | "l2" => Ok(DistanceType::L2), |
| 44 | "cosine" => Ok(DistanceType::Cosine), |
| 45 | "dot" => Ok(DistanceType::Dot), |
| 46 | _ => Err(PyValueError::new_err(format!( |
| 47 | "Invalid distance type '{}'. Must be one of l2, cosine, or dot", |
| 48 | distance_type.as_ref() |
| 49 | ))), |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[pyfunction] |
| 54 | pub fn validate_table_name(table_name: &str) -> PyResult<()> { |
| 55 | lancedb::utils::validate_table_name(table_name) |
| 56 | .map_err(|e| PyValueError::new_err(e.to_string())) |
| 57 | } |