| 1 | // Copyright 2024 Lance Developers. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | use arrow_ipc::writer::FileWriter; |
| 16 | use lancedb::ipc::ipc_file_to_batches; |
| 17 | use lancedb::table::{ |
| 18 | AddDataMode, ColumnAlteration as LanceColumnAlteration, Duration, NewColumnTransform, |
| 19 | OptimizeAction, OptimizeOptions, Table as LanceDbTable, |
| 20 | }; |
| 21 | use napi::bindgen_prelude::*; |
| 22 | use napi_derive::napi; |
| 23 | |
| 24 | use crate::error::NapiErrorExt; |
| 25 | use crate::index::Index; |
| 26 | use crate::merge::NativeMergeInsertBuilder; |
| 27 | use crate::query::{Query, VectorQuery}; |
| 28 | |
| 29 | #[napi] |
| 30 | pub struct Table { |
| 31 | // We keep a duplicate of the table name so we can use it for error |
| 32 | // messages even if the table has been closed |
| 33 | pub name: String, |
| 34 | pub(crate) inner: Option<LanceDbTable>, |
| 35 | } |
| 36 | |
| 37 | impl Table { |
| 38 | fn inner_ref(&self) -> napi::Result<&LanceDbTable> { |
| 39 | self.inner |
| 40 | .as_ref() |
| 41 | .ok_or_else(|| napi::Error::from_reason(format!("Table {} is closed", self.name))) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[napi] |
| 46 | impl Table { |
| 47 | pub(crate) fn new(table: LanceDbTable) -> Self { |
| 48 | Self { |
| 49 | name: table.name().to_string(), |
| 50 | inner: Some(table), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[napi] |
| 55 | pub fn display(&self) -> String { |
| 56 | match &self.inner { |
| 57 | None => format!("ClosedTable({})", self.name), |
| 58 | Some(inner) => inner.to_string(), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | #[napi] |
| 63 | pub fn is_open(&self) -> bool { |
| 64 | self.inner.is_some() |
| 65 | } |
| 66 | |
| 67 | #[napi] |
| 68 | pub fn close(&mut self) { |
| 69 | self.inner.take(); |
| 70 | } |
| 71 | |
| 72 | /// Return Schema as empty Arrow IPC file. |
| 73 | #[napi(catch_unwind)] |
| 74 | pub async fn schema(&self) -> napi::Result<Buffer> { |
| 75 | let schema = |
| 76 | self.inner_ref()?.schema().await.map_err(|e| { |
| 77 | napi::Error::from_reason(format!("Failed to create IPC file: {}", e)) |
| 78 | })?; |
| 79 | let mut writer = FileWriter::try_new(vec![], &schema) |
| 80 | .map_err(|e| napi::Error::from_reason(format!("Failed to create IPC file: {}", e)))?; |
| 81 | writer |
| 82 | .finish() |
| 83 | .map_err(|e| napi::Error::from_reason(format!("Failed to finish IPC file: {}", e)))?; |
| 84 | Ok(Buffer::from(writer.into_inner().map_err(|e| { |
| 85 | napi::Error::from_reason(format!("Failed to get IPC file: {}", e)) |
| 86 | })?)) |
| 87 | } |
| 88 | |
| 89 | #[napi(catch_unwind)] |
| 90 | pub async fn add(&self, buf: Buffer, mode: String) -> napi::Result<()> { |
| 91 | let batches = ipc_file_to_batches(buf.to_vec()) |
| 92 | .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?; |
| 93 | let mut op = self.inner_ref()?.add(batches); |
| 94 | |
| 95 | op = if mode == "append" { |
| 96 | op.mode(AddDataMode::Append) |
| 97 | } else if mode == "overwrite" { |
| 98 | op.mode(AddDataMode::Overwrite) |
| 99 | } else { |
| 100 | return Err(napi::Error::from_reason(format!("Invalid mode: {}", mode))); |
| 101 | }; |
| 102 | |
| 103 | op.execute().await.map_err(|e| { |
| 104 | napi::Error::from_reason(format!( |
| 105 | "Failed to add batches to table {}: {}", |
| 106 | self.name, e |
| 107 | )) |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | #[napi(catch_unwind)] |
| 112 | pub async fn count_rows(&self, filter: Option<String>) -> napi::Result<i64> { |
| 113 | self.inner_ref()? |
| 114 | .count_rows(filter) |
| 115 | .await |
| 116 | .map(|val| val as i64) |
| 117 | .map_err(|e| { |
| 118 | napi::Error::from_reason(format!( |
| 119 | "Failed to count rows in table {}: {}", |
| 120 | self.name, e |
| 121 | )) |
| 122 | }) |
| 123 | } |
| 124 | |
| 125 | #[napi(catch_unwind)] |
| 126 | pub async fn delete(&self, predicate: String) -> napi::Result<()> { |
| 127 | self.inner_ref()?.delete(&predicate).await.map_err(|e| { |
| 128 | napi::Error::from_reason(format!( |
| 129 | "Failed to delete rows in table {}: predicate={}", |
| 130 | self.name, e |
| 131 | )) |
| 132 | }) |
| 133 | } |
| 134 | |
| 135 | #[napi(catch_unwind)] |
| 136 | pub async fn create_index( |
| 137 | &self, |
| 138 | index: Option<&Index>, |
| 139 | column: String, |
| 140 | replace: Option<bool>, |
| 141 | ) -> napi::Result<()> { |
| 142 | let lancedb_index = if let Some(index) = index { |
| 143 | index.consume()? |
| 144 | } else { |
| 145 | lancedb::index::Index::Auto |
| 146 | }; |
| 147 | let mut builder = self.inner_ref()?.create_index(&[column], lancedb_index); |
| 148 | if let Some(replace) = replace { |
| 149 | builder = builder.replace(replace); |
| 150 | } |
| 151 | builder.execute().await.default_error() |
| 152 | } |
| 153 | |
| 154 | #[napi(catch_unwind)] |
| 155 | pub async fn update( |
| 156 | &self, |
| 157 | only_if: Option<String>, |
| 158 | columns: Vec<(String, String)>, |
| 159 | ) -> napi::Result<u64> { |
| 160 | let mut op = self.inner_ref()?.update(); |
| 161 | if let Some(only_if) = only_if { |
| 162 | op = op.only_if(only_if); |
| 163 | } |
| 164 | for (column_name, value) in columns { |
| 165 | op = op.column(column_name, value); |
| 166 | } |
| 167 | op.execute().await.default_error() |
| 168 | } |
| 169 | |
| 170 | #[napi(catch_unwind)] |
| 171 | pub fn query(&self) -> napi::Result<Query> { |
| 172 | Ok(Query::new(self.inner_ref()?.query())) |
| 173 | } |
| 174 | |
| 175 | #[napi(catch_unwind)] |
| 176 | pub fn vector_search(&self, vector: Float32Array) -> napi::Result<VectorQuery> { |
| 177 | self.query()?.nearest_to(vector) |
| 178 | } |
| 179 | |
| 180 | #[napi(catch_unwind)] |
| 181 | pub async fn add_columns(&self, transforms: Vec<AddColumnsSql>) -> napi::Result<()> { |
| 182 | let transforms = transforms |
| 183 | .into_iter() |
| 184 | .map(|sql| (sql.name, sql.value_sql)) |
| 185 | .collect::<Vec<_>>(); |
| 186 | let transforms = NewColumnTransform::SqlExpressions(transforms); |
| 187 | self.inner_ref()? |
| 188 | .add_columns(transforms, None) |
| 189 | .await |
| 190 | .map_err(|err| { |
| 191 | napi::Error::from_reason(format!( |
| 192 | "Failed to add columns to table {}: {}", |
| 193 | self.name, err |
| 194 | )) |
| 195 | })?; |
| 196 | Ok(()) |
| 197 | } |
| 198 | |
| 199 | #[napi(catch_unwind)] |
| 200 | pub async fn alter_columns(&self, alterations: Vec<ColumnAlteration>) -> napi::Result<()> { |
| 201 | for alteration in &alterations { |
| 202 | if alteration.rename.is_none() && alteration.nullable.is_none() { |
| 203 | return Err(napi::Error::from_reason( |
| 204 | "Alteration must have a 'rename' or 'nullable' field.", |
| 205 | )); |
| 206 | } |
| 207 | } |
| 208 | let alterations = alterations |
| 209 | .into_iter() |
| 210 | .map(LanceColumnAlteration::from) |
| 211 | .collect::<Vec<_>>(); |
| 212 | |
| 213 | self.inner_ref()? |
| 214 | .alter_columns(&alterations) |
| 215 | .await |
| 216 | .map_err(|err| { |
| 217 | napi::Error::from_reason(format!( |
| 218 | "Failed to alter columns in table {}: {}", |
| 219 | self.name, err |
| 220 | )) |
| 221 | })?; |
| 222 | Ok(()) |
| 223 | } |
| 224 | |
| 225 | #[napi(catch_unwind)] |
| 226 | pub async fn drop_columns(&self, columns: Vec<String>) -> napi::Result<()> { |
| 227 | let col_refs = columns.iter().map(String::as_str).collect::<Vec<_>>(); |
| 228 | self.inner_ref()? |
| 229 | .drop_columns(&col_refs) |
| 230 | .await |
| 231 | .map_err(|err| { |
| 232 | napi::Error::from_reason(format!( |
| 233 | "Failed to drop columns from table {}: {}", |
| 234 | self.name, err |
| 235 | )) |
| 236 | })?; |
| 237 | Ok(()) |
| 238 | } |
| 239 | |
| 240 | #[napi(catch_unwind)] |
| 241 | pub async fn version(&self) -> napi::Result<i64> { |
| 242 | self.inner_ref()? |
| 243 | .version() |
| 244 | .await |
| 245 | .map(|val| val as i64) |
| 246 | .default_error() |
| 247 | } |
| 248 | |
| 249 | #[napi(catch_unwind)] |
| 250 | pub async fn checkout(&self, version: i64) -> napi::Result<()> { |
| 251 | self.inner_ref()? |
| 252 | .checkout(version as u64) |
| 253 | .await |
| 254 | .default_error() |
| 255 | } |
| 256 | |
| 257 | #[napi(catch_unwind)] |
| 258 | pub async fn checkout_latest(&self) -> napi::Result<()> { |
| 259 | self.inner_ref()?.checkout_latest().await.default_error() |
| 260 | } |
| 261 | |
| 262 | #[napi(catch_unwind)] |
| 263 | pub async fn restore(&self) -> napi::Result<()> { |
| 264 | self.inner_ref()?.restore().await.default_error() |
| 265 | } |
| 266 | |
| 267 | #[napi(catch_unwind)] |
| 268 | pub async fn optimize( |
| 269 | &self, |
| 270 | older_than_ms: Option<i64>, |
| 271 | delete_unverified: Option<bool>, |
| 272 | ) -> napi::Result<OptimizeStats> { |
| 273 | let inner = self.inner_ref()?; |
| 274 | |
| 275 | let older_than = if let Some(ms) = older_than_ms { |
| 276 | if ms == i64::MIN { |
| 277 | return Err(napi::Error::from_reason(format!( |
| 278 | "older_than_ms can not be {}", |
| 279 | i32::MIN, |
| 280 | ))); |
| 281 | } |
| 282 | Duration::try_milliseconds(ms) |
| 283 | } else { |
| 284 | None |
| 285 | }; |
| 286 | |
| 287 | let compaction_stats = inner |
| 288 | .optimize(OptimizeAction::Compact { |
| 289 | options: lancedb::table::CompactionOptions::default(), |
| 290 | remap_options: None, |
| 291 | }) |
| 292 | .await |
| 293 | .default_error()? |
| 294 | .compaction |
| 295 | .unwrap(); |
| 296 | let prune_stats = inner |
| 297 | .optimize(OptimizeAction::Prune { |
| 298 | older_than, |
| 299 | delete_unverified, |
| 300 | error_if_tagged_old_versions: None, |
| 301 | }) |
| 302 | .await |
| 303 | .default_error()? |
| 304 | .prune |
| 305 | .unwrap(); |
| 306 | inner |
| 307 | .optimize(lancedb::table::OptimizeAction::Index( |
| 308 | OptimizeOptions::default(), |
| 309 | )) |
| 310 | .await |
| 311 | .default_error()?; |
| 312 | Ok(OptimizeStats { |
| 313 | compaction: CompactionStats { |
| 314 | files_added: compaction_stats.files_added as i64, |
| 315 | files_removed: compaction_stats.files_removed as i64, |
| 316 | fragments_added: compaction_stats.fragments_added as i64, |
| 317 | fragments_removed: compaction_stats.fragments_removed as i64, |
| 318 | }, |
| 319 | prune: RemovalStats { |
| 320 | bytes_removed: prune_stats.bytes_removed as i64, |
| 321 | old_versions_removed: prune_stats.old_versions as i64, |
| 322 | }, |
| 323 | }) |
| 324 | } |
| 325 | |
| 326 | #[napi(catch_unwind)] |
| 327 | pub async fn list_indices(&self) -> napi::Result<Vec<IndexConfig>> { |
| 328 | Ok(self |
| 329 | .inner_ref()? |
| 330 | .list_indices() |
| 331 | .await |
| 332 | .default_error()? |
| 333 | .into_iter() |
| 334 | .map(IndexConfig::from) |
| 335 | .collect::<Vec<_>>()) |
| 336 | } |
| 337 | |
| 338 | #[napi(catch_unwind)] |
| 339 | pub async fn index_stats(&self, index_name: String) -> napi::Result<Option<IndexStatistics>> { |
| 340 | let tbl = self.inner_ref()?; |
| 341 | let stats = tbl.index_stats(&index_name).await.default_error()?; |
| 342 | Ok(stats.map(IndexStatistics::from)) |
| 343 | } |
| 344 | |
| 345 | #[napi(catch_unwind)] |
| 346 | pub fn merge_insert(&self, on: Vec<String>) -> napi::Result<NativeMergeInsertBuilder> { |
| 347 | let on: Vec<_> = on.iter().map(String::as_str).collect(); |
| 348 | Ok(self.inner_ref()?.merge_insert(on.as_slice()).into()) |
| 349 | } |
| 350 | |
| 351 | #[napi(catch_unwind)] |
| 352 | pub async fn uses_v2_manifest_paths(&self) -> napi::Result<bool> { |
| 353 | self.inner_ref()? |
| 354 | .as_native() |
| 355 | .ok_or_else(|| napi::Error::from_reason("This cannot be run on a remote table"))? |
| 356 | .uses_v2_manifest_paths() |
| 357 | .await |
| 358 | .default_error() |
| 359 | } |
| 360 | |
| 361 | #[napi(catch_unwind)] |
| 362 | pub async fn migrate_manifest_paths_v2(&self) -> napi::Result<()> { |
| 363 | self.inner_ref()? |
| 364 | .as_native() |
| 365 | .ok_or_else(|| napi::Error::from_reason("This cannot be run on a remote table"))? |
| 366 | .migrate_manifest_paths_v2() |
| 367 | .await |
| 368 | .default_error() |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | #[napi(object)] |
| 373 | /// A description of an index currently configured on a column |
| 374 | pub struct IndexConfig { |
| 375 | /// The name of the index |
| 376 | pub name: String, |
| 377 | /// The type of the index |
| 378 | pub index_type: String, |
| 379 | /// The columns in the index |
| 380 | /// |
| 381 | /// Currently this is always an array of size 1. In the future there may |
| 382 | /// be more columns to represent composite indices. |
| 383 | pub columns: Vec<String>, |
| 384 | } |
| 385 | |
| 386 | impl From<lancedb::index::IndexConfig> for IndexConfig { |
| 387 | fn from(value: lancedb::index::IndexConfig) -> Self { |
| 388 | let index_type = format!("{:?}", value.index_type); |
| 389 | Self { |
| 390 | index_type, |
| 391 | columns: value.columns, |
| 392 | name: value.name, |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// Statistics about a compaction operation. |
| 398 | #[napi(object)] |
| 399 | #[derive(Clone, Debug)] |
| 400 | pub struct CompactionStats { |
| 401 | /// The number of fragments removed |
| 402 | pub fragments_removed: i64, |
| 403 | /// The number of new, compacted fragments added |
| 404 | pub fragments_added: i64, |
| 405 | /// The number of data files removed |
| 406 | pub files_removed: i64, |
| 407 | /// The number of new, compacted data files added |
| 408 | pub files_added: i64, |
| 409 | } |
| 410 | |
| 411 | /// Statistics about a cleanup operation |
| 412 | #[napi(object)] |
| 413 | #[derive(Clone, Debug)] |
| 414 | pub struct RemovalStats { |
| 415 | /// The number of bytes removed |
| 416 | pub bytes_removed: i64, |
| 417 | /// The number of old versions removed |
| 418 | pub old_versions_removed: i64, |
| 419 | } |
| 420 | |
| 421 | /// Statistics about an optimize operation |
| 422 | #[napi(object)] |
| 423 | #[derive(Clone, Debug)] |
| 424 | pub struct OptimizeStats { |
| 425 | /// Statistics about the compaction operation |
| 426 | pub compaction: CompactionStats, |
| 427 | /// Statistics about the removal operation |
| 428 | pub prune: RemovalStats, |
| 429 | } |
| 430 | |
| 431 | /// A definition of a column alteration. The alteration changes the column at |
| 432 | /// `path` to have the new name `name`, to be nullable if `nullable` is true, |
| 433 | /// and to have the data type `data_type`. At least one of `rename` or `nullable` |
| 434 | /// must be provided. |
| 435 | #[napi(object)] |
| 436 | pub struct ColumnAlteration { |
| 437 | /// The path to the column to alter. This is a dot-separated path to the column. |
| 438 | /// If it is a top-level column then it is just the name of the column. If it is |
| 439 | /// a nested column then it is the path to the column, e.g. "a.b.c" for a column |
| 440 | /// `c` nested inside a column `b` nested inside a column `a`. |
| 441 | pub path: String, |
| 442 | /// The new name of the column. If not provided then the name will not be changed. |
| 443 | /// This must be distinct from the names of all other columns in the table. |
| 444 | pub rename: Option<String>, |
| 445 | /// Set the new nullability. Note that a nullable column cannot be made non-nullable. |
| 446 | pub nullable: Option<bool>, |
| 447 | } |
| 448 | |
| 449 | impl From<ColumnAlteration> for LanceColumnAlteration { |
| 450 | fn from(js: ColumnAlteration) -> Self { |
| 451 | let ColumnAlteration { |
| 452 | path, |
| 453 | rename, |
| 454 | nullable, |
| 455 | } = js; |
| 456 | Self { |
| 457 | path, |
| 458 | rename, |
| 459 | nullable, |
| 460 | // TODO: wire up this field |
| 461 | data_type: None, |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | /// A definition of a new column to add to a table. |
| 467 | #[napi(object)] |
| 468 | pub struct AddColumnsSql { |
| 469 | /// The name of the new column. |
| 470 | pub name: String, |
| 471 | /// The values to populate the new column with, as a SQL expression. |
| 472 | /// The expression can reference other columns in the table. |
| 473 | pub value_sql: String, |
| 474 | } |
| 475 | |
| 476 | #[napi(object)] |
| 477 | pub struct IndexStatistics { |
| 478 | /// The number of rows indexed by the index |
| 479 | pub num_indexed_rows: f64, |
| 480 | /// The number of rows not indexed |
| 481 | pub num_unindexed_rows: f64, |
| 482 | /// The type of the index |
| 483 | pub index_type: String, |
| 484 | /// The type of the distance function used by the index. This is only |
| 485 | /// present for vector indices. Scalar and full text search indices do |
| 486 | /// not have a distance function. |
| 487 | pub distance_type: Option<String>, |
| 488 | /// The number of parts this index is split into. |
| 489 | pub num_indices: Option<u32>, |
| 490 | } |
| 491 | impl From<lancedb::index::IndexStatistics> for IndexStatistics { |
| 492 | fn from(value: lancedb::index::IndexStatistics) -> Self { |
| 493 | Self { |
| 494 | num_indexed_rows: value.num_indexed_rows as f64, |
| 495 | num_unindexed_rows: value.num_unindexed_rows as f64, |
| 496 | index_type: value.index_type.to_string(), |
| 497 | distance_type: value.distance_type.map(|d| d.to_string()), |
| 498 | num_indices: value.num_indices, |
| 499 | } |
| 500 | } |
| 501 | } |