| 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, PyString}, |
| 12 | Bound, PyAny, PyRef, PyResult, Python, |
| 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 __repr__(&self) -> String { |
| 208 | match &self.inner { |
| 209 | None => format!("ClosedTable({})", self.name), |
| 210 | Some(inner) => inner.to_string(), |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | pub fn version(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 215 | let inner = self_.inner_ref()?.clone(); |
| 216 | future_into_py( |
| 217 | self_.py(), |
| 218 | async move { inner.version().await.infer_error() }, |
| 219 | ) |
| 220 | } |
| 221 | |
| 222 | pub fn checkout(self_: PyRef<'_, Self>, version: u64) -> PyResult<Bound<'_, PyAny>> { |
| 223 | let inner = self_.inner_ref()?.clone(); |
| 224 | future_into_py(self_.py(), async move { |
| 225 | inner.checkout(version).await.infer_error() |
| 226 | }) |
| 227 | } |
| 228 | |
| 229 | pub fn checkout_latest(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 230 | let inner = self_.inner_ref()?.clone(); |
| 231 | future_into_py(self_.py(), async move { |
| 232 | inner.checkout_latest().await.infer_error() |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | pub fn restore(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 237 | let inner = self_.inner_ref()?.clone(); |
| 238 | future_into_py( |
| 239 | self_.py(), |
| 240 | async move { inner.restore().await.infer_error() }, |
| 241 | ) |
| 242 | } |
| 243 | |
| 244 | pub fn query(&self) -> Query { |
| 245 | Query::new(self.inner_ref().unwrap().query()) |
| 246 | } |
| 247 | |
| 248 | pub fn optimize( |
| 249 | self_: PyRef<'_, Self>, |
| 250 | cleanup_since_ms: Option<u64>, |
| 251 | delete_unverified: Option<bool>, |
| 252 | ) -> PyResult<Bound<'_, PyAny>> { |
| 253 | let inner = self_.inner_ref()?.clone(); |
| 254 | let older_than = if let Some(ms) = cleanup_since_ms { |
| 255 | if ms > i64::MAX as u64 { |
| 256 | return Err(PyValueError::new_err(format!( |
| 257 | "cleanup_since_ms must be between {} and -{}", |
| 258 | i32::MAX, |
| 259 | i32::MAX |
| 260 | ))); |
| 261 | } |
| 262 | Duration::try_milliseconds(ms as i64) |
| 263 | } else { |
| 264 | None |
| 265 | }; |
| 266 | future_into_py(self_.py(), async move { |
| 267 | let compaction_stats = inner |
| 268 | .optimize(OptimizeAction::Compact { |
| 269 | options: lancedb::table::CompactionOptions::default(), |
| 270 | remap_options: None, |
| 271 | }) |
| 272 | .await |
| 273 | .infer_error()? |
| 274 | .compaction |
| 275 | .unwrap(); |
| 276 | let prune_stats = inner |
| 277 | .optimize(OptimizeAction::Prune { |
| 278 | older_than, |
| 279 | delete_unverified, |
| 280 | error_if_tagged_old_versions: None, |
| 281 | }) |
| 282 | .await |
| 283 | .infer_error()? |
| 284 | .prune |
| 285 | .unwrap(); |
| 286 | inner |
| 287 | .optimize(lancedb::table::OptimizeAction::Index( |
| 288 | OptimizeOptions::default(), |
| 289 | )) |
| 290 | .await |
| 291 | .infer_error()?; |
| 292 | Ok(OptimizeStats { |
| 293 | compaction: CompactionStats { |
| 294 | files_added: compaction_stats.files_added as u64, |
| 295 | files_removed: compaction_stats.files_removed as u64, |
| 296 | fragments_added: compaction_stats.fragments_added as u64, |
| 297 | fragments_removed: compaction_stats.fragments_removed as u64, |
| 298 | }, |
| 299 | prune: RemovalStats { |
| 300 | bytes_removed: prune_stats.bytes_removed, |
| 301 | old_versions_removed: prune_stats.old_versions, |
| 302 | }, |
| 303 | }) |
| 304 | }) |
| 305 | } |
| 306 | |
| 307 | pub fn uses_v2_manifest_paths(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 308 | let inner = self_.inner_ref()?.clone(); |
| 309 | future_into_py(self_.py(), async move { |
| 310 | inner |
| 311 | .as_native() |
| 312 | .ok_or_else(|| PyValueError::new_err("This cannot be run on a remote table"))? |
| 313 | .uses_v2_manifest_paths() |
| 314 | .await |
| 315 | .infer_error() |
| 316 | }) |
| 317 | } |
| 318 | |
| 319 | pub fn migrate_manifest_paths_v2(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 320 | let inner = self_.inner_ref()?.clone(); |
| 321 | future_into_py(self_.py(), async move { |
| 322 | inner |
| 323 | .as_native() |
| 324 | .ok_or_else(|| PyValueError::new_err("This cannot be run on a remote table"))? |
| 325 | .migrate_manifest_paths_v2() |
| 326 | .await |
| 327 | .infer_error() |
| 328 | }) |
| 329 | } |
| 330 | } |