| 1 | use arrow::{ |
| 2 | ffi_stream::ArrowArrayStreamReader, |
| 3 | pyarrow::{FromPyArrow, ToPyArrow}, |
| 4 | }; |
| 5 | use lancedb::table::{ |
| 6 | AddDataMode, Duration, OptimizeAction, OptimizeOptions, Table as LanceDbTable, |
| 7 | }; |
| 8 | use pyo3::{ |
| 9 | exceptions::{PyRuntimeError, PyValueError}, |
| 10 | pyclass, pymethods, |
| 11 | types::{PyDict, PyDictMethods, PyString}, |
| 12 | Bound, FromPyObject, PyAny, PyRef, PyResult, Python, ToPyObject, |
| 13 | }; |
| 14 | use pyo3_asyncio_0_21::tokio::future_into_py; |
| 15 | |
| 16 | use crate::{ |
| 17 | error::PythonErrorExt, |
| 18 | index::{Index, IndexConfig}, |
| 19 | query::Query, |
| 20 | }; |
| 21 | |
| 22 | /// Statistics about a compaction operation. |
| 23 | #[pyclass(get_all)] |
| 24 | #[derive(Clone, Debug)] |
| 25 | pub struct CompactionStats { |
| 26 | /// The number of fragments removed |
| 27 | pub fragments_removed: u64, |
| 28 | /// The number of new, compacted fragments added |
| 29 | pub fragments_added: u64, |
| 30 | /// The number of data files removed |
| 31 | pub files_removed: u64, |
| 32 | /// The number of new, compacted data files added |
| 33 | pub files_added: u64, |
| 34 | } |
| 35 | |
| 36 | /// Statistics about a cleanup operation |
| 37 | #[pyclass(get_all)] |
| 38 | #[derive(Clone, Debug)] |
| 39 | pub struct RemovalStats { |
| 40 | /// The number of bytes removed |
| 41 | pub bytes_removed: u64, |
| 42 | /// The number of old versions removed |
| 43 | pub old_versions_removed: u64, |
| 44 | } |
| 45 | |
| 46 | /// Statistics about an optimize operation |
| 47 | #[pyclass(get_all)] |
| 48 | #[derive(Clone, Debug)] |
| 49 | pub struct OptimizeStats { |
| 50 | /// Statistics about the compaction operation |
| 51 | pub compaction: CompactionStats, |
| 52 | /// Statistics about the removal operation |
| 53 | pub prune: RemovalStats, |
| 54 | } |
| 55 | |
| 56 | #[pyclass] |
| 57 | pub struct Table { |
| 58 | // We keep a copy of the name to use if the inner table is dropped |
| 59 | name: String, |
| 60 | inner: Option<LanceDbTable>, |
| 61 | } |
| 62 | |
| 63 | #[pymethods] |
| 64 | impl OptimizeStats { |
| 65 | pub fn __repr__(&self) -> String { |
| 66 | format!( |
| 67 | "OptimizeStats(compaction={:?}, prune={:?})", |
| 68 | self.compaction, self.prune |
| 69 | ) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | impl Table { |
| 74 | pub(crate) fn new(inner: LanceDbTable) -> Self { |
| 75 | Self { |
| 76 | name: inner.name().to_string(), |
| 77 | inner: Some(inner), |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | impl Table { |
| 83 | fn inner_ref(&self) -> PyResult<&LanceDbTable> { |
| 84 | self.inner |
| 85 | .as_ref() |
| 86 | .ok_or_else(|| PyRuntimeError::new_err(format!("Table {} is closed", self.name))) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | #[pymethods] |
| 91 | impl Table { |
| 92 | pub fn name(&self) -> String { |
| 93 | self.name.clone() |
| 94 | } |
| 95 | |
| 96 | pub fn is_open(&self) -> bool { |
| 97 | self.inner.is_some() |
| 98 | } |
| 99 | |
| 100 | pub fn close(&mut self) { |
| 101 | self.inner.take(); |
| 102 | } |
| 103 | |
| 104 | pub fn schema(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 105 | let inner = self_.inner_ref()?.clone(); |
| 106 | future_into_py(self_.py(), async move { |
| 107 | let schema = inner.schema().await.infer_error()?; |
| 108 | Python::with_gil(|py| schema.to_pyarrow(py)) |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | pub fn add<'a>( |
| 113 | self_: PyRef<'a, Self>, |
| 114 | data: Bound<'_, PyAny>, |
| 115 | mode: String, |
| 116 | ) -> PyResult<Bound<'a, PyAny>> { |
| 117 | let batches = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; |
| 118 | let mut op = self_.inner_ref()?.add(batches); |
| 119 | if mode == "append" { |
| 120 | op = op.mode(AddDataMode::Append); |
| 121 | } else if mode == "overwrite" { |
| 122 | op = op.mode(AddDataMode::Overwrite); |
| 123 | } else { |
| 124 | return Err(PyValueError::new_err(format!("Invalid mode: {}", mode))); |
| 125 | } |
| 126 | |
| 127 | future_into_py(self_.py(), async move { |
| 128 | op.execute().await.infer_error()?; |
| 129 | Ok(()) |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | pub fn delete(self_: PyRef<'_, Self>, condition: String) -> PyResult<Bound<'_, PyAny>> { |
| 134 | let inner = self_.inner_ref()?.clone(); |
| 135 | future_into_py(self_.py(), async move { |
| 136 | inner.delete(&condition).await.infer_error() |
| 137 | }) |
| 138 | } |
| 139 | |
| 140 | pub fn update<'a>( |
| 141 | self_: PyRef<'a, Self>, |
| 142 | updates: &PyDict, |
| 143 | r#where: Option<String>, |
| 144 | ) -> PyResult<Bound<'a, PyAny>> { |
| 145 | let mut op = self_.inner_ref()?.update(); |
| 146 | if let Some(only_if) = r#where { |
| 147 | op = op.only_if(only_if); |
| 148 | } |
| 149 | for (column_name, value) in updates.into_iter() { |
| 150 | let column_name: &PyString = column_name.downcast()?; |
| 151 | let column_name = column_name.to_str()?.to_string(); |
| 152 | let value: &PyString = value.downcast()?; |
| 153 | let value = value.to_str()?.to_string(); |
| 154 | op = op.column(column_name, value); |
| 155 | } |
| 156 | future_into_py(self_.py(), async move { |
| 157 | op.execute().await.infer_error()?; |
| 158 | Ok(()) |
| 159 | }) |
| 160 | } |
| 161 | |
| 162 | pub fn count_rows( |
| 163 | self_: PyRef<'_, Self>, |
| 164 | filter: Option<String>, |
| 165 | ) -> PyResult<Bound<'_, PyAny>> { |
| 166 | let inner = self_.inner_ref()?.clone(); |
| 167 | future_into_py(self_.py(), async move { |
| 168 | inner.count_rows(filter).await.infer_error() |
| 169 | }) |
| 170 | } |
| 171 | |
| 172 | pub fn create_index<'a>( |
| 173 | self_: PyRef<'a, Self>, |
| 174 | column: String, |
| 175 | index: Option<&Index>, |
| 176 | replace: Option<bool>, |
| 177 | ) -> PyResult<Bound<'a, PyAny>> { |
| 178 | let index = if let Some(index) = index { |
| 179 | index.consume()? |
| 180 | } else { |
| 181 | lancedb::index::Index::Auto |
| 182 | }; |
| 183 | let mut op = self_.inner_ref()?.create_index(&[column], index); |
| 184 | if let Some(replace) = replace { |
| 185 | op = op.replace(replace); |
| 186 | } |
| 187 | |
| 188 | future_into_py(self_.py(), async move { |
| 189 | op.execute().await.infer_error()?; |
| 190 | Ok(()) |
| 191 | }) |
| 192 | } |
| 193 | |
| 194 | pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 195 | let inner = self_.inner_ref()?.clone(); |
| 196 | future_into_py(self_.py(), async move { |
| 197 | Ok(inner |
| 198 | .list_indices() |
| 199 | .await |
| 200 | .infer_error()? |
| 201 | .into_iter() |
| 202 | .map(IndexConfig::from) |
| 203 | .collect::<Vec<_>>()) |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | pub fn index_stats(self_: PyRef<'_, Self>, index_name: String) -> PyResult<Bound<'_, PyAny>> { |
| 208 | let inner = self_.inner_ref()?.clone(); |
| 209 | future_into_py(self_.py(), async move { |
| 210 | let stats = inner.index_stats(&index_name).await.infer_error()?; |
| 211 | if let Some(stats) = stats { |
| 212 | Python::with_gil(|py| { |
| 213 | let dict = PyDict::new_bound(py); |
| 214 | dict.set_item("num_indexed_rows", stats.num_indexed_rows)?; |
| 215 | dict.set_item("num_unindexed_rows", stats.num_unindexed_rows)?; |
| 216 | dict.set_item("index_type", stats.index_type.to_string())?; |
| 217 | |
| 218 | if let Some(distance_type) = stats.distance_type { |
| 219 | dict.set_item("distance_type", distance_type.to_string())?; |
| 220 | } |
| 221 | |
| 222 | if let Some(num_indices) = stats.num_indices { |
| 223 | dict.set_item("num_indices", num_indices)?; |
| 224 | } |
| 225 | |
| 226 | Ok(Some(dict.to_object(py))) |
| 227 | }) |
| 228 | } else { |
| 229 | Ok(None) |
| 230 | } |
| 231 | }) |
| 232 | } |
| 233 | |
| 234 | pub fn __repr__(&self) -> String { |
| 235 | match &self.inner { |
| 236 | None => format!("ClosedTable({})", self.name), |
| 237 | Some(inner) => inner.to_string(), |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | pub fn version(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 242 | let inner = self_.inner_ref()?.clone(); |
| 243 | future_into_py( |
| 244 | self_.py(), |
| 245 | async move { inner.version().await.infer_error() }, |
| 246 | ) |
| 247 | } |
| 248 | |
| 249 | pub fn checkout(self_: PyRef<'_, Self>, version: u64) -> PyResult<Bound<'_, PyAny>> { |
| 250 | let inner = self_.inner_ref()?.clone(); |
| 251 | future_into_py(self_.py(), async move { |
| 252 | inner.checkout(version).await.infer_error() |
| 253 | }) |
| 254 | } |
| 255 | |
| 256 | pub fn checkout_latest(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 257 | let inner = self_.inner_ref()?.clone(); |
| 258 | future_into_py(self_.py(), async move { |
| 259 | inner.checkout_latest().await.infer_error() |
| 260 | }) |
| 261 | } |
| 262 | |
| 263 | pub fn restore(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 264 | let inner = self_.inner_ref()?.clone(); |
| 265 | future_into_py( |
| 266 | self_.py(), |
| 267 | async move { inner.restore().await.infer_error() }, |
| 268 | ) |
| 269 | } |
| 270 | |
| 271 | pub fn query(&self) -> Query { |
| 272 | Query::new(self.inner_ref().unwrap().query()) |
| 273 | } |
| 274 | |
| 275 | pub fn optimize( |
| 276 | self_: PyRef<'_, Self>, |
| 277 | cleanup_since_ms: Option<u64>, |
| 278 | delete_unverified: Option<bool>, |
| 279 | ) -> PyResult<Bound<'_, PyAny>> { |
| 280 | let inner = self_.inner_ref()?.clone(); |
| 281 | let older_than = if let Some(ms) = cleanup_since_ms { |
| 282 | if ms > i64::MAX as u64 { |
| 283 | return Err(PyValueError::new_err(format!( |
| 284 | "cleanup_since_ms must be between {} and -{}", |
| 285 | i32::MAX, |
| 286 | i32::MAX |
| 287 | ))); |
| 288 | } |
| 289 | Duration::try_milliseconds(ms as i64) |
| 290 | } else { |
| 291 | None |
| 292 | }; |
| 293 | future_into_py(self_.py(), async move { |
| 294 | let compaction_stats = inner |
| 295 | .optimize(OptimizeAction::Compact { |
| 296 | options: lancedb::table::CompactionOptions::default(), |
| 297 | remap_options: None, |
| 298 | }) |
| 299 | .await |
| 300 | .infer_error()? |
| 301 | .compaction |
| 302 | .unwrap(); |
| 303 | let prune_stats = inner |
| 304 | .optimize(OptimizeAction::Prune { |
| 305 | older_than, |
| 306 | delete_unverified, |
| 307 | error_if_tagged_old_versions: None, |
| 308 | }) |
| 309 | .await |
| 310 | .infer_error()? |
| 311 | .prune |
| 312 | .unwrap(); |
| 313 | inner |
| 314 | .optimize(lancedb::table::OptimizeAction::Index( |
| 315 | OptimizeOptions::default(), |
| 316 | )) |
| 317 | .await |
| 318 | .infer_error()?; |
| 319 | Ok(OptimizeStats { |
| 320 | compaction: CompactionStats { |
| 321 | files_added: compaction_stats.files_added as u64, |
| 322 | files_removed: compaction_stats.files_removed as u64, |
| 323 | fragments_added: compaction_stats.fragments_added as u64, |
| 324 | fragments_removed: compaction_stats.fragments_removed as u64, |
| 325 | }, |
| 326 | prune: RemovalStats { |
| 327 | bytes_removed: prune_stats.bytes_removed, |
| 328 | old_versions_removed: prune_stats.old_versions, |
| 329 | }, |
| 330 | }) |
| 331 | }) |
| 332 | } |
| 333 | |
| 334 | pub fn execute_merge_insert<'a>( |
| 335 | self_: PyRef<'a, Self>, |
| 336 | data: Bound<'a, PyAny>, |
| 337 | parameters: MergeInsertParams, |
| 338 | ) -> PyResult<Bound<'a, PyAny>> { |
| 339 | let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; |
| 340 | let on = parameters.on.iter().map(|s| s.as_str()).collect::<Vec<_>>(); |
| 341 | let mut builder = self_.inner_ref()?.merge_insert(&on); |
| 342 | if parameters.when_matched_update_all { |
| 343 | builder.when_matched_update_all(parameters.when_matched_update_all_condition); |
| 344 | } |
| 345 | if parameters.when_not_matched_insert_all { |
| 346 | builder.when_not_matched_insert_all(); |
| 347 | } |
| 348 | if parameters.when_not_matched_by_source_delete { |
| 349 | builder |
| 350 | .when_not_matched_by_source_delete(parameters.when_not_matched_by_source_condition); |
| 351 | } |
| 352 | |
| 353 | future_into_py(self_.py(), async move { |
| 354 | builder.execute(Box::new(batches)).await.infer_error()?; |
| 355 | Ok(()) |
| 356 | }) |
| 357 | } |
| 358 | |
| 359 | pub fn uses_v2_manifest_paths(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 360 | let inner = self_.inner_ref()?.clone(); |
| 361 | future_into_py(self_.py(), async move { |
| 362 | inner |
| 363 | .as_native() |
| 364 | .ok_or_else(|| PyValueError::new_err("This cannot be run on a remote table"))? |
| 365 | .uses_v2_manifest_paths() |
| 366 | .await |
| 367 | .infer_error() |
| 368 | }) |
| 369 | } |
| 370 | |
| 371 | pub fn migrate_manifest_paths_v2(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 372 | let inner = self_.inner_ref()?.clone(); |
| 373 | future_into_py(self_.py(), async move { |
| 374 | inner |
| 375 | .as_native() |
| 376 | .ok_or_else(|| PyValueError::new_err("This cannot be run on a remote table"))? |
| 377 | .migrate_manifest_paths_v2() |
| 378 | .await |
| 379 | .infer_error() |
| 380 | }) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | #[derive(FromPyObject)] |
| 385 | #[pyo3(from_item_all)] |
| 386 | pub struct MergeInsertParams { |
| 387 | on: Vec<String>, |
| 388 | when_matched_update_all: bool, |
| 389 | when_matched_update_all_condition: Option<String>, |
| 390 | when_not_matched_insert_all: bool, |
| 391 | when_not_matched_by_source_delete: bool, |
| 392 | when_not_matched_by_source_condition: Option<String>, |
| 393 | } |