-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathlance.hpp
More file actions
1785 lines (1579 loc) · 73.5 KB
/
Copy pathlance.hpp
File metadata and controls
1785 lines (1579 loc) · 73.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: Apache-2.0 */
/* SPDX-FileCopyrightText: Copyright The Lance Authors */
/**
* @file lance.hpp
* @brief C++ RAII wrappers for the Lance C API.
*
* Header-only library providing:
* - lance::Error exception class
* - lance::Dataset RAII handle with builder-pattern Scanner
* - lance::Scanner fluent API
* - All data exchange via Arrow C Data Interface
*/
#ifndef LANCE_HPP
#define LANCE_HPP
#include "lance/lance.h"
#include <array>
#include <cstdint>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace lance {
// ─── Error ───────────────────────────────────────────────────────────────────
class Error : public std::runtime_error {
public:
LanceErrorCode code;
Error(LanceErrorCode code, std::string msg)
: std::runtime_error(std::move(msg)), code(code) {}
};
/// Check thread-local error and throw if non-OK.
inline void check_error() {
LanceErrorCode code = lance_last_error_code();
if (code != LANCE_OK) {
const char* msg = lance_last_error_message();
std::string owned(msg ? msg : "Unknown error");
if (msg) lance_free_string(msg);
throw Error(code, std::move(owned));
}
}
/// Release and free a library-allocated ArrowArrayStream returned by
/// Scanner::scan_async. NULL-safe; do not use for caller-allocated streams.
inline void scanner_async_stream_free(ArrowArrayStream* stream) noexcept {
lance_scanner_async_stream_free(stream);
}
// ─── RAII Handle Template ────────────────────────────────────────────────────
template <typename T, void (*Deleter)(T*)>
class Handle {
T* ptr_;
public:
explicit Handle(T* ptr = nullptr) : ptr_(ptr) {}
~Handle() {
if (ptr_) Deleter(ptr_);
}
Handle(Handle&& o) noexcept : ptr_(o.ptr_) { o.ptr_ = nullptr; }
Handle& operator=(Handle&& o) noexcept {
if (this != &o) {
if (ptr_) Deleter(ptr_);
ptr_ = o.ptr_;
o.ptr_ = nullptr;
}
return *this;
}
Handle(const Handle&) = delete;
Handle& operator=(const Handle&) = delete;
T* get() const { return ptr_; }
T* release() {
auto p = ptr_;
ptr_ = nullptr;
return p;
}
explicit operator bool() const { return ptr_ != nullptr; }
};
// ─── Forward Declarations ────────────────────────────────────────────────────
class Scanner;
class IndexModel;
class IndexSegmentBuilder;
class IndexSegmentMetadata;
class FtsQueryContext;
// ─── Version history ─────────────────────────────────────────────────────────
/// Metadata for a single dataset version.
/// `id` mirrors the upstream Version::version (monotonic manifest version);
/// `timestamp_ms` is Unix epoch milliseconds.
struct VersionInfo {
uint64_t id;
int64_t timestamp_ms;
};
/// Per-field storage statistics for query planning.
/// `id` is the schema field id; `bytes_on_disk` is the compressed on-disk size
/// (0 for datasets written with the legacy v1 storage format).
struct FieldStatistics {
uint32_t id;
uint64_t bytes_on_disk;
};
// ─── Write mode ──────────────────────────────────────────────────────────────
enum class WriteMode : int32_t {
Create = LANCE_WRITE_CREATE,
Append = LANCE_WRITE_APPEND,
Overwrite = LANCE_WRITE_OVERWRITE,
};
enum class FtsCoverageMode : int32_t {
Strict = LANCE_FTS_COVERAGE_STRICT,
IndexOnly = LANCE_FTS_COVERAGE_INDEX_ONLY,
};
enum class FtsMatchOperator : int32_t {
Or = LANCE_FTS_MATCH_OPERATOR_OR,
And = LANCE_FTS_MATCH_OPERATOR_AND,
};
/// Tunable parameters for Dataset::write. Numeric fields default-out via 0;
/// `data_storage_version` defaults out via `std::nullopt`.
///
/// `enable_stable_row_ids` has no default sentinel — whatever value the
/// caller writes is forwarded to upstream. Today this matches upstream's
/// default (`false`), so a default-constructed WriteParams is a no-op; if
/// upstream ever changes its default, callers must set this field explicitly.
struct WriteParams {
uint64_t max_rows_per_file = 0;
uint64_t max_rows_per_group = 0;
uint64_t max_bytes_per_file = 0;
/// Lance file format version, e.g. "2.0", "2.1", "stable", "legacy".
std::optional<std::string> data_storage_version;
bool enable_stable_row_ids = false;
};
// ─── Column alteration ───────────────────────────────────────────────────────
/// A single alteration applied to one column by `Dataset::alter_columns`.
/// Every non-`path` field is optional; at least one must request a change.
///
/// `data_type`, when non-null, borrows an Arrow C Data Interface `ArrowSchema`
/// describing the target type. The caller owns it and must keep it alive for
/// the duration of the `alter_columns` call; the wrapper does not release it.
struct ColumnAlteration {
std::string path;
std::optional<std::string> rename;
LanceColumnNullableMode nullable_mode = LANCE_COLUMN_NULLABLE_UNCHANGED;
const ArrowSchema* data_type = nullptr;
};
// ─── New column (SQL) ────────────────────────────────────────────────────────
/// A single new column defined by a SQL expression over the dataset's existing
/// columns, added by `Dataset::add_columns_sql`. Both fields are required and
/// non-empty, e.g. `{ "doubled", "x * 2" }`.
struct SqlColumn {
std::string name;
std::string expression;
};
// ─── Shared Session ──────────────────────────────────────────────────────────
class Session {
Handle<LanceSession, lance_session_close> handle_;
public:
Session(uint64_t index_cache_size_bytes, uint64_t metadata_cache_size_bytes)
: handle_(lance_session_new(index_cache_size_bytes, metadata_cache_size_bytes)) {
if (!handle_) check_error();
}
LanceSessionCacheStats cache_stats() const {
LanceSessionCacheStats stats{};
if (lance_session_get_cache_stats(handle_.get(), &stats) != 0)
check_error();
return stats;
}
const LanceSession* c_handle() const { return handle_.get(); }
};
// ─── Process-local FTS query context ────────────────────────────────────────
/// Immutable, query-specific global BM25 scorer plus pinned FTS segment list.
/// This handle is process-local and intentionally has no serialization API.
class FtsQueryContext {
Handle<LanceFtsQueryContext, lance_fts_query_context_close> handle_;
public:
explicit FtsQueryContext(LanceFtsQueryContext* context) : handle_(context) {}
FtsQueryContext(FtsQueryContext&&) noexcept = default;
FtsQueryContext& operator=(FtsQueryContext&&) noexcept = default;
FtsQueryContext(const FtsQueryContext&) = delete;
FtsQueryContext& operator=(const FtsQueryContext&) = delete;
const LanceFtsQueryContext* c_handle() const { return handle_.get(); }
};
// ─── Blob file ───────────────────────────────────────────────────────────────
/// RAII handle over one value of a Blob v2 column, from `Dataset::take_blobs()`
/// or `take_blobs_by_indices()`. Stays usable after the Dataset is destroyed.
/// `read()` and `read_up_to()` advance the cursor, `read_range()` does not.
/// Not thread-safe per handle.
class BlobFile {
Handle<LanceBlobFile, lance_blob_file_close> handle_;
public:
/// Adopt a handle from the C API; closed on destruction.
explicit BlobFile(LanceBlobFile* blob) : handle_(blob) {}
/// Size of the blob in bytes. Independent of the cursor.
uint64_t size() const {
uint64_t n = lance_blob_file_size(handle_.get());
if (lance_last_error_code() != LANCE_OK) check_error();
return n;
}
/// Read from the cursor to the end (the whole blob when the cursor is 0).
std::vector<uint8_t> read() {
uint64_t blob_size = size();
uint64_t cursor = tell();
uint64_t remaining = cursor >= blob_size ? 0 : blob_size - cursor;
std::vector<uint8_t> out(static_cast<size_t>(remaining));
if (lance_blob_file_read(handle_.get(), out.data(), out.size()) != 0)
check_error();
return out;
}
/// Read at most `len` bytes from the current cursor, advancing it past
/// them. The result is shorter than `len` at the end of the blob.
std::vector<uint8_t> read_up_to(size_t len) {
std::vector<uint8_t> out(len);
size_t bytes_read = 0;
if (lance_blob_file_read_up_to(
handle_.get(), out.data(), len, &bytes_read) != 0)
check_error();
out.resize(bytes_read);
return out;
}
/// Read exactly `len` bytes at `offset` without moving the cursor. The
/// range must lie within the blob.
std::vector<uint8_t> read_range(uint64_t offset, size_t len) const {
std::vector<uint8_t> out(len);
if (lance_blob_file_read_range(
handle_.get(), offset, out.data(), len) != 0)
check_error();
return out;
}
/// Move the cursor. Seeking past the end is allowed; reads then return
/// no bytes.
void seek(uint64_t pos) {
if (lance_blob_file_seek(handle_.get(), pos) != 0) check_error();
}
/// Current cursor position, in bytes from the start of the blob.
uint64_t tell() const {
uint64_t pos = 0;
if (lance_blob_file_tell(handle_.get(), &pos) != 0) check_error();
return pos;
}
};
// ─── Dataset ─────────────────────────────────────────────────────────────────
class Dataset {
Handle<LanceDataset, lance_dataset_close> handle_;
static std::vector<const char*> to_c_storage_options(
const std::vector<std::pair<std::string, std::string>>& storage_opts) {
std::vector<const char*> kv;
for (auto& [k, v] : storage_opts) {
kv.push_back(k.c_str());
kv.push_back(v.c_str());
}
kv.push_back(nullptr);
return kv;
}
/// Move raw handles into RAII owners. `blobs` must be reserved up front so
/// nothing can throw while handles are still unowned.
///
/// Leak-freedom also rests on the C side: `lance_dataset_take_blobs*` fill
/// `out` all-or-nothing and leave it untouched on error. A partial fill
/// before an error would leak, because `check_error()` throws before this
/// runs and `raw` owns nothing.
static void adopt_blobs(const std::vector<LanceBlobFile*>& raw,
std::vector<std::optional<BlobFile>>& blobs) {
for (auto* blob : raw) {
if (blob) {
blobs.emplace_back(BlobFile(blob));
} else {
blobs.emplace_back(std::nullopt);
}
}
}
public:
/// Open a dataset at the given URI. Pass `version` = 0 (the default) for
/// the latest, or a specific version id from `versions()` to check out
/// that version, e.g. `lance::Dataset::open("data.lance", {}, /*version=*/42)`.
static Dataset open(
const std::string& uri,
const std::vector<std::pair<std::string, std::string>>& storage_opts = {},
uint64_t version = 0) {
auto kv = to_c_storage_options(storage_opts);
const char* const* opts_ptr =
storage_opts.empty() ? nullptr : kv.data();
auto* ds = lance_dataset_open(uri.c_str(), opts_ptr, version);
if (!ds) check_error();
return Dataset(ds);
}
/// Open a dataset with caches owned by `session`. The returned dataset
/// remains valid if the Session wrapper is destroyed first.
static Dataset open_with_session(
const Session& session,
const std::string& uri,
const std::vector<std::pair<std::string, std::string>>& storage_opts = {},
uint64_t version = 0) {
auto kv = to_c_storage_options(storage_opts);
const char* const* opts_ptr =
storage_opts.empty() ? nullptr : kv.data();
auto* ds = lance_dataset_open_with_session(
uri.c_str(), opts_ptr, version, session.c_handle());
if (!ds) check_error();
return Dataset(ds);
}
/// Write an Arrow record batch stream to a Lance dataset and return the
/// open dataset at the committed version.
///
/// The stream must be self-describing; its own schema is used. Treat the
/// stream as consumed once this call returns or throws — do not reuse it.
/// Throws lance::Error on failure (including if `stream` is null).
static Dataset write(
const std::string& uri,
ArrowArrayStream* stream,
WriteMode mode,
const std::vector<std::pair<std::string, std::string>>& storage_opts = {}) {
return write(uri, stream, mode, WriteParams{}, storage_opts);
}
/// Same as the four-argument `write` but tunes the output via `params`.
/// Pass a default-constructed `WriteParams{}` to inherit upstream defaults.
static Dataset write(
const std::string& uri,
ArrowArrayStream* stream,
WriteMode mode,
const WriteParams& params,
const std::vector<std::pair<std::string, std::string>>& storage_opts = {}) {
if (stream == nullptr) {
throw Error(LANCE_ERR_INVALID_ARGUMENT, "stream must not be null");
}
// RAII guard for the stream. Until `lance_dataset_write_with_params`
// is called, any exception (failed `get_schema`, `std::bad_alloc`
// while building `kv`, etc.) must release the stream. After that call
// Rust owns it, so we `disarm()` immediately before invoking the C API.
struct StreamGuard {
ArrowArrayStream* s;
bool armed = true;
// Explicit constructor: `= delete`d copy/move ctors disqualify
// this from being an aggregate under C++20, so brace-init like
// `StreamGuard{stream}` would otherwise fail to compile there.
explicit StreamGuard(ArrowArrayStream* p) noexcept : s(p) {}
~StreamGuard() noexcept {
if (armed && s && s->release) s->release(s);
}
void disarm() noexcept { armed = false; }
StreamGuard(const StreamGuard&) = delete;
StreamGuard& operator=(const StreamGuard&) = delete;
StreamGuard(StreamGuard&&) = delete;
StreamGuard& operator=(StreamGuard&&) = delete;
} stream_guard{stream};
// Defensive: a non-conforming or already-released producer may have a
// null `get_schema`. Without this guard a bad caller would crash with
// a null function-pointer dereference on the next line.
if (stream->get_schema == nullptr) {
throw Error(LANCE_ERR_INVALID_ARGUMENT,
"stream get_schema callback is null");
}
// Arm SchemaGuard before calling `get_schema` so a non-conforming
// producer that partially populates the schema before returning an
// error still has its `release` fired on unwind. The zero-init keeps
// the destructor a no-op on the clean-error path (release == null).
struct SchemaGuard {
ArrowSchema* s;
// Explicit constructor for the same C++20 aggregate-init reason
// documented on StreamGuard above.
explicit SchemaGuard(ArrowSchema* p) noexcept : s(p) {}
~SchemaGuard() noexcept {
if (s && s->release) s->release(s);
}
SchemaGuard(const SchemaGuard&) = delete;
SchemaGuard& operator=(const SchemaGuard&) = delete;
SchemaGuard(SchemaGuard&&) = delete;
SchemaGuard& operator=(SchemaGuard&&) = delete;
};
ArrowSchema schema = {};
SchemaGuard schema_guard{&schema};
// On failure, StreamGuard releases the stream and SchemaGuard
// releases any partial schema state — preserving the "consumed on
// return or throw" contract for both resources.
if (stream->get_schema(stream, &schema) != 0) {
const char* err = stream->get_last_error
? stream->get_last_error(stream)
: nullptr;
std::string msg = std::string("failed to read stream schema: ") +
(err ? err : "unknown");
throw Error(LANCE_ERR_INVALID_ARGUMENT, msg);
}
std::vector<const char*> kv;
for (auto& [k, v] : storage_opts) {
kv.push_back(k.c_str());
kv.push_back(v.c_str());
}
kv.push_back(nullptr);
const char* const* opts_ptr =
storage_opts.empty() ? nullptr : kv.data();
LanceWriteParams c_params = {};
c_params.max_rows_per_file = params.max_rows_per_file;
c_params.max_rows_per_group = params.max_rows_per_group;
c_params.max_bytes_per_file = params.max_bytes_per_file;
c_params.data_storage_version =
params.data_storage_version ? params.data_storage_version->c_str() : nullptr;
c_params.enable_stable_row_ids = params.enable_stable_row_ids;
// The C API consumes the stream on every return path, so disarm the
// guard before calling. After this point the stream pointer is logically
// owned by Rust and any C++-side exception must not re-release it.
stream_guard.disarm();
LanceDataset* out = nullptr;
int32_t rc = lance_dataset_write_with_params(
uri.c_str(),
&schema,
stream,
static_cast<int32_t>(mode),
&c_params,
opts_ptr,
&out);
if (rc != 0) check_error();
// Defensive null guard: a conforming Rust impl never returns rc == 0
// with `out == nullptr`, but constructing a Dataset around a null
// handle would silently crash on the first method call. Throw
// explicitly rather than going through `check_error()` because the
// thread-local code is `LANCE_OK` on this path (rc == 0).
if (!out) {
throw Error(LANCE_ERR_INTERNAL,
"lance_dataset_write_with_params returned success with null out_dataset");
}
return Dataset(out);
}
/// Number of rows in the dataset.
uint64_t count_rows() const {
uint64_t n = lance_dataset_count_rows(handle_.get());
if (lance_last_error_code() != LANCE_OK) check_error();
return n;
}
/// Version of this dataset snapshot.
uint64_t version() const {
uint64_t v = lance_dataset_version(handle_.get());
if (lance_last_error_code() != LANCE_OK) check_error();
return v;
}
/// Latest version ID (queries object store).
uint64_t latest_version() const {
uint64_t v = lance_dataset_latest_version(handle_.get());
if (lance_last_error_code() != LANCE_OK) check_error();
return v;
}
/// Snapshot the dataset's version history, ordered by version id.
/// Throws lance::Error on failure.
std::vector<VersionInfo> versions() const {
auto* raw = lance_dataset_versions(handle_.get());
if (!raw) check_error();
Handle<LanceVersions, lance_versions_close> snap(raw);
uint64_t n = lance_versions_count(snap.get());
if (lance_last_error_code() != LANCE_OK) check_error();
std::vector<VersionInfo> out;
out.reserve(static_cast<size_t>(n));
for (uint64_t i = 0; i < n; i++) {
VersionInfo info;
info.id = lance_versions_id_at(snap.get(), static_cast<size_t>(i));
if (lance_last_error_code() != LANCE_OK) check_error();
info.timestamp_ms =
lance_versions_timestamp_ms_at(snap.get(), static_cast<size_t>(i));
if (lance_last_error_code() != LANCE_OK) check_error();
out.push_back(info);
}
return out;
}
/// Compute per-field data statistics (compressed on-disk byte size) for
/// query planning, ordered by schema field id. Performs I/O over every
/// fragment. Throws lance::Error on failure.
std::vector<FieldStatistics> calculate_data_stats() const {
auto* raw = lance_dataset_calculate_data_stats(handle_.get());
if (!raw) check_error();
Handle<LanceDataStatistics, lance_data_statistics_close> snap(raw);
uint64_t n = lance_data_statistics_count(snap.get());
if (lance_last_error_code() != LANCE_OK) check_error();
std::vector<FieldStatistics> out;
out.reserve(static_cast<size_t>(n));
for (uint64_t i = 0; i < n; i++) {
FieldStatistics fs;
fs.id = lance_data_statistics_field_id_at(snap.get(), static_cast<size_t>(i));
if (lance_last_error_code() != LANCE_OK) check_error();
fs.bytes_on_disk =
lance_data_statistics_bytes_on_disk_at(snap.get(), static_cast<size_t>(i));
if (lance_last_error_code() != LANCE_OK) check_error();
out.push_back(fs);
}
return out;
}
/// Commit a new manifest that aliases `version` as the latest. The
/// returned Dataset points at the target version; this handle is
/// unchanged. If `version` is already the latest, no new manifest is
/// written. Throws lance::Error on failure.
Dataset restore(uint64_t version) const {
auto* out = lance_dataset_restore(handle_.get(), version);
if (!out) check_error();
return Dataset(out);
}
/// Delete rows matching the SQL `predicate`, committing a new manifest.
/// Mutates this dataset in place; the handle continues to point at the
/// new version. Returns the number of rows that were deleted.
/// Throws lance::Error on failure (empty predicate, malformed SQL,
/// commit conflict, ...).
///
/// Named `delete_rows` to avoid the C++ `delete` keyword.
uint64_t delete_rows(const std::string& predicate) {
uint64_t num_deleted = 0;
if (lance_dataset_delete(handle_.get(), predicate.c_str(), &num_deleted) != 0) {
check_error();
}
return num_deleted;
}
/// Update rows matching the SQL `predicate` by applying per-column SQL
/// expressions. Mutates this dataset in place; the handle continues to
/// point at the new version. Returns the number of rows updated.
///
/// `predicate` is empty -> updates every row (passed as NULL to the C
/// API). `updates` must be non-empty; each pair is `{column_name,
/// sql_expr}`. Throws lance::Error on failure (empty pair entry,
/// malformed SQL, unknown column, commit conflict, ...).
uint64_t update(
const std::string& predicate,
const std::vector<std::pair<std::string, std::string>>& updates) {
std::vector<const char*> col_ptrs;
std::vector<const char*> val_ptrs;
col_ptrs.reserve(updates.size());
val_ptrs.reserve(updates.size());
for (const auto& [col, val] : updates) {
col_ptrs.push_back(col.c_str());
val_ptrs.push_back(val.c_str());
}
uint64_t num_updated = 0;
const char* pred_ptr = predicate.empty() ? nullptr : predicate.c_str();
if (lance_dataset_update(
handle_.get(),
pred_ptr,
col_ptrs.data(),
val_ptrs.data(),
updates.size(),
&num_updated) != 0) {
check_error();
}
return num_updated;
}
/// Merge `source` into this dataset keyed on `on_columns`, committing a
/// new manifest. Defaults to find-or-create semantics (insert rows that
/// do not match an existing key). Returns the per-call insert / update /
/// delete counts.
///
/// `on_columns` must be non-empty. `params` controls match behavior; pass
/// `nullptr` for find-or-create defaults. `source` is consumed.
/// Throws lance::Error on failure (empty key, schema mismatch, malformed
/// SQL, missing expression for *_IF mode, commit conflict, ...).
LanceMergeInsertResult merge_insert(
const std::vector<std::string>& on_columns,
ArrowArrayStream* source,
const LanceMergeInsertParams* params = nullptr) {
std::vector<const char*> col_ptrs;
col_ptrs.reserve(on_columns.size());
for (const auto& c : on_columns) {
col_ptrs.push_back(c.c_str());
}
LanceMergeInsertResult result{};
if (lance_dataset_merge_insert(
handle_.get(),
col_ptrs.data(),
on_columns.size(),
source,
params,
&result) != 0) {
check_error();
}
return result;
}
/// Convenience: classic upsert (when_matched=UpdateAll, when_not_matched=InsertAll).
LanceMergeInsertResult upsert(
const std::vector<std::string>& on_columns,
ArrowArrayStream* source) {
LanceMergeInsertParams params{};
params.when_matched = LANCE_MERGE_WHEN_MATCHED_UPDATE_ALL;
params.when_not_matched = LANCE_MERGE_WHEN_NOT_MATCHED_INSERT_ALL;
params.when_not_matched_by_source = LANCE_MERGE_WHEN_NOT_MATCHED_BY_SOURCE_KEEP;
return merge_insert(on_columns, source, ¶ms);
}
/// Compact small or deleted-heavy fragments into larger ones, committing
/// a new manifest. A clean dataset is a no-op — all-zero metrics and the
/// version is unchanged. Pass `nullptr` for upstream defaults.
/// Throws lance::Error on failure (commit conflict, ...).
LanceCompactionMetrics compact_files(
const LanceCompactionOptions* options = nullptr) {
LanceCompactionMetrics metrics{};
if (lance_dataset_compact_files(handle_.get(), options, &metrics) != 0) {
check_error();
}
return metrics;
}
/// Drop columns from the dataset's schema and commit a new manifest.
/// Metadata-only — data files remain until a later `compact_files()`
/// call rewrites them. Mutates this dataset in place; the handle
/// continues to point at the new version.
///
/// `columns` must be non-empty. Throws lance::Error on failure (empty
/// list, unknown column, attempt to drop every column, commit
/// conflict, ...).
void drop_columns(const std::vector<std::string>& columns) {
std::vector<const char*> col_ptrs;
col_ptrs.reserve(columns.size());
for (const auto& c : columns) {
col_ptrs.push_back(c.c_str());
}
// Pass `col_ptrs.data()` unconditionally — matches the `update`
// and `merge_insert` siblings whose inputs are also required to
// be non-empty. The Rust layer rejects `num_columns == 0` before
// dereferencing the pointer, so an empty vector still surfaces
// INVALID_ARGUMENT with the precise "num_columns must be > 0"
// message rather than the misleading "columns must not be NULL".
if (lance_dataset_drop_columns(
handle_.get(), col_ptrs.data(), columns.size()) != 0) {
check_error();
}
}
/// Apply one or more column alterations (rename / nullability / type
/// change) and commit a new manifest. Rename and nullability-only
/// changes are zero-copy and preserve any indices on the affected
/// columns; a type change rewrites the column's data files and drops
/// any indices that referenced it.
///
/// `alterations` must be non-empty and each entry must request at least
/// one change. Any `data_type` pointer must remain valid for the
/// duration of this call. Throws lance::Error on failure (empty list,
/// no-op alteration, unknown column, incompatible cast, tightening
/// nullability when NULLs exist, commit conflict, ...).
void alter_columns(const std::vector<ColumnAlteration>& alterations) {
// The C strings we install in each entry borrow from `alterations`
// (the caller's std::strings), which outlive this call. The entries
// themselves are copied by value into `raw`, so any reallocation
// during push_back just moves the raw bytes — pointer values are
// preserved. `reserve` is a performance hint, not a lifetime guard.
std::vector<LanceColumnAlteration> raw;
raw.reserve(alterations.size());
for (const auto& a : alterations) {
LanceColumnAlteration entry{};
entry.path = a.path.c_str();
entry.rename = a.rename ? a.rename->c_str() : nullptr;
entry.nullable_mode = static_cast<int32_t>(a.nullable_mode);
entry.data_type = a.data_type;
raw.push_back(entry);
}
if (lance_dataset_alter_columns(
handle_.get(), raw.data(), raw.size()) != 0) {
check_error();
}
}
/// Add columns computed from SQL expressions over the dataset's existing
/// columns, committing a new manifest. `batch_size = 0` uses the upstream
/// default scan batch size.
///
/// `columns` must be non-empty and each entry's `name` and `expression`
/// must be non-empty. Throws lance::Error on failure (empty list, empty
/// name/expression, malformed SQL syntax, a reference to a non-existent
/// column, name collision with an existing column, commit conflict, ...).
void add_columns_sql(const std::vector<SqlColumn>& columns,
uint64_t batch_size = 0) {
// The C strings we install in each entry borrow from `columns` (the
// caller's std::strings), which outlive this call. The entries are
// copied by value into `raw`, so any reallocation during push_back
// just moves the raw bytes — pointer values are preserved.
std::vector<LanceSqlColumn> raw;
raw.reserve(columns.size());
for (const auto& c : columns) {
LanceSqlColumn entry{};
entry.name = c.name.c_str();
entry.expression = c.expression.c_str();
raw.push_back(entry);
}
// Pass `raw.data()` unconditionally — matches the `alter_columns` and
// `drop_columns` siblings whose inputs are also required to be
// non-empty. An empty `columns` yields `num_columns == 0`, which the
// Rust layer rejects before it indexes the pointer.
if (lance_dataset_add_columns_sql(
handle_.get(), raw.data(), raw.size(), batch_size) != 0) {
check_error();
}
}
/// Add all-null columns described by an Arrow schema, committing a new
/// manifest. Metadata-only on non-legacy datasets. Every field in `schema`
/// must be nullable. The caller owns `schema` and must keep it alive for
/// the duration of the call; the wrapper does not release it.
///
/// Throws lance::Error on failure (invalid schema, non-nullable field, name
/// collision with an existing column, commit conflict, ...). A legacy-format
/// dataset throws with code `LANCE_ERR_NOT_SUPPORTED` (all-null columns are
/// metadata-only and the legacy format cannot represent them that way).
void add_columns_nulls(const ArrowSchema* schema) {
if (lance_dataset_add_columns_nulls(handle_.get(), schema) != 0) {
check_error();
}
}
/// Add columns by splicing precomputed data from an Arrow C stream into the
/// dataset, committing a new manifest. `batch_size = 0` uses the upstream
/// default. When non-null, `stream` is consumed (released) on every return
/// path — including a null-dataset error and when this method throws — so do
/// not use it again afterward. Only a null `stream` is rejected without
/// consuming anything.
///
/// The stream's total row count must match the dataset exactly. Throws
/// lance::Error on failure (row-count mismatch, name collision with an
/// existing column, commit conflict, ...).
void add_columns_stream(ArrowArrayStream* stream, uint64_t batch_size = 0) {
// Forward `stream` straight to the C API, which owns the stream and
// releases it on every path. No RAII guard is needed here (unlike
// `write`, which builds vectors before its C call): nothing between this
// method's entry and the call below can throw, so the stream can never
// be stranded by an exception. WARNING: do not add any throwing code
// before the C call without first arming a stream-release guard.
if (lance_dataset_add_columns_stream(
handle_.get(), stream, batch_size) != 0) {
check_error();
}
}
/// Export the schema as an Arrow C Data Interface struct.
void schema(ArrowSchema* out) const {
if (lance_dataset_schema(handle_.get(), out) != 0) {
check_error();
}
}
/// Take rows by indices. `out` is caller-owned and its non-null `release`
/// must be called exactly once. Deferred iteration/cleanup panics are
/// contained by the exported stream guard.
void take(const uint64_t* indices, size_t num_indices,
const std::vector<std::string>& columns,
ArrowArrayStream* out) const {
std::vector<const char*> col_ptrs;
for (auto& c : columns) col_ptrs.push_back(c.c_str());
col_ptrs.push_back(nullptr);
const char* const* cols_ptr = columns.empty() ? nullptr : col_ptrs.data();
if (lance_dataset_take(handle_.get(), indices, num_indices, cols_ptr, out) != 0) {
check_error();
}
}
/// Take all columns with the same stream ownership as the overload above.
void take(const uint64_t* indices, size_t num_indices,
ArrowArrayStream* out) const {
if (lance_dataset_take(handle_.get(), indices, num_indices, nullptr, out) != 0) {
check_error();
}
}
/// Take rows by dataset row IDs. `out` is caller-owned and its non-null
/// `release` must be called exactly once. Deferred iteration/cleanup panics
/// are contained by the exported stream guard.
void take_rows(const uint64_t* row_ids, size_t num_row_ids,
const std::vector<std::string>& columns,
ArrowArrayStream* out) const {
std::vector<const char*> col_ptrs;
for (auto& c : columns) col_ptrs.push_back(c.c_str());
col_ptrs.push_back(nullptr);
const char* const* cols_ptr = columns.empty() ? nullptr : col_ptrs.data();
if (lance_dataset_take_rows(
handle_.get(), row_ids, num_row_ids, cols_ptr, out) != 0) {
check_error();
}
}
/// Take all columns by dataset row IDs with the same stream ownership as
/// the overload above.
void take_rows(const uint64_t* row_ids, size_t num_row_ids,
ArrowArrayStream* out) const {
if (lance_dataset_take_rows(
handle_.get(), row_ids, num_row_ids, nullptr, out) != 0) {
check_error();
}
}
/// Take blob handles by dataset row ID; element `i` is for `row_ids[i]`,
/// `std::nullopt` for a null blob value.
std::vector<std::optional<BlobFile>> take_blobs(
const uint64_t* row_ids, size_t num_row_ids,
const std::string& column) const {
std::vector<LanceBlobFile*> raw(num_row_ids, nullptr);
std::vector<std::optional<BlobFile>> blobs;
blobs.reserve(num_row_ids);
// An empty vector's data() may be null, which the C side rejects.
if (num_row_ids > 0 &&
lance_dataset_take_blobs(handle_.get(), row_ids, num_row_ids,
column.c_str(), raw.data()) != 0) {
check_error();
}
adopt_blobs(raw, blobs);
return blobs;
}
/// Take blob handles by 0-based row index, with the same ownership and
/// null-slot semantics as the overload above.
std::vector<std::optional<BlobFile>> take_blobs_by_indices(
const uint64_t* indices, size_t num_indices,
const std::string& column) const {
std::vector<LanceBlobFile*> raw(num_indices, nullptr);
std::vector<std::optional<BlobFile>> blobs;
blobs.reserve(num_indices);
// Same empty-request shortcut as take_blobs().
if (num_indices > 0 &&
lance_dataset_take_blobs_by_indices(
handle_.get(), indices, num_indices,
column.c_str(), raw.data()) != 0) {
check_error();
}
adopt_blobs(raw, blobs);
return blobs;
}
/// Create a Scanner builder for this dataset.
Scanner scan() const;
/// Compatibility wrapper for an OR Match query.
[[deprecated("Use prepare_fts_match_query() to select the Match operator")]]
FtsQueryContext prepare_fts_query(
const std::string& column,
const std::string& query,
uint32_t max_fuzzy_distance = 0,
FtsCoverageMode coverage_mode = FtsCoverageMode::Strict) const {
return prepare_fts_match_query(column, query, FtsMatchOperator::Or,
max_fuzzy_distance, coverage_mode);
}
/// Prepare a Match query with a global BM25 scorer. AND and OR are
/// supported. `max_fuzzy_distance` is reserved and currently must be zero;
/// keeping it here avoids another API change when canonical cross-segment
/// fuzzy vocabulary injection becomes available.
FtsQueryContext prepare_fts_match_query(
const std::string& column,
const std::string& query,
FtsMatchOperator match_operator = FtsMatchOperator::Or,
uint32_t max_fuzzy_distance = 0,
FtsCoverageMode coverage_mode = FtsCoverageMode::Strict) const {
auto* context = lance_dataset_prepare_fts_match_query(
handle_.get(), column.c_str(), query.c_str(),
static_cast<int32_t>(match_operator), max_fuzzy_distance,
static_cast<int32_t>(coverage_mode));
if (!context) check_error();
return FtsQueryContext(context);
}
/// Prepare a Phrase query. Its FTS index must store token positions and
/// slop must be non-negative.
FtsQueryContext prepare_fts_phrase_query(
const std::string& column,
const std::string& query,
int32_t slop = 0,
FtsCoverageMode coverage_mode = FtsCoverageMode::Strict) const {
auto* context = lance_dataset_prepare_fts_phrase_query(
handle_.get(), column.c_str(), query.c_str(), slop,
static_cast<int32_t>(coverage_mode));
if (!context) check_error();
return FtsQueryContext(context);
}
/// Number of fragments in the dataset.
uint64_t fragment_count() const {
uint64_t n = lance_dataset_fragment_count(handle_.get());
if (lance_last_error_code() != LANCE_OK) check_error();
return n;
}
/// Get all fragment IDs.
std::vector<uint64_t> fragment_ids() const {
auto count = fragment_count();
std::vector<uint64_t> ids(count);
if (count > 0) {
if (lance_dataset_fragment_ids(handle_.get(), ids.data()) != 0)
check_error();
}
return ids;
}
/// Create a vector index on a column.
void create_vector_index(const std::string& column,
const LanceVectorIndexParams& params,
const std::string& name = "",
bool replace = false) {
const char* name_c = name.empty() ? nullptr : name.c_str();
if (lance_dataset_create_vector_index(handle_.get(), column.c_str(),
name_c, ¶ms, replace) != 0)
check_error();
}
/// Create a scalar index on a column.
void create_scalar_index(const std::string& column,
LanceScalarIndexType index_type,
const std::string& name = "",
const std::string& params_json = "",
bool replace = false) {
const char* name_c = name.empty() ? nullptr : name.c_str();
const char* json_c = params_json.empty() ? nullptr : params_json.c_str();
if (lance_dataset_create_scalar_index(handle_.get(), column.c_str(),
name_c, index_type,
json_c, replace) != 0)
check_error();
}
/// Create a single-use builder for an uncommitted scalar index segment.
/// The builder owns a snapshot, so it remains valid independently of this
/// Dataset object's lifetime.
IndexSegmentBuilder new_scalar_index_segment_builder(
const std::string& column,
LanceScalarIndexType index_type,
const std::string& index_name = "",
const std::string& params_json = "",
const LanceIndexSegmentBuildOptions* options = nullptr) const;
/// Create a single-use builder for an uncommitted vector index segment.
IndexSegmentBuilder new_vector_index_segment_builder(
const std::string& column,
const LanceVectorIndexParams& params,
const std::string& index_name = "",
const LanceIndexSegmentBuildOptions* options = nullptr) const;
/// Train shared IVF centroids as an Arrow C Data Interface array/schema.
IndexModel train_ivf_model(
const std::string& column,
uint32_t num_partitions,