Repository navigation
Expand file tree
/
Copy pathfragment.rs
More file actions
6238 lines (5721 loc) · 233 KB
/
Copy pathfragment.rs
File metadata and controls
6238 lines (5721 loc) · 233 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
//! Wraps a Fragment of the dataset.
pub mod session;
pub mod write;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use arrow::compute::concat_batches;
use arrow_array::cast::as_primitive_array;
use arrow_array::types::UInt64Type;
use arrow_array::{
Array, RecordBatch, RecordBatchReader, StructArray, UInt32Array, UInt64Array, new_null_array,
};
use arrow_schema::Schema as ArrowSchema;
use datafusion::logical_expr::Expr;
use datafusion::scalar::ScalarValue;
use futures::future::{BoxFuture, try_join_all};
use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, join, stream};
use lance_arrow::json::{convert_json_columns, has_json_fields, is_arrow_json_field};
use lance_arrow::{RecordBatchExt, SchemaExt};
use lance_core::datatypes::{OnMissing, OnTypeMismatch, SchemaCompareOptions};
use lance_core::utils::address::RowAddress;
use lance_core::utils::deletion::DeletionVector;
use lance_core::utils::tokio::get_num_compute_intensive_cpus;
use lance_core::{Error, Result, cache::CacheKey, datatypes::Schema};
use lance_core::{
ROW_ADDR, ROW_ADDR_FIELD, ROW_CREATED_AT_VERSION_FIELD, ROW_ID, ROW_ID_FIELD,
ROW_LAST_UPDATED_AT_VERSION_FIELD,
};
use lance_datafusion::utils::StreamingWriteSource;
use lance_encoding::decoder::DecoderPlugins;
use lance_file::previous::reader::{
FileReader as PreviousFileReader, read_batch as previous_read_batch,
};
use lance_file::reader::{
CachedFileMetadata, FileMetadataIndex, FileReaderOptions, ProjectedFileReader, ReaderProjection,
};
use lance_file::version::LanceFileVersion;
use lance_file::{LanceEncodingsIo, determine_file_version};
use lance_io::ReadBatchParams;
use lance_io::scheduler::{FileScheduler, ScanScheduler, SchedulerConfig};
use lance_io::utils::CachedFileSize;
use lance_table::format::{DataFile, DeletionFile, Fragment};
use lance_table::io::deletion::{deletion_file_path, write_deletion_file};
use lance_table::rowids::RowIdSequence;
use lance_table::utils::stream::{
ReadBatchFutStream, ReadBatchTask, ReadBatchTaskStream, RowIdAndDeletesConfig,
wrap_with_row_id_and_delete,
};
use roaring::RoaringBitmap;
use self::write::FragmentCreateBuilder;
use super::hash_joiner::HashJoiner;
use super::rowids::load_row_id_sequence;
use super::scanner::Scanner;
use super::updater::Updater;
use super::{NewColumnTransform, WriteParams, schema_evolution};
use crate::dataset::Dataset;
use crate::dataset::fragment::session::FragmentSession;
use crate::dataset::overlay::{
OverlayReadPlanner, merge_overlay_batch, plan_overlays, resolve_overlays,
};
use crate::io::deletion::read_dataset_deletion_file;
/// Result of [`FileFragment::update_columns_with_offsets`]: updated fragment metadata, modified field ids,
/// and physical row offsets that matched the join (for stable row-id version metadata).
#[derive(Debug, Clone)]
pub struct FragmentUpdateColumnsResult {
pub fragment: Fragment,
pub fields_modified: Vec<u32>,
/// Physical row offsets (0-based within this fragment) whose columns were rewritten from the right-hand stream.
pub matched_offsets: RoaringBitmap,
}
/// A Fragment of a Lance [`Dataset`].
///
/// The interface is modeled after `pyarrow.dataset.Fragment`.
#[derive(Debug, Clone)]
pub struct FileFragment {
dataset: Arc<Dataset>,
pub(super) metadata: Fragment,
}
const DEFAULT_BATCH_READ_SIZE: u32 = 1024;
/// A trait for file readers to be implemented by both the v1 and v2 readers
///
/// The `read_*_tasks` methods are async because for v2 files they drive
/// the decode scheduler's `initialize` step (and, for small reads, the
/// synchronous scheduling that follows) before returning the stream.
/// Doing that work here keeps it on whichever task awaits this call —
/// typically a per-fragment `tokio::spawn` — instead of smuggling it
/// into the first poll of the returned stream.
#[allow(clippy::len_without_is_empty)]
pub trait GenericFileReader: std::fmt::Debug + Send + Sync {
/// Reads the requested range of rows from the file, returning as a stream
/// of tasks.
fn read_range_tasks(
&self,
range: Range<u64>,
batch_size: u32,
projection: Arc<lance_core::datatypes::Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>>;
/// Reads the requested ranges of rows from the file, only supported by v2
fn read_ranges_tasks(
&self,
ranges: Arc<[Range<u64>]>,
batch_size: u32,
projection: Arc<lance_core::datatypes::Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>>;
/// Reads all rows from the file, returning as a stream of tasks
fn read_all_tasks(
&self,
batch_size: u32,
projection: Arc<lance_core::datatypes::Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>>;
/// Take specific rows from the file, returning as a stream of tasks
fn take_all_tasks(
&self,
indices: &[u32],
batch_size: u32,
projection: Arc<lance_core::datatypes::Schema>,
take_priority: Option<u32>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>>;
/// Return the number of rows in the file
fn len(&self) -> u32;
/// Schema of the reader
fn projection(&self) -> &Arc<Schema>;
/// Get storage statistics for this file (ignored by v1 reader)
fn storage_stats(&self) -> Result<Vec<(u32, u64)>>;
// Helper functions to fallback to the legacy implementation while we
// slowly migrate functionality over to the generic reader
// Clone the reader, this is needed because Box<dyn Foo: Clone> doesn't
// implement Clone
fn clone_box(&self) -> Box<dyn GenericFileReader>;
// Return true if the reader is a v1 reader
fn is_legacy(&self) -> bool;
// Return a reference to the legacy reader, panics if called on a v2
// file.
fn as_legacy(&self) -> &PreviousFileReader {
self.as_legacy_opt()
.expect("legacy function called on v2 file")
}
// Return a reference to the legacy reader if this is a v1 reader and
// return None otherwise
fn as_legacy_opt(&self) -> Option<&PreviousFileReader>;
// Return a mutable reference to the legacy reader if this is a v1 reader
// and return None otherwise
fn as_legacy_opt_mut(&mut self) -> Option<&mut PreviousFileReader>;
}
fn ranges_to_tasks(
reader: &PreviousFileReader,
ranges: Vec<(i32, Range<usize>)>,
projection: Arc<Schema>,
) -> ReadBatchTaskStream {
let reader = reader.clone();
stream::iter(ranges)
.map(move |(batch_idx, range)| {
let num_rows = range.end - range.start;
let reader = reader.clone();
let projection = projection.clone();
let task = tokio::task::spawn(async move {
previous_read_batch(
&reader,
&ReadBatchParams::Range(range.clone()),
&projection,
batch_idx,
)
.await
})
.map(|task_out| task_out.unwrap())
.boxed();
ReadBatchTask {
task,
num_rows: num_rows as u32,
}
})
.boxed()
}
#[derive(Clone, Debug)]
struct V1Reader {
reader: PreviousFileReader,
projection: Arc<Schema>,
}
impl V1Reader {
fn new(reader: PreviousFileReader, projection: Arc<Schema>) -> Self {
Self { reader, projection }
}
}
impl GenericFileReader for V1Reader {
/// Reads the requested range of rows from the file, returning as a stream
fn read_range_tasks(
&self,
range: Range<u64>,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
let mut to_skip = range.start as u32;
let mut remaining = range.end as u32 - to_skip;
let mut ranges = Vec::new();
let mut batch_idx = 0;
while remaining > 0 {
let next_batch_len = self.reader.num_rows_in_batch(batch_idx) as u32;
let next_batch_idx = batch_idx;
batch_idx += 1;
if to_skip >= next_batch_len {
to_skip -= next_batch_len;
continue;
}
let batch_start = to_skip;
to_skip = 0;
let batch_end = next_batch_len.min(batch_start + remaining);
remaining -= batch_end - batch_start;
for chunk_start in (batch_start..batch_end).step_by(batch_size as usize) {
let chunk_end = (chunk_start + batch_size).min(batch_end);
ranges.push((next_batch_idx, (chunk_start as usize..chunk_end as usize)));
}
}
let stream = ranges_to_tasks(&self.reader, ranges, projection);
async move { Ok(stream) }.boxed()
}
fn read_all_tasks(
&self,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
let ranges = (0..self.reader.num_batches())
.flat_map(move |batch_idx| {
let rows_in_batch = self.reader.num_rows_in_batch(batch_idx as i32);
(0..rows_in_batch)
.step_by(batch_size as usize)
.map(move |start| {
let end = (start + batch_size as usize).min(rows_in_batch);
(batch_idx as i32, start..end)
})
})
.collect::<Vec<_>>();
let stream = ranges_to_tasks(&self.reader, ranges, projection);
async move { Ok(stream) }.boxed()
}
fn read_ranges_tasks(
&self,
_ranges: Arc<[Range<u64>]>,
_batch_size: u32,
_projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
async move {
Err(Error::internal(
"Attempt to perform FilteredRead on v1 files".to_string(),
))
}
.boxed()
}
fn take_all_tasks(
&self,
indices: &[u32],
_batch_size: u32,
projection: Arc<Schema>,
_take_priority: Option<u32>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
let indices_vec = indices.to_vec();
let reader = self.reader.clone();
let num_rows = indices.len() as u32;
async move {
// In the new path the row id is added by the fragment and not the file
let task_fut =
async move { reader.take(&indices_vec, projection.as_ref()).await }.boxed();
let task = std::future::ready(ReadBatchTask {
task: task_fut,
num_rows,
})
.boxed();
Ok(futures::stream::once(task).boxed())
}
.boxed()
}
fn projection(&self) -> &Arc<Schema> {
&self.projection
}
/// Return the number of rows in the file
fn len(&self) -> u32 {
self.reader.len() as u32
}
fn storage_stats(&self) -> Result<Vec<(u32, u64)>> {
// No-op for v1 files
Ok(Vec::new())
}
fn clone_box(&self) -> Box<dyn GenericFileReader> {
Box::new(self.clone())
}
fn is_legacy(&self) -> bool {
true
}
fn as_legacy_opt(&self) -> Option<&PreviousFileReader> {
Some(&self.reader)
}
fn as_legacy_opt_mut(&mut self) -> Option<&mut PreviousFileReader> {
Some(&mut self.reader)
}
}
mod v2_adapter {
use lance_encoding::decoder::FilterExpression;
use super::*;
#[derive(Debug, Clone)]
pub struct Reader {
reader: Arc<ProjectedFileReader>,
projection: Arc<Schema>,
field_id_to_column_idx: Arc<BTreeMap<u32, u32>>,
default_priority: u32,
file_scheduler: FileScheduler,
}
impl Reader {
pub fn new(
reader: Arc<ProjectedFileReader>,
projection: Arc<Schema>,
field_id_to_column_idx: Arc<BTreeMap<u32, u32>>,
default_priority: u32,
file_scheduler: FileScheduler,
) -> Self {
Self {
reader,
projection,
field_id_to_column_idx,
default_priority,
file_scheduler,
}
}
}
impl GenericFileReader for Reader {
/// Reads the requested range of rows from the file, returning as a stream
fn read_range_tasks(
&self,
range: Range<u64>,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
async move {
let projection = ReaderProjection::from_field_ids(
self.reader.version(),
projection.as_ref(),
self.field_id_to_column_idx.as_ref(),
)?;
Ok(self
.reader
.read_tasks(
ReadBatchParams::Range(range.start as usize..range.end as usize),
batch_size,
Some(projection),
FilterExpression::no_filter(),
)
.await?
.map(|v2_task| ReadBatchTask {
task: v2_task.task.map_err(Error::from).boxed(),
num_rows: v2_task.num_rows,
})
.boxed())
}
.boxed()
}
fn read_ranges_tasks(
&self,
ranges: Arc<[Range<u64>]>,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
async move {
let projection = ReaderProjection::from_field_ids(
self.reader.version(),
projection.as_ref(),
self.field_id_to_column_idx.as_ref(),
)?;
Ok(self
.reader
.read_tasks(
ReadBatchParams::Ranges(ranges),
batch_size,
Some(projection),
FilterExpression::no_filter(),
)
.await?
.map(|v2_task| ReadBatchTask {
task: v2_task.task.map_err(Error::from).boxed(),
num_rows: v2_task.num_rows,
})
.boxed())
}
.boxed()
}
fn read_all_tasks(
&self,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
async move {
let projection = ReaderProjection::from_field_ids(
self.reader.version(),
projection.as_ref(),
self.field_id_to_column_idx.as_ref(),
)?;
Ok(self
.reader
.read_tasks(
ReadBatchParams::RangeFull,
batch_size,
Some(projection),
FilterExpression::no_filter(),
)
.await?
.map(|v2_task| ReadBatchTask {
task: v2_task.task.map_err(Error::from).boxed(),
num_rows: v2_task.num_rows,
})
.boxed())
}
.boxed()
}
fn take_all_tasks(
&self,
indices: &[u32],
batch_size: u32,
projection: Arc<Schema>,
take_priority: Option<u32>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
let indices = UInt32Array::from(indices.to_vec());
async move {
let projection = ReaderProjection::from_field_ids(
self.reader.version(),
projection.as_ref(),
self.field_id_to_column_idx.as_ref(),
)?;
let reader = if let Some(take_priority) = take_priority {
let op_priority = ((take_priority as u64) << 32) | self.default_priority as u64;
let scheduler = self.file_scheduler.with_priority(op_priority);
Arc::new(
self.reader
.with_scheduler(Arc::new(LanceEncodingsIo::new(scheduler))),
)
} else {
self.reader.clone()
};
Ok(reader
.read_tasks(
ReadBatchParams::Indices(indices),
batch_size,
Some(projection),
FilterExpression::no_filter(),
)
.await?
.map(|v2_task| ReadBatchTask {
task: v2_task.task.map_err(Error::from).boxed(),
num_rows: v2_task.num_rows,
})
.boxed())
}
.boxed()
}
fn storage_stats(&self) -> Result<Vec<(u32, u64)>> {
let file_statistics = self.reader.file_statistics().ok_or_else(|| {
Error::internal("storage_stats requires full file metadata".to_string())
})?;
let column_idx_to_field_id = self
.field_id_to_column_idx
.iter()
.map(|(field_id, column_idx)| (*column_idx, *field_id))
.collect::<HashMap<_, _>>();
let mut stats = Vec::new();
// Some fields span more than one column. We assume a column that doesn't have an
// entry in the field_id_to_column_idx map is a continuation of the previous field.
let mut current_field_id = 0;
for (column_idx, col_stats) in file_statistics.columns.iter().enumerate() {
if let Some(field_id) = column_idx_to_field_id.get(&(column_idx as u32)) {
current_field_id = *field_id;
}
stats.push((current_field_id, col_stats.size_bytes));
}
Ok(stats)
}
fn projection(&self) -> &Arc<Schema> {
&self.projection
}
/// Return the number of rows in the file
fn len(&self) -> u32 {
self.reader.num_rows() as u32
}
fn clone_box(&self) -> Box<dyn GenericFileReader> {
Box::new(self.clone())
}
fn is_legacy(&self) -> bool {
false
}
fn as_legacy_opt(&self) -> Option<&PreviousFileReader> {
None
}
fn as_legacy_opt_mut(&mut self) -> Option<&mut PreviousFileReader> {
None
}
}
}
/// A reader where all rows are null. Used when there are fields that have no
/// data files in a fragment.
#[derive(Debug, Clone)]
struct NullReader {
schema: Arc<Schema>,
num_rows: u32,
}
impl NullReader {
fn new(schema: Arc<Schema>, num_rows: u32) -> Self {
Self { schema, num_rows }
}
fn batch(projection: Arc<ArrowSchema>, num_rows: usize) -> RecordBatch {
let columns = projection
.fields()
.iter()
.map(|f| new_null_array(f.data_type(), num_rows))
.collect::<Vec<_>>();
RecordBatch::try_new(projection, columns).unwrap()
}
}
impl GenericFileReader for NullReader {
fn read_range_tasks(
&self,
range: Range<u64>,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
self.read_ranges_tasks(vec![range].into(), batch_size, projection)
}
fn read_ranges_tasks(
&self,
ranges: Arc<[Range<u64>]>,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
let mut remaining_rows = ranges.iter().map(|r| r.end - r.start).sum::<u64>();
let projection: Arc<ArrowSchema> = Arc::new(projection.as_ref().into());
let task_iter = std::iter::from_fn(move || {
if remaining_rows == 0 {
return None;
}
let num_rows = remaining_rows.min(batch_size as u64) as usize;
remaining_rows -= num_rows as u64;
let batch = Self::batch(projection.clone(), num_rows);
let task = ReadBatchTask {
task: futures::future::ready(Ok(batch)).boxed(),
num_rows: num_rows as u32,
};
Some(task)
});
async move { Ok(futures::stream::iter(task_iter).boxed()) }.boxed()
}
fn read_all_tasks(
&self,
batch_size: u32,
projection: Arc<Schema>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
self.read_ranges_tasks(vec![0..self.num_rows as u64].into(), batch_size, projection)
}
fn take_all_tasks(
&self,
indices: &[u32],
batch_size: u32,
projection: Arc<Schema>,
_take_priority: Option<u32>,
) -> BoxFuture<'_, Result<ReadBatchTaskStream>> {
let num_rows = indices.len() as u64;
self.read_ranges_tasks(vec![0..num_rows].into(), batch_size, projection)
}
fn storage_stats(&self) -> Result<Vec<(u32, u64)>> {
// No-op for null reader
Ok(Vec::new())
}
fn projection(&self) -> &Arc<Schema> {
&self.schema
}
fn len(&self) -> u32 {
self.num_rows
}
fn clone_box(&self) -> Box<dyn GenericFileReader> {
Box::new(self.clone())
}
fn is_legacy(&self) -> bool {
false
}
fn as_legacy_opt(&self) -> Option<&PreviousFileReader> {
None
}
fn as_legacy_opt_mut(&mut self) -> Option<&mut PreviousFileReader> {
None
}
}
#[derive(Debug, Default, Clone)]
pub struct FragReadConfig {
// Add the row id column
pub with_row_id: bool,
// Add the row address column
pub with_row_address: bool,
// Add the last updated at version column
pub with_row_last_updated_at_version: bool,
// Add the created at version column
pub with_row_created_at_version: bool,
/// The scan scheduler to use for reading data files.
///
/// This should be specified if multiple readers are being used in
/// an operation
pub scan_scheduler: Option<Arc<ScanScheduler>>,
/// The default scan priority to use for reading data files
///
/// Only used if `scan_scheduler` is provided
///
/// The overall priority for reads will be
///
/// operation_priority: u32 | reader_priority: u32 | file_position: u64
pub reader_priority: Option<u32>,
/// File reader options to use when reading data files.
pub file_reader_options: Option<FileReaderOptions>,
}
impl FragReadConfig {
pub fn with_row_id(mut self, value: bool) -> Self {
self.with_row_id = value;
self
}
pub fn with_row_address(mut self, value: bool) -> Self {
self.with_row_address = value;
self
}
pub fn with_row_last_updated_at_version(mut self, value: bool) -> Self {
self.with_row_last_updated_at_version = value;
self
}
pub fn with_row_created_at_version(mut self, value: bool) -> Self {
self.with_row_created_at_version = value;
self
}
pub fn has_system_cols(&self) -> bool {
self.with_row_id
|| self.with_row_address
|| self.with_row_last_updated_at_version
|| self.with_row_created_at_version
}
pub fn with_scan_scheduler(mut self, value: Arc<ScanScheduler>) -> Self {
self.scan_scheduler = Some(value);
self
}
pub fn with_reader_priority(mut self, value: u32) -> Self {
self.reader_priority = Some(value);
self
}
pub fn with_file_reader_options(mut self, value: FileReaderOptions) -> Self {
self.file_reader_options = Some(value);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MetadataMode {
LazyAllowed,
Full,
}
impl FileFragment {
/// Creates a new FileFragment.
pub fn new(dataset: Arc<Dataset>, metadata: Fragment) -> Self {
Self { dataset, metadata }
}
/// Create a new [`FileFragment`] from a [`StreamingWriteSource`].
///
/// This method can be used before a `Dataset` is created. For example,
/// Fragments can be created distributed first, before a central machine to
/// commit the dataset with these fragments.
///
pub async fn create(
dataset_uri: &str,
id: usize,
source: impl StreamingWriteSource,
params: Option<WriteParams>,
) -> Result<Fragment> {
let mut builder = FragmentCreateBuilder::new(dataset_uri);
if let Some(params) = params.as_ref() {
builder = builder.write_params(params);
}
builder.write(source, Some(id as u64)).await
}
/// Create a list of [`FileFragment`] from a [`StreamingWriteSource`].
pub async fn create_fragments(
dataset_uri: &str,
source: impl StreamingWriteSource,
params: Option<WriteParams>,
) -> Result<Vec<Fragment>> {
let mut builder = FragmentCreateBuilder::new(dataset_uri);
if let Some(params) = params.as_ref() {
builder = builder.write_params(params);
}
builder.write_fragments(source).await
}
pub async fn create_from_file(
filename: &str,
dataset: &Dataset,
fragment_id: usize,
physical_rows: Option<usize>,
) -> Result<Fragment> {
let filepath = dataset.data_dir().join(filename);
let file_version =
determine_file_version(dataset.object_store.as_ref(), &filepath, None).await?;
if file_version != dataset.manifest.data_storage_format.lance_file_version()? {
return Err(Error::invalid_input(format!(
"File version mismatch. Dataset version: {:?} Fragment version: {:?}",
dataset.manifest.data_storage_format.lance_file_version()?,
file_version
)));
}
if file_version == LanceFileVersion::Legacy {
let fragment = Fragment::with_file_legacy(
fragment_id as u64,
filename,
dataset.schema(),
physical_rows,
);
Ok(fragment)
} else {
// Load the file metadata, confirm the schema is compatible, and
// determine the column offsets
let mut frag = Fragment::new(fragment_id as u64);
let scheduler = ScanScheduler::new(
dataset.object_store.clone(),
SchedulerConfig::max_bandwidth(&dataset.object_store),
);
let file_scheduler = scheduler
.open_file(&filepath, &CachedFileSize::unknown())
.await?;
let reader = lance_file::reader::FileReader::try_open(
file_scheduler,
None,
Arc::<DecoderPlugins>::default(),
&dataset.metadata_cache.file_metadata_cache(&filepath),
dataset.file_reader_options.clone().unwrap_or_default(),
)
.await?;
// If the schemas are not compatible we can't calculate field id offsets
reader
.schema()
.check_compatible(dataset.schema(), &SchemaCompareOptions::default())?;
let projection = lance_file::reader::ReaderProjection::from_whole_schema(
dataset.schema(),
reader.metadata().version(),
);
let physical_rows = reader.metadata().num_rows as usize;
frag.physical_rows = Some(physical_rows);
frag.id = fragment_id as u64;
let column_indices = projection
.column_indices
.into_iter()
.map(|c| c as i32)
.collect();
frag.add_file(
filename,
dataset.schema().field_ids(),
column_indices,
&file_version,
None,
);
Ok(frag)
}
}
/// Returns storage stats as `(field_id, bytes_on_disk)` pairs for this fragment.
pub(crate) async fn storage_stats(
&self,
dataset_schema: &Schema,
scan_scheduler: Arc<ScanScheduler>,
) -> Result<Vec<(u32, u64)>> {
let mut stats = Vec::new();
for reader in self
.open_readers_with_full_metadata(
dataset_schema,
&FragReadConfig::default().with_scan_scheduler(scan_scheduler),
)
.await?
{
stats.extend(reader.storage_stats()?);
}
Ok(stats)
}
pub fn dataset(&self) -> &Dataset {
self.dataset.as_ref()
}
pub fn schema(&self) -> &Schema {
self.dataset.schema()
}
/// Returns the fragment's metadata.
pub fn metadata(&self) -> &Fragment {
&self.metadata
}
/// The id of this [`FileFragment`].
pub fn id(&self) -> usize {
self.metadata.id as usize
}
/// The number of data files in this fragment.
pub fn num_data_files(&self) -> usize {
self.metadata.files.len()
}
/// Gets the data file for a given field
pub fn data_file_for_field(&self, field_id: u32) -> Option<&DataFile> {
self.metadata
.files
.iter()
.find(|f| f.fields.contains(&(field_id as i32)))
}
/// Open a FileFragment with a given default projection.
///
/// All read operations (other than `read_projected`) will use the supplied
/// default projection. For `read_projected`, the projection must be a subset
/// of the default projection.
///
/// Parameters
/// - `projection`: The projection schema.
/// - `read_config`: Controls what columns are included in the output.
/// - `scan_scheduler`: The scheduler to use for reading data files. If not supplied
/// and the data is v2 data then a new scheduler will be created
///
/// `projection` may be an empty schema only if `with_row_id` is true. In that
/// case, the reader will only be generating row ids.
pub async fn open(
&self,
projection: &Schema,
read_config: FragReadConfig,
) -> Result<FragmentReader> {
let open_files = self.open_readers(projection, &read_config);
let deletion_vec_load = self.get_deletion_vector();
let row_id_load = if self.dataset.manifest.uses_stable_row_ids() {
futures::future::Either::Left(
load_row_id_sequence(&self.dataset, &self.metadata).map_ok(Some),
)
} else {
futures::future::Either::Right(futures::future::ready(Ok(None)))
};
let (opened_files, deletion_vec, row_id_sequence) =
join!(open_files, deletion_vec_load, row_id_load);
let opened_files = opened_files?;
let deletion_vec = deletion_vec?;
let row_id_sequence = row_id_sequence?;
if opened_files.is_empty() && !read_config.has_system_cols() {
return Err(Error::not_found(format!(
"No data files found for schema: {}, fragment_id={}",
projection,
self.id()
)));
}
let num_physical_rows = self.physical_rows().await?;
let mut reader = FragmentReader::try_new(
self.id(),
deletion_vec,
row_id_sequence,
opened_files,
ArrowSchema::from(projection),
self.count_rows(None).await?,
num_physical_rows,
Arc::new(self.metadata.clone()),
)?;
// Plan overlay resolution from coverage metadata (no files opened here); the
// readers are opened lazily on read, pruned to the rows each read touches.
if !self.metadata.overlays.is_empty() {
let planner = plan_overlays(self, projection)?;
if !planner.is_empty() {
reader.overlay = Some(OverlayReadState {
planner: Arc::new(planner),
fragment: Arc::new(self.clone()),
read_config: Arc::new(read_config.clone()),
});
}
}
if read_config.with_row_id {
reader.with_row_id();
}
if read_config.with_row_address {
reader.with_row_address();
}
if read_config.with_row_last_updated_at_version {
reader.with_row_last_updated_at_version();
}
if read_config.with_row_created_at_version {
reader.with_row_created_at_version();
}
Ok(reader)
}
fn get_field_id_offset(data_file: &DataFile) -> u32 {
data_file.fields.first().copied().unwrap_or(0) as u32
}
fn should_try_indexed_metadata(
data_file: &DataFile,
projection: &ReaderProjection,
file_version: LanceFileVersion,
) -> bool {
if !ProjectedFileReader::supports_projection(projection, file_version) {
return false;
}
let total_columns = data_file
.column_indices
.iter()
.filter(|column_index| **column_index >= 0)
.count();