| 1 | // Copyright 2023 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 std::ops::Deref; |
| 16 | |
| 17 | use arrow_array::{RecordBatch, RecordBatchIterator}; |
| 18 | use lance::dataset::optimize::CompactionOptions; |
| 19 | use lance::dataset::{ColumnAlteration, NewColumnTransform, WriteMode, WriteParams}; |
| 20 | use lancedb::table::{OptimizeAction, WriteOptions}; |
| 21 | |
| 22 | use crate::arrow::{arrow_buffer_to_record_batch, record_batch_to_buffer}; |
| 23 | use lancedb::table::Table as LanceDbTable; |
| 24 | use neon::prelude::*; |
| 25 | use neon::types::buffer::TypedArray; |
| 26 | |
| 27 | use crate::error::ResultExt; |
| 28 | use crate::{convert, runtime, JsDatabase}; |
| 29 | |
| 30 | pub struct JsTable { |
| 31 | pub table: LanceDbTable, |
| 32 | } |
| 33 | |
| 34 | impl Finalize for JsTable {} |
| 35 | |
| 36 | impl From<LanceDbTable> for JsTable { |
| 37 | fn from(table: LanceDbTable) -> Self { |
| 38 | Self { table } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl JsTable { |
| 43 | pub(crate) fn js_create(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 44 | let db = cx |
| 45 | .this() |
| 46 | .downcast_or_throw::<JsBox<JsDatabase>, _>(&mut cx)?; |
| 47 | let table_name = cx.argument::<JsString>(0)?.value(&mut cx); |
| 48 | let buffer = cx.argument::<JsBuffer>(1)?; |
| 49 | let (batches, schema) = |
| 50 | arrow_buffer_to_record_batch(buffer.as_slice(&cx)).or_throw(&mut cx)?; |
| 51 | |
| 52 | // Write mode |
| 53 | let mode = match cx.argument::<JsString>(2)?.value(&mut cx).as_str() { |
| 54 | "overwrite" => WriteMode::Overwrite, |
| 55 | "append" => WriteMode::Append, |
| 56 | "create" => WriteMode::Create, |
| 57 | _ => { |
| 58 | return cx.throw_error("Table::create only supports 'overwrite' and 'create' modes") |
| 59 | } |
| 60 | }; |
| 61 | let params = WriteParams { |
| 62 | mode, |
| 63 | ..WriteParams::default() |
| 64 | }; |
| 65 | |
| 66 | let rt = runtime(&mut cx)?; |
| 67 | let channel = cx.channel(); |
| 68 | |
| 69 | let (deferred, promise) = cx.promise(); |
| 70 | let database = db.database.clone(); |
| 71 | |
| 72 | rt.spawn(async move { |
| 73 | let batch_reader = RecordBatchIterator::new(batches.into_iter().map(Ok), schema); |
| 74 | let table_rst = database |
| 75 | .create_table(&table_name, batch_reader) |
| 76 | .write_options(WriteOptions { |
| 77 | lance_write_params: Some(params), |
| 78 | }) |
| 79 | .execute() |
| 80 | .await; |
| 81 | |
| 82 | deferred.settle_with(&channel, move |mut cx| { |
| 83 | let table = table_rst.or_throw(&mut cx)?; |
| 84 | Ok(cx.boxed(Self::from(table))) |
| 85 | }); |
| 86 | }); |
| 87 | Ok(promise) |
| 88 | } |
| 89 | |
| 90 | pub(crate) fn js_add(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 91 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 92 | let buffer = cx.argument::<JsBuffer>(0)?; |
| 93 | let write_mode = cx.argument::<JsString>(1)?.value(&mut cx); |
| 94 | let (batches, schema) = |
| 95 | arrow_buffer_to_record_batch(buffer.as_slice(&cx)).or_throw(&mut cx)?; |
| 96 | let rt = runtime(&mut cx)?; |
| 97 | let channel = cx.channel(); |
| 98 | let table = js_table.table.clone(); |
| 99 | |
| 100 | let (deferred, promise) = cx.promise(); |
| 101 | let write_mode = match write_mode.as_str() { |
| 102 | "create" => WriteMode::Create, |
| 103 | "append" => WriteMode::Append, |
| 104 | "overwrite" => WriteMode::Overwrite, |
| 105 | s => return cx.throw_error(format!("invalid write mode {}", s)), |
| 106 | }; |
| 107 | |
| 108 | let params = WriteParams { |
| 109 | mode: write_mode, |
| 110 | ..WriteParams::default() |
| 111 | }; |
| 112 | |
| 113 | rt.spawn(async move { |
| 114 | let batch_reader = RecordBatchIterator::new(batches.into_iter().map(Ok), schema); |
| 115 | let add_result = table |
| 116 | .add(batch_reader) |
| 117 | .write_options(WriteOptions { |
| 118 | lance_write_params: Some(params), |
| 119 | }) |
| 120 | .execute() |
| 121 | .await; |
| 122 | |
| 123 | deferred.settle_with(&channel, move |mut cx| { |
| 124 | add_result.or_throw(&mut cx)?; |
| 125 | Ok(cx.boxed(Self::from(table))) |
| 126 | }); |
| 127 | }); |
| 128 | Ok(promise) |
| 129 | } |
| 130 | |
| 131 | pub(crate) fn js_count_rows(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 132 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 133 | let filter = cx |
| 134 | .argument_opt(0) |
| 135 | .and_then(|filt| { |
| 136 | if filt.is_a::<JsUndefined, _>(&mut cx) || filt.is_a::<JsNull, _>(&mut cx) { |
| 137 | None |
| 138 | } else { |
| 139 | Some( |
| 140 | filt.downcast_or_throw::<JsString, _>(&mut cx) |
| 141 | .map(|js_filt| js_filt.deref().value(&mut cx)), |
| 142 | ) |
| 143 | } |
| 144 | }) |
| 145 | .transpose()?; |
| 146 | let rt = runtime(&mut cx)?; |
| 147 | let (deferred, promise) = cx.promise(); |
| 148 | let channel = cx.channel(); |
| 149 | let table = js_table.table.clone(); |
| 150 | |
| 151 | rt.spawn(async move { |
| 152 | let num_rows_result = table.count_rows(filter).await; |
| 153 | |
| 154 | deferred.settle_with(&channel, move |mut cx| { |
| 155 | let num_rows = num_rows_result.or_throw(&mut cx)?; |
| 156 | Ok(cx.number(num_rows as f64)) |
| 157 | }); |
| 158 | }); |
| 159 | Ok(promise) |
| 160 | } |
| 161 | |
| 162 | pub(crate) fn js_delete(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 163 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 164 | let rt = runtime(&mut cx)?; |
| 165 | let (deferred, promise) = cx.promise(); |
| 166 | let predicate = cx.argument::<JsString>(0)?.value(&mut cx); |
| 167 | let channel = cx.channel(); |
| 168 | let table = js_table.table.clone(); |
| 169 | |
| 170 | rt.spawn(async move { |
| 171 | let delete_result = table.delete(&predicate).await; |
| 172 | |
| 173 | deferred.settle_with(&channel, move |mut cx| { |
| 174 | delete_result.or_throw(&mut cx)?; |
| 175 | Ok(cx.boxed(Self::from(table))) |
| 176 | }) |
| 177 | }); |
| 178 | Ok(promise) |
| 179 | } |
| 180 | |
| 181 | pub(crate) fn js_merge_insert(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 182 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 183 | let rt = runtime(&mut cx)?; |
| 184 | let (deferred, promise) = cx.promise(); |
| 185 | let channel = cx.channel(); |
| 186 | let table = js_table.table.clone(); |
| 187 | |
| 188 | let key = cx.argument::<JsString>(0)?.value(&mut cx); |
| 189 | let mut builder = table.merge_insert(&[&key]); |
| 190 | if cx.argument::<JsBoolean>(1)?.value(&mut cx) { |
| 191 | let filter = cx.argument_opt(2).unwrap(); |
| 192 | if filter.is_a::<JsNull, _>(&mut cx) { |
| 193 | builder.when_matched_update_all(None); |
| 194 | } else { |
| 195 | let filter = filter |
| 196 | .downcast_or_throw::<JsString, _>(&mut cx)? |
| 197 | .deref() |
| 198 | .value(&mut cx); |
| 199 | builder.when_matched_update_all(Some(filter)); |
| 200 | } |
| 201 | } |
| 202 | if cx.argument::<JsBoolean>(3)?.value(&mut cx) { |
| 203 | builder.when_not_matched_insert_all(); |
| 204 | } |
| 205 | if cx.argument::<JsBoolean>(4)?.value(&mut cx) { |
| 206 | let filter = cx.argument_opt(5).unwrap(); |
| 207 | if filter.is_a::<JsNull, _>(&mut cx) { |
| 208 | builder.when_not_matched_by_source_delete(None); |
| 209 | } else { |
| 210 | let filter = filter |
| 211 | .downcast_or_throw::<JsString, _>(&mut cx)? |
| 212 | .deref() |
| 213 | .value(&mut cx); |
| 214 | builder.when_not_matched_by_source_delete(Some(filter)); |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | let buffer = cx.argument::<JsBuffer>(6)?; |
| 219 | let (batches, schema) = |
| 220 | arrow_buffer_to_record_batch(buffer.as_slice(&cx)).or_throw(&mut cx)?; |
| 221 | |
| 222 | rt.spawn(async move { |
| 223 | let new_data = RecordBatchIterator::new(batches.into_iter().map(Ok), schema); |
| 224 | let merge_insert_result = builder.execute(Box::new(new_data)).await; |
| 225 | |
| 226 | deferred.settle_with(&channel, move |mut cx| { |
| 227 | merge_insert_result.or_throw(&mut cx)?; |
| 228 | Ok(cx.boxed(Self::from(table))) |
| 229 | }) |
| 230 | }); |
| 231 | Ok(promise) |
| 232 | } |
| 233 | |
| 234 | pub(crate) fn js_update(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 235 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 236 | let table = js_table.table.clone(); |
| 237 | |
| 238 | let rt = runtime(&mut cx)?; |
| 239 | let (deferred, promise) = cx.promise(); |
| 240 | let channel = cx.channel(); |
| 241 | |
| 242 | // create a vector of updates from the passed map |
| 243 | let updates_arg = cx.argument::<JsObject>(1)?; |
| 244 | let properties = updates_arg.get_own_property_names(&mut cx)?; |
| 245 | let mut updates: Vec<(String, String)> = |
| 246 | Vec::with_capacity(properties.len(&mut cx) as usize); |
| 247 | |
| 248 | let len_properties = properties.len(&mut cx); |
| 249 | for i in 0..len_properties { |
| 250 | let property = properties |
| 251 | .get_value(&mut cx, i)? |
| 252 | .downcast_or_throw::<JsString, _>(&mut cx)?; |
| 253 | |
| 254 | let value = updates_arg |
| 255 | .get_value(&mut cx, property)? |
| 256 | .downcast_or_throw::<JsString, _>(&mut cx)?; |
| 257 | |
| 258 | let property = property.value(&mut cx); |
| 259 | let value = value.value(&mut cx); |
| 260 | updates.push((property, value)); |
| 261 | } |
| 262 | |
| 263 | // get the filter/predicate if the user passed one |
| 264 | let predicate = cx.argument_opt(0); |
| 265 | let predicate = predicate.unwrap().downcast::<JsString, _>(&mut cx); |
| 266 | let predicate = match predicate { |
| 267 | Ok(_) => { |
| 268 | let val = predicate.map(|s| s.value(&mut cx)).unwrap(); |
| 269 | Some(val) |
| 270 | } |
| 271 | Err(_) => { |
| 272 | // if the predicate is not string, check it's null otherwise an invalid |
| 273 | // type was passed |
| 274 | cx.argument::<JsNull>(0)?; |
| 275 | None |
| 276 | } |
| 277 | }; |
| 278 | |
| 279 | rt.spawn(async move { |
| 280 | let updates_arg = updates |
| 281 | .iter() |
| 282 | .map(|(k, v)| (k.as_str(), v.as_str())) |
| 283 | .collect::<Vec<_>>(); |
| 284 | |
| 285 | let predicate = predicate.as_deref(); |
| 286 | |
| 287 | let mut update_op = table.update(); |
| 288 | if let Some(predicate) = predicate { |
| 289 | update_op = update_op.only_if(predicate); |
| 290 | } |
| 291 | for (column, value) in updates_arg { |
| 292 | update_op = update_op.column(column, value); |
| 293 | } |
| 294 | let update_result = update_op.execute().await; |
| 295 | deferred.settle_with(&channel, move |mut cx| { |
| 296 | update_result.or_throw(&mut cx)?; |
| 297 | Ok(cx.boxed(Self::from(table))) |
| 298 | }) |
| 299 | }); |
| 300 | |
| 301 | Ok(promise) |
| 302 | } |
| 303 | |
| 304 | pub(crate) fn js_cleanup(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 305 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 306 | let rt = runtime(&mut cx)?; |
| 307 | let (deferred, promise) = cx.promise(); |
| 308 | let table = js_table.table.clone(); |
| 309 | let channel = cx.channel(); |
| 310 | |
| 311 | let older_than: i64 = cx |
| 312 | .argument_opt(0) |
| 313 | .and_then(|val| val.downcast::<JsNumber, _>(&mut cx).ok()) |
| 314 | .map(|val| val.value(&mut cx) as i64) |
| 315 | .unwrap_or_else(|| 2 * 7 * 24 * 60); // 2 weeks |
| 316 | let older_than = chrono::Duration::try_minutes(older_than).unwrap(); |
| 317 | let delete_unverified: Option<bool> = Some( |
| 318 | cx.argument_opt(1) |
| 319 | .and_then(|val| val.downcast::<JsBoolean, _>(&mut cx).ok()) |
| 320 | .map(|val| val.value(&mut cx)) |
| 321 | .unwrap_or_default(), |
| 322 | ); |
| 323 | let error_if_tagged_old_versions: Option<bool> = Some( |
| 324 | cx.argument_opt(2) |
| 325 | .and_then(|val| val.downcast::<JsBoolean, _>(&mut cx).ok()) |
| 326 | .map(|val| val.value(&mut cx)) |
| 327 | .unwrap_or_default(), |
| 328 | ); |
| 329 | |
| 330 | rt.spawn(async move { |
| 331 | let stats = table |
| 332 | .optimize(OptimizeAction::Prune { |
| 333 | older_than: Some(older_than), |
| 334 | delete_unverified, |
| 335 | error_if_tagged_old_versions, |
| 336 | }) |
| 337 | .await; |
| 338 | |
| 339 | deferred.settle_with(&channel, move |mut cx| { |
| 340 | let stats = stats.or_throw(&mut cx)?; |
| 341 | |
| 342 | let prune_stats = stats.prune.as_ref().expect("Prune stats missing"); |
| 343 | let output_metrics = JsObject::new(&mut cx); |
| 344 | let bytes_removed = cx.number(prune_stats.bytes_removed as f64); |
| 345 | output_metrics.set(&mut cx, "bytesRemoved", bytes_removed)?; |
| 346 | |
| 347 | let old_versions = cx.number(prune_stats.old_versions as f64); |
| 348 | output_metrics.set(&mut cx, "oldVersions", old_versions)?; |
| 349 | |
| 350 | let output_table = cx.boxed(Self::from(table)); |
| 351 | |
| 352 | let output = JsObject::new(&mut cx); |
| 353 | output.set(&mut cx, "metrics", output_metrics)?; |
| 354 | output.set(&mut cx, "newTable", output_table)?; |
| 355 | |
| 356 | Ok(output) |
| 357 | }) |
| 358 | }); |
| 359 | Ok(promise) |
| 360 | } |
| 361 | |
| 362 | pub(crate) fn js_compact(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 363 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 364 | let rt = runtime(&mut cx)?; |
| 365 | let (deferred, promise) = cx.promise(); |
| 366 | let table = js_table.table.clone(); |
| 367 | let channel = cx.channel(); |
| 368 | |
| 369 | let js_options = cx.argument::<JsObject>(0)?; |
| 370 | let mut options = CompactionOptions::default(); |
| 371 | |
| 372 | if let Some(target_rows) = |
| 373 | js_options.get_opt::<JsNumber, _, _>(&mut cx, "targetRowsPerFragment")? |
| 374 | { |
| 375 | options.target_rows_per_fragment = target_rows.value(&mut cx) as usize; |
| 376 | } |
| 377 | if let Some(max_per_group) = |
| 378 | js_options.get_opt::<JsNumber, _, _>(&mut cx, "maxRowsPerGroup")? |
| 379 | { |
| 380 | options.max_rows_per_group = max_per_group.value(&mut cx) as usize; |
| 381 | } |
| 382 | if let Some(materialize_deletions) = |
| 383 | js_options.get_opt::<JsBoolean, _, _>(&mut cx, "materializeDeletions")? |
| 384 | { |
| 385 | options.materialize_deletions = materialize_deletions.value(&mut cx); |
| 386 | } |
| 387 | if let Some(materialize_deletions_threshold) = |
| 388 | js_options.get_opt::<JsNumber, _, _>(&mut cx, "materializeDeletionsThreshold")? |
| 389 | { |
| 390 | options.materialize_deletions_threshold = |
| 391 | materialize_deletions_threshold.value(&mut cx) as f32; |
| 392 | } |
| 393 | if let Some(num_threads) = js_options.get_opt::<JsNumber, _, _>(&mut cx, "numThreads")? { |
| 394 | options.num_threads = Some(num_threads.value(&mut cx) as usize); |
| 395 | } |
| 396 | |
| 397 | rt.spawn(async move { |
| 398 | let stats = table |
| 399 | .optimize(OptimizeAction::Compact { |
| 400 | options, |
| 401 | remap_options: None, |
| 402 | }) |
| 403 | .await; |
| 404 | |
| 405 | deferred.settle_with(&channel, move |mut cx| { |
| 406 | let stats = stats.or_throw(&mut cx)?; |
| 407 | let stats = stats.compaction.as_ref().expect("Compact stats missing"); |
| 408 | |
| 409 | let output_metrics = JsObject::new(&mut cx); |
| 410 | let fragments_removed = cx.number(stats.fragments_removed as f64); |
| 411 | output_metrics.set(&mut cx, "fragmentsRemoved", fragments_removed)?; |
| 412 | |
| 413 | let fragments_added = cx.number(stats.fragments_added as f64); |
| 414 | output_metrics.set(&mut cx, "fragmentsAdded", fragments_added)?; |
| 415 | |
| 416 | let files_removed = cx.number(stats.files_removed as f64); |
| 417 | output_metrics.set(&mut cx, "filesRemoved", files_removed)?; |
| 418 | |
| 419 | let files_added = cx.number(stats.files_added as f64); |
| 420 | output_metrics.set(&mut cx, "filesAdded", files_added)?; |
| 421 | |
| 422 | let output_table = cx.boxed(Self::from(table)); |
| 423 | |
| 424 | let output = JsObject::new(&mut cx); |
| 425 | output.set(&mut cx, "metrics", output_metrics)?; |
| 426 | output.set(&mut cx, "newTable", output_table)?; |
| 427 | |
| 428 | Ok(output) |
| 429 | }) |
| 430 | }); |
| 431 | Ok(promise) |
| 432 | } |
| 433 | |
| 434 | pub(crate) fn js_list_indices(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 435 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 436 | let rt = runtime(&mut cx)?; |
| 437 | let (deferred, promise) = cx.promise(); |
| 438 | // let predicate = cx.argument::<JsString>(0)?.value(&mut cx); |
| 439 | let channel = cx.channel(); |
| 440 | let table = js_table.table.clone(); |
| 441 | |
| 442 | rt.spawn(async move { |
| 443 | let indices = table.as_native().unwrap().load_indices().await; |
| 444 | |
| 445 | deferred.settle_with(&channel, move |mut cx| { |
| 446 | let indices = indices.or_throw(&mut cx)?; |
| 447 | |
| 448 | let output = JsArray::new(&mut cx, indices.len() as u32); |
| 449 | for (i, index) in indices.iter().enumerate() { |
| 450 | let js_index = JsObject::new(&mut cx); |
| 451 | let index_name = cx.string(index.index_name.clone()); |
| 452 | js_index.set(&mut cx, "name", index_name)?; |
| 453 | |
| 454 | let index_uuid = cx.string(index.index_uuid.clone()); |
| 455 | js_index.set(&mut cx, "uuid", index_uuid)?; |
| 456 | |
| 457 | let js_index_columns = JsArray::new(&mut cx, index.columns.len() as u32); |
| 458 | for (j, column) in index.columns.iter().enumerate() { |
| 459 | let js_column = cx.string(column.clone()); |
| 460 | js_index_columns.set(&mut cx, j as u32, js_column)?; |
| 461 | } |
| 462 | js_index.set(&mut cx, "columns", js_index_columns)?; |
| 463 | |
| 464 | output.set(&mut cx, i as u32, js_index)?; |
| 465 | } |
| 466 | |
| 467 | Ok(output) |
| 468 | }) |
| 469 | }); |
| 470 | Ok(promise) |
| 471 | } |
| 472 | |
| 473 | pub(crate) fn js_index_stats(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 474 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 475 | let rt = runtime(&mut cx)?; |
| 476 | let (deferred, promise) = cx.promise(); |
| 477 | let index_name = cx.argument::<JsString>(0)?.value(&mut cx); |
| 478 | let channel = cx.channel(); |
| 479 | let table = js_table.table.clone(); |
| 480 | |
| 481 | rt.spawn(async move { |
| 482 | let load_stats = table.index_stats(index_name).await; |
| 483 | |
| 484 | deferred.settle_with(&channel, move |mut cx| { |
| 485 | let stats = load_stats.or_throw(&mut cx)?; |
| 486 | |
| 487 | if let Some(stats) = stats { |
| 488 | let output = JsObject::new(&mut cx); |
| 489 | let num_indexed_rows = cx.number(stats.num_indexed_rows as f64); |
| 490 | output.set(&mut cx, "numIndexedRows", num_indexed_rows)?; |
| 491 | let num_unindexed_rows = cx.number(stats.num_unindexed_rows as f64); |
| 492 | output.set(&mut cx, "numUnindexedRows", num_unindexed_rows)?; |
| 493 | if let Some(distance_type) = stats.distance_type { |
| 494 | let distance_type = cx.string(distance_type.to_string()); |
| 495 | output.set(&mut cx, "distanceType", distance_type)?; |
| 496 | } |
| 497 | let index_type = cx.string(stats.index_type.to_string()); |
| 498 | output.set(&mut cx, "indexType", index_type)?; |
| 499 | |
| 500 | if let Some(num_indices) = stats.num_indices { |
| 501 | let num_indices = cx.number(num_indices as f64); |
| 502 | output.set(&mut cx, "numIndices", num_indices)?; |
| 503 | } |
| 504 | |
| 505 | Ok(output.as_value(&mut cx)) |
| 506 | } else { |
| 507 | Ok(JsNull::new(&mut cx).as_value(&mut cx)) |
| 508 | } |
| 509 | }) |
| 510 | }); |
| 511 | |
| 512 | Ok(promise) |
| 513 | } |
| 514 | |
| 515 | pub(crate) fn js_schema(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 516 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 517 | let rt = runtime(&mut cx)?; |
| 518 | let (deferred, promise) = cx.promise(); |
| 519 | let channel = cx.channel(); |
| 520 | let table = js_table.table.clone(); |
| 521 | |
| 522 | let is_electron = cx |
| 523 | .argument::<JsBoolean>(0) |
| 524 | .or_throw(&mut cx)? |
| 525 | .value(&mut cx); |
| 526 | |
| 527 | rt.spawn(async move { |
| 528 | let schema = table.schema().await; |
| 529 | deferred.settle_with(&channel, move |mut cx| { |
| 530 | let schema = schema.or_throw(&mut cx)?; |
| 531 | let batches = vec![RecordBatch::new_empty(schema)]; |
| 532 | let buffer = record_batch_to_buffer(batches).or_throw(&mut cx)?; |
| 533 | convert::new_js_buffer(buffer, &mut cx, is_electron) |
| 534 | }) |
| 535 | }); |
| 536 | Ok(promise) |
| 537 | } |
| 538 | |
| 539 | pub(crate) fn js_add_columns(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 540 | let expressions = cx |
| 541 | .argument::<JsArray>(0)? |
| 542 | .to_vec(&mut cx)? |
| 543 | .into_iter() |
| 544 | .map(|val| { |
| 545 | let obj = val.downcast_or_throw::<JsObject, _>(&mut cx)?; |
| 546 | let name = obj.get::<JsString, _, _>(&mut cx, "name")?.value(&mut cx); |
| 547 | let sql = obj |
| 548 | .get::<JsString, _, _>(&mut cx, "valueSql")? |
| 549 | .value(&mut cx); |
| 550 | Ok((name, sql)) |
| 551 | }) |
| 552 | .collect::<NeonResult<Vec<(String, String)>>>()?; |
| 553 | |
| 554 | let transforms = NewColumnTransform::SqlExpressions(expressions); |
| 555 | |
| 556 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 557 | let rt = runtime(&mut cx)?; |
| 558 | |
| 559 | let (deferred, promise) = cx.promise(); |
| 560 | let channel = cx.channel(); |
| 561 | let table = js_table.table.clone(); |
| 562 | |
| 563 | rt.spawn(async move { |
| 564 | let result = table.add_columns(transforms, None).await; |
| 565 | deferred.settle_with(&channel, move |mut cx| { |
| 566 | result.or_throw(&mut cx)?; |
| 567 | Ok(cx.undefined()) |
| 568 | }) |
| 569 | }); |
| 570 | |
| 571 | Ok(promise) |
| 572 | } |
| 573 | |
| 574 | pub(crate) fn js_alter_columns(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 575 | let alterations = cx |
| 576 | .argument::<JsArray>(0)? |
| 577 | .to_vec(&mut cx)? |
| 578 | .into_iter() |
| 579 | .map(|val| { |
| 580 | let obj = val.downcast_or_throw::<JsObject, _>(&mut cx)?; |
| 581 | let path = obj.get::<JsString, _, _>(&mut cx, "path")?.value(&mut cx); |
| 582 | let rename = obj |
| 583 | .get_opt::<JsString, _, _>(&mut cx, "rename")? |
| 584 | .map(|val| val.value(&mut cx)); |
| 585 | let nullable = obj |
| 586 | .get_opt::<JsBoolean, _, _>(&mut cx, "nullable")? |
| 587 | .map(|val| val.value(&mut cx)); |
| 588 | // TODO: support data type here. Will need to do some serialization/deserialization |
| 589 | |
| 590 | if rename.is_none() && nullable.is_none() { |
| 591 | return cx.throw_error("At least one of 'name' or 'nullable' must be provided"); |
| 592 | } |
| 593 | |
| 594 | Ok(ColumnAlteration { |
| 595 | path, |
| 596 | rename, |
| 597 | nullable, |
| 598 | // TODO: wire up this field |
| 599 | data_type: None, |
| 600 | }) |
| 601 | }) |
| 602 | .collect::<NeonResult<Vec<ColumnAlteration>>>()?; |
| 603 | |
| 604 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 605 | let rt = runtime(&mut cx)?; |
| 606 | |
| 607 | let (deferred, promise) = cx.promise(); |
| 608 | let channel = cx.channel(); |
| 609 | let table = js_table.table.clone(); |
| 610 | |
| 611 | rt.spawn(async move { |
| 612 | let result = table.alter_columns(&alterations).await; |
| 613 | deferred.settle_with(&channel, move |mut cx| { |
| 614 | result.or_throw(&mut cx)?; |
| 615 | Ok(cx.undefined()) |
| 616 | }) |
| 617 | }); |
| 618 | |
| 619 | Ok(promise) |
| 620 | } |
| 621 | |
| 622 | pub(crate) fn js_drop_columns(mut cx: FunctionContext) -> JsResult<JsPromise> { |
| 623 | let columns = cx |
| 624 | .argument::<JsArray>(0)? |
| 625 | .to_vec(&mut cx)? |
| 626 | .into_iter() |
| 627 | .map(|val| { |
| 628 | Ok(val |
| 629 | .downcast_or_throw::<JsString, _>(&mut cx)? |
| 630 | .value(&mut cx)) |
| 631 | }) |
| 632 | .collect::<NeonResult<Vec<String>>>()?; |
| 633 | |
| 634 | let js_table = cx.this().downcast_or_throw::<JsBox<Self>, _>(&mut cx)?; |
| 635 | let rt = runtime(&mut cx)?; |
| 636 | |
| 637 | let (deferred, promise) = cx.promise(); |
| 638 | let channel = cx.channel(); |
| 639 | let table = js_table.table.clone(); |
| 640 | |
| 641 | rt.spawn(async move { |
| 642 | let col_refs = columns.iter().map(|s| s.as_str()).collect::<Vec<_>>(); |
| 643 | let result = table.drop_columns(&col_refs).await; |
| 644 | deferred.settle_with(&channel, move |mut cx| { |
| 645 | result.or_throw(&mut cx)?; |
| 646 | Ok(cx.undefined()) |
| 647 | }) |
| 648 | }); |
| 649 | |
| 650 | Ok(promise) |
| 651 | } |
| 652 | } |