-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathscan.rs
1875 lines (1597 loc) · 67.4 KB
/
scan.rs
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Table scan api.
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use arrow_array::RecordBatch;
use futures::channel::mpsc::{channel, Sender};
use futures::stream::BoxStream;
use futures::{SinkExt, StreamExt, TryFutureExt, TryStreamExt};
use serde::{Deserialize, Serialize};
use crate::arrow::ArrowReaderBuilder;
use crate::expr::visitors::expression_evaluator::ExpressionEvaluator;
use crate::expr::visitors::inclusive_metrics_evaluator::InclusiveMetricsEvaluator;
use crate::expr::visitors::inclusive_projection::InclusiveProjection;
use crate::expr::visitors::manifest_evaluator::ManifestEvaluator;
use crate::expr::{Bind, BoundPredicate, Predicate};
use crate::io::object_cache::ObjectCache;
use crate::io::FileIO;
use crate::runtime::spawn;
use crate::spec::{
DataContentType, DataFileFormat, ManifestContentType, ManifestEntryRef, ManifestFile,
ManifestList, Schema, SchemaRef, SnapshotRef, TableMetadataRef,
};
use crate::table::Table;
use crate::utils::available_parallelism;
use crate::{Error, ErrorKind, Result};
/// A stream of [`FileScanTask`].
pub type FileScanTaskStream = BoxStream<'static, Result<FileScanTask>>;
/// A stream of arrow [`RecordBatch`]es.
pub type ArrowRecordBatchStream = BoxStream<'static, Result<RecordBatch>>;
/// Builder to create table scan.
pub struct TableScanBuilder<'a> {
table: &'a Table,
// Defaults to none which means select all columns
column_names: Option<Vec<String>>,
snapshot_id: Option<i64>,
batch_size: Option<usize>,
case_sensitive: bool,
filter: Option<Predicate>,
concurrency_limit_data_files: usize,
concurrency_limit_manifest_entries: usize,
concurrency_limit_manifest_files: usize,
row_group_filtering_enabled: bool,
row_selection_enabled: bool,
}
impl<'a> TableScanBuilder<'a> {
pub(crate) fn new(table: &'a Table) -> Self {
let num_cpus = available_parallelism().get();
Self {
table,
column_names: None,
snapshot_id: None,
batch_size: None,
case_sensitive: true,
filter: None,
concurrency_limit_data_files: num_cpus,
concurrency_limit_manifest_entries: num_cpus,
concurrency_limit_manifest_files: num_cpus,
row_group_filtering_enabled: true,
row_selection_enabled: false,
}
}
/// Sets the desired size of batches in the response
/// to something other than the default
pub fn with_batch_size(mut self, batch_size: Option<usize>) -> Self {
self.batch_size = batch_size;
self
}
/// Sets the scan's case sensitivity
pub fn with_case_sensitive(mut self, case_sensitive: bool) -> Self {
self.case_sensitive = case_sensitive;
self
}
/// Specifies a predicate to use as a filter
pub fn with_filter(mut self, predicate: Predicate) -> Self {
// calls rewrite_not to remove Not nodes, which must be absent
// when applying the manifest evaluator
self.filter = Some(predicate.rewrite_not());
self
}
/// Select all columns.
pub fn select_all(mut self) -> Self {
self.column_names = None;
self
}
/// Select empty columns.
pub fn select_empty(mut self) -> Self {
self.column_names = Some(vec![]);
self
}
/// Select some columns of the table.
pub fn select(mut self, column_names: impl IntoIterator<Item = impl ToString>) -> Self {
self.column_names = Some(
column_names
.into_iter()
.map(|item| item.to_string())
.collect(),
);
self
}
/// Set the snapshot to scan. When not set, it uses current snapshot.
pub fn snapshot_id(mut self, snapshot_id: i64) -> Self {
self.snapshot_id = Some(snapshot_id);
self
}
/// Sets the concurrency limit for both manifest files and manifest
/// entries for this scan
pub fn with_concurrency_limit(mut self, limit: usize) -> Self {
self.concurrency_limit_manifest_files = limit;
self.concurrency_limit_manifest_entries = limit;
self.concurrency_limit_data_files = limit;
self
}
/// Sets the data file concurrency limit for this scan
pub fn with_data_file_concurrency_limit(mut self, limit: usize) -> Self {
self.concurrency_limit_data_files = limit;
self
}
/// Sets the manifest entry concurrency limit for this scan
pub fn with_manifest_entry_concurrency_limit(mut self, limit: usize) -> Self {
self.concurrency_limit_manifest_entries = limit;
self
}
/// Determines whether to enable row group filtering.
/// When enabled, if a read is performed with a filter predicate,
/// then the metadata for each row group in the parquet file is
/// evaluated against the filter predicate and row groups
/// that cant contain matching rows will be skipped entirely.
///
/// Defaults to enabled, as it generally improves performance or
/// keeps it the same, with performance degradation unlikely.
pub fn with_row_group_filtering_enabled(mut self, row_group_filtering_enabled: bool) -> Self {
self.row_group_filtering_enabled = row_group_filtering_enabled;
self
}
/// Determines whether to enable row selection.
/// When enabled, if a read is performed with a filter predicate,
/// then (for row groups that have not been skipped) the page index
/// for each row group in a parquet file is parsed and evaluated
/// against the filter predicate to determine if ranges of rows
/// within a row group can be skipped, based upon the page-level
/// statistics for each column.
///
/// Defaults to being disabled. Enabling requires parsing the parquet page
/// index, which can be slow enough that parsing the page index outweighs any
/// gains from the reduced number of rows that need scanning.
/// It is recommended to experiment with partitioning, sorting, row group size,
/// page size, and page row limit Iceberg settings on the table being scanned in
/// order to get the best performance from using row selection.
pub fn with_row_selection_enabled(mut self, row_selection_enabled: bool) -> Self {
self.row_selection_enabled = row_selection_enabled;
self
}
/// Build the table scan.
pub fn build(self) -> Result<TableScan> {
let snapshot = match self.snapshot_id {
Some(snapshot_id) => self
.table
.metadata()
.snapshot_by_id(snapshot_id)
.ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!("Snapshot with id {} not found", snapshot_id),
)
})?
.clone(),
None => self
.table
.metadata()
.current_snapshot()
.ok_or_else(|| {
Error::new(ErrorKind::Unexpected, "Can't scan table without snapshots")
})?
.clone(),
};
let schema = snapshot.schema(self.table.metadata())?;
// Check that all column names exist in the schema.
if let Some(column_names) = self.column_names.as_ref() {
for column_name in column_names {
if schema.field_by_name(column_name).is_none() {
return Err(Error::new(
ErrorKind::DataInvalid,
format!(
"Column {} not found in table. Schema: {}",
column_name, schema
),
));
}
}
}
let mut field_ids = vec![];
let column_names = self.column_names.clone().unwrap_or_else(|| {
schema
.as_struct()
.fields()
.iter()
.map(|f| f.name.clone())
.collect()
});
for column_name in column_names.iter() {
let field_id = schema.field_id_by_name(column_name).ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!(
"Column {} not found in table. Schema: {}",
column_name, schema
),
)
})?;
let field = schema
.as_struct()
.field_by_id(field_id)
.ok_or_else(|| {
Error::new(
ErrorKind::FeatureUnsupported,
format!(
"Column {} is not a direct child of schema but a nested field, which is not supported now. Schema: {}",
column_name, schema
),
)
})?;
if !field.field_type.is_primitive() {
return Err(Error::new(
ErrorKind::FeatureUnsupported,
format!(
"Column {} is not a primitive type. Schema: {}",
column_name, schema
),
));
}
field_ids.push(field_id);
}
let snapshot_bound_predicate = if let Some(ref predicates) = self.filter {
Some(predicates.bind(schema.clone(), true)?)
} else {
None
};
let plan_context = PlanContext {
snapshot,
table_metadata: self.table.metadata_ref(),
snapshot_schema: schema,
case_sensitive: self.case_sensitive,
predicate: self.filter.map(Arc::new),
snapshot_bound_predicate: snapshot_bound_predicate.map(Arc::new),
object_cache: self.table.object_cache(),
field_ids: Arc::new(field_ids),
partition_filter_cache: Arc::new(PartitionFilterCache::new()),
manifest_evaluator_cache: Arc::new(ManifestEvaluatorCache::new()),
expression_evaluator_cache: Arc::new(ExpressionEvaluatorCache::new()),
};
Ok(TableScan {
batch_size: self.batch_size,
column_names: self.column_names,
file_io: self.table.file_io().clone(),
plan_context,
concurrency_limit_data_files: self.concurrency_limit_data_files,
concurrency_limit_manifest_entries: self.concurrency_limit_manifest_entries,
concurrency_limit_manifest_files: self.concurrency_limit_manifest_files,
row_group_filtering_enabled: self.row_group_filtering_enabled,
row_selection_enabled: self.row_selection_enabled,
})
}
}
/// Table scan.
#[derive(Debug)]
pub struct TableScan {
plan_context: PlanContext,
batch_size: Option<usize>,
file_io: FileIO,
column_names: Option<Vec<String>>,
/// The maximum number of manifest files that will be
/// retrieved from [`FileIO`] concurrently
concurrency_limit_manifest_files: usize,
/// The maximum number of [`ManifestEntry`]s that will
/// be processed in parallel
concurrency_limit_manifest_entries: usize,
/// The maximum number of [`ManifestEntry`]s that will
/// be processed in parallel
concurrency_limit_data_files: usize,
row_group_filtering_enabled: bool,
row_selection_enabled: bool,
}
/// PlanContext wraps a [`SnapshotRef`] alongside all the other
/// objects that are required to perform a scan file plan.
#[derive(Debug)]
struct PlanContext {
snapshot: SnapshotRef,
table_metadata: TableMetadataRef,
snapshot_schema: SchemaRef,
case_sensitive: bool,
predicate: Option<Arc<Predicate>>,
snapshot_bound_predicate: Option<Arc<BoundPredicate>>,
object_cache: Arc<ObjectCache>,
field_ids: Arc<Vec<i32>>,
partition_filter_cache: Arc<PartitionFilterCache>,
manifest_evaluator_cache: Arc<ManifestEvaluatorCache>,
expression_evaluator_cache: Arc<ExpressionEvaluatorCache>,
}
impl TableScan {
/// Returns a stream of [`FileScanTask`]s.
pub async fn plan_files(&self) -> Result<FileScanTaskStream> {
let concurrency_limit_manifest_files = self.concurrency_limit_manifest_files;
let concurrency_limit_manifest_entries = self.concurrency_limit_manifest_entries;
// used to stream ManifestEntryContexts between stages of the file plan operation
let (manifest_entry_ctx_tx, manifest_entry_ctx_rx) =
channel(concurrency_limit_manifest_files);
// used to stream the results back to the caller
let (file_scan_task_tx, file_scan_task_rx) = channel(concurrency_limit_manifest_entries);
let manifest_list = self.plan_context.get_manifest_list().await?;
// get the [`ManifestFile`]s from the [`ManifestList`], filtering out any
// whose content type is not Data or whose partitions cannot match this
// scan's filter
let manifest_file_contexts = self
.plan_context
.build_manifest_file_contexts(manifest_list, manifest_entry_ctx_tx)?;
let mut channel_for_manifest_error = file_scan_task_tx.clone();
// Concurrently load all [`Manifest`]s and stream their [`ManifestEntry`]s
spawn(async move {
let result = futures::stream::iter(manifest_file_contexts)
.try_for_each_concurrent(concurrency_limit_manifest_files, |ctx| async move {
ctx.fetch_manifest_and_stream_manifest_entries().await
})
.await;
if let Err(error) = result {
let _ = channel_for_manifest_error.send(Err(error)).await;
}
});
let mut channel_for_manifest_entry_error = file_scan_task_tx.clone();
// Process the [`ManifestEntry`] stream in parallel
spawn(async move {
let result = manifest_entry_ctx_rx
.map(|me_ctx| Ok((me_ctx, file_scan_task_tx.clone())))
.try_for_each_concurrent(
concurrency_limit_manifest_entries,
|(manifest_entry_context, tx)| async move {
spawn(async move {
Self::process_manifest_entry(manifest_entry_context, tx).await
})
.await
},
)
.await;
if let Err(error) = result {
let _ = channel_for_manifest_entry_error.send(Err(error)).await;
}
});
return Ok(file_scan_task_rx.boxed());
}
/// Returns an [`ArrowRecordBatchStream`].
pub async fn to_arrow(&self) -> Result<ArrowRecordBatchStream> {
let mut arrow_reader_builder = ArrowReaderBuilder::new(self.file_io.clone())
.with_data_file_concurrency_limit(self.concurrency_limit_data_files)
.with_row_group_filtering_enabled(self.row_group_filtering_enabled)
.with_row_selection_enabled(self.row_selection_enabled);
if let Some(batch_size) = self.batch_size {
arrow_reader_builder = arrow_reader_builder.with_batch_size(batch_size);
}
arrow_reader_builder.build().read(self.plan_files().await?)
}
/// Returns a reference to the column names of the table scan.
pub fn column_names(&self) -> Option<&[String]> {
self.column_names.as_deref()
}
/// Returns a reference to the snapshot of the table scan.
pub fn snapshot(&self) -> &SnapshotRef {
&self.plan_context.snapshot
}
async fn process_manifest_entry(
manifest_entry_context: ManifestEntryContext,
mut file_scan_task_tx: Sender<Result<FileScanTask>>,
) -> Result<()> {
// skip processing this manifest entry if it has been marked as deleted
if !manifest_entry_context.manifest_entry.is_alive() {
return Ok(());
}
// abort the plan if we encounter a manifest entry whose data file's
// content type is currently unsupported
if manifest_entry_context.manifest_entry.content_type() != DataContentType::Data {
return Err(Error::new(
ErrorKind::FeatureUnsupported,
"Only Data files currently supported",
));
}
if let Some(ref bound_predicates) = manifest_entry_context.bound_predicates {
let BoundPredicates {
ref snapshot_bound_predicate,
ref partition_bound_predicate,
} = bound_predicates.as_ref();
let expression_evaluator_cache =
manifest_entry_context.expression_evaluator_cache.as_ref();
let expression_evaluator = expression_evaluator_cache.get(
manifest_entry_context.partition_spec_id,
partition_bound_predicate,
)?;
// skip any data file whose partition data indicates that it can't contain
// any data that matches this scan's filter
if !expression_evaluator.eval(manifest_entry_context.manifest_entry.data_file())? {
return Ok(());
}
// skip any data file whose metrics don't match this scan's filter
if !InclusiveMetricsEvaluator::eval(
snapshot_bound_predicate,
manifest_entry_context.manifest_entry.data_file(),
false,
)? {
return Ok(());
}
}
// congratulations! the manifest entry has made its way through the
// entire plan without getting filtered out. Create a corresponding
// FileScanTask and push it to the result stream
file_scan_task_tx
.send(Ok(manifest_entry_context.into_file_scan_task()))
.await?;
Ok(())
}
}
struct BoundPredicates {
partition_bound_predicate: BoundPredicate,
snapshot_bound_predicate: BoundPredicate,
}
/// Wraps a [`ManifestFile`] alongside the objects that are needed
/// to process it in a thread-safe manner
struct ManifestFileContext {
manifest_file: ManifestFile,
sender: Sender<ManifestEntryContext>,
field_ids: Arc<Vec<i32>>,
bound_predicates: Option<Arc<BoundPredicates>>,
object_cache: Arc<ObjectCache>,
snapshot_schema: SchemaRef,
expression_evaluator_cache: Arc<ExpressionEvaluatorCache>,
}
/// Wraps a [`ManifestEntryRef`] alongside the objects that are needed
/// to process it in a thread-safe manner
struct ManifestEntryContext {
manifest_entry: ManifestEntryRef,
expression_evaluator_cache: Arc<ExpressionEvaluatorCache>,
field_ids: Arc<Vec<i32>>,
bound_predicates: Option<Arc<BoundPredicates>>,
partition_spec_id: i32,
snapshot_schema: SchemaRef,
}
impl ManifestFileContext {
/// Consumes this [`ManifestFileContext`], fetching its Manifest from FileIO and then
/// streaming its constituent [`ManifestEntries`] to the channel provided in the context
async fn fetch_manifest_and_stream_manifest_entries(self) -> Result<()> {
let ManifestFileContext {
object_cache,
manifest_file,
bound_predicates,
snapshot_schema,
field_ids,
mut sender,
expression_evaluator_cache,
..
} = self;
let manifest = object_cache.get_manifest(&manifest_file).await?;
for manifest_entry in manifest.entries() {
let manifest_entry_context = ManifestEntryContext {
// TODO: refactor to avoid clone
manifest_entry: manifest_entry.clone(),
expression_evaluator_cache: expression_evaluator_cache.clone(),
field_ids: field_ids.clone(),
partition_spec_id: manifest_file.partition_spec_id,
bound_predicates: bound_predicates.clone(),
snapshot_schema: snapshot_schema.clone(),
};
sender
.send(manifest_entry_context)
.map_err(|_| Error::new(ErrorKind::Unexpected, "mpsc channel SendError"))
.await?;
}
Ok(())
}
}
impl ManifestEntryContext {
/// consume this `ManifestEntryContext`, returning a `FileScanTask`
/// created from it
fn into_file_scan_task(self) -> FileScanTask {
FileScanTask {
start: 0,
length: self.manifest_entry.file_size_in_bytes(),
record_count: Some(self.manifest_entry.record_count()),
data_file_path: self.manifest_entry.file_path().to_string(),
data_file_content: self.manifest_entry.content_type(),
data_file_format: self.manifest_entry.file_format(),
schema: self.snapshot_schema,
project_field_ids: self.field_ids.to_vec(),
predicate: self
.bound_predicates
.map(|x| x.as_ref().snapshot_bound_predicate.clone()),
}
}
}
impl PlanContext {
async fn get_manifest_list(&self) -> Result<Arc<ManifestList>> {
self.object_cache
.as_ref()
.get_manifest_list(&self.snapshot, &self.table_metadata)
.await
}
fn get_partition_filter(&self, manifest_file: &ManifestFile) -> Result<Arc<BoundPredicate>> {
let partition_spec_id = manifest_file.partition_spec_id;
let partition_filter = self.partition_filter_cache.get(
partition_spec_id,
&self.table_metadata,
&self.snapshot_schema,
self.case_sensitive,
self.predicate
.as_ref()
.ok_or(Error::new(
ErrorKind::Unexpected,
"Expected a predicate but none present",
))?
.as_ref()
.bind(self.snapshot_schema.clone(), self.case_sensitive)?,
)?;
Ok(partition_filter)
}
fn build_manifest_file_contexts(
&self,
manifest_list: Arc<ManifestList>,
sender: Sender<ManifestEntryContext>,
) -> Result<Box<impl Iterator<Item = Result<ManifestFileContext>>>> {
let filtered_entries = manifest_list
.entries()
.iter()
.filter(|manifest_file| manifest_file.content == ManifestContentType::Data);
// TODO: Ideally we could ditch this intermediate Vec as we return an iterator.
let mut filtered_mfcs = vec![];
if self.predicate.is_some() {
for manifest_file in filtered_entries {
let partition_bound_predicate = self.get_partition_filter(manifest_file)?;
// evaluate the ManifestFile against the partition filter. Skip
// if it cannot contain any matching rows
if self
.manifest_evaluator_cache
.get(
manifest_file.partition_spec_id,
partition_bound_predicate.clone(),
)
.eval(manifest_file)?
{
let mfc = self.create_manifest_file_context(
manifest_file,
Some(partition_bound_predicate),
sender.clone(),
);
filtered_mfcs.push(Ok(mfc));
}
}
} else {
for manifest_file in filtered_entries {
let mfc = self.create_manifest_file_context(manifest_file, None, sender.clone());
filtered_mfcs.push(Ok(mfc));
}
}
Ok(Box::new(filtered_mfcs.into_iter()))
}
fn create_manifest_file_context(
&self,
manifest_file: &ManifestFile,
partition_filter: Option<Arc<BoundPredicate>>,
sender: Sender<ManifestEntryContext>,
) -> ManifestFileContext {
let bound_predicates =
if let (Some(ref partition_bound_predicate), Some(snapshot_bound_predicate)) =
(partition_filter, &self.snapshot_bound_predicate)
{
Some(Arc::new(BoundPredicates {
partition_bound_predicate: partition_bound_predicate.as_ref().clone(),
snapshot_bound_predicate: snapshot_bound_predicate.as_ref().clone(),
}))
} else {
None
};
ManifestFileContext {
manifest_file: manifest_file.clone(),
bound_predicates,
sender,
object_cache: self.object_cache.clone(),
snapshot_schema: self.snapshot_schema.clone(),
field_ids: self.field_ids.clone(),
expression_evaluator_cache: self.expression_evaluator_cache.clone(),
}
}
}
/// Manages the caching of [`BoundPredicate`] objects
/// for [`PartitionSpec`]s based on partition spec id.
#[derive(Debug)]
struct PartitionFilterCache(RwLock<HashMap<i32, Arc<BoundPredicate>>>);
impl PartitionFilterCache {
/// Creates a new [`PartitionFilterCache`]
/// with an empty internal HashMap.
fn new() -> Self {
Self(RwLock::new(HashMap::new()))
}
/// Retrieves a [`BoundPredicate`] from the cache
/// or computes it if not present.
fn get(
&self,
spec_id: i32,
table_metadata: &TableMetadataRef,
schema: &Schema,
case_sensitive: bool,
filter: BoundPredicate,
) -> Result<Arc<BoundPredicate>> {
// we need a block here to ensure that the `read()` gets dropped before we hit the `write()`
// below, otherwise we hit deadlock
{
let read = self.0.read().map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"PartitionFilterCache RwLock was poisoned",
)
})?;
if read.contains_key(&spec_id) {
return Ok(read.get(&spec_id).unwrap().clone());
}
}
let partition_spec = table_metadata
.partition_spec_by_id(spec_id)
.ok_or(Error::new(
ErrorKind::Unexpected,
format!("Could not find partition spec for id {}", spec_id),
))?;
let partition_type = partition_spec.partition_type(schema)?;
let partition_fields = partition_type.fields().to_owned();
let partition_schema = Arc::new(
Schema::builder()
.with_schema_id(partition_spec.spec_id())
.with_fields(partition_fields)
.build()?,
);
let mut inclusive_projection = InclusiveProjection::new(partition_spec.clone());
let partition_filter = inclusive_projection
.project(&filter)?
.rewrite_not()
.bind(partition_schema.clone(), case_sensitive)?;
self.0
.write()
.map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"PartitionFilterCache RwLock was poisoned",
)
})?
.insert(spec_id, Arc::new(partition_filter));
let read = self.0.read().map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"PartitionFilterCache RwLock was poisoned",
)
})?;
Ok(read.get(&spec_id).unwrap().clone())
}
}
/// Manages the caching of [`ManifestEvaluator`] objects
/// for [`PartitionSpec`]s based on partition spec id.
#[derive(Debug)]
struct ManifestEvaluatorCache(RwLock<HashMap<i32, Arc<ManifestEvaluator>>>);
impl ManifestEvaluatorCache {
/// Creates a new [`ManifestEvaluatorCache`]
/// with an empty internal HashMap.
fn new() -> Self {
Self(RwLock::new(HashMap::new()))
}
/// Retrieves a [`ManifestEvaluator`] from the cache
/// or computes it if not present.
fn get(&self, spec_id: i32, partition_filter: Arc<BoundPredicate>) -> Arc<ManifestEvaluator> {
// we need a block here to ensure that the `read()` gets dropped before we hit the `write()`
// below, otherwise we hit deadlock
{
let read = self
.0
.read()
.map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"ManifestEvaluatorCache RwLock was poisoned",
)
})
.unwrap();
if read.contains_key(&spec_id) {
return read.get(&spec_id).unwrap().clone();
}
}
self.0
.write()
.map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"ManifestEvaluatorCache RwLock was poisoned",
)
})
.unwrap()
.insert(
spec_id,
Arc::new(ManifestEvaluator::new(partition_filter.as_ref().clone())),
);
let read = self
.0
.read()
.map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"ManifestEvaluatorCache RwLock was poisoned",
)
})
.unwrap();
read.get(&spec_id).unwrap().clone()
}
}
/// Manages the caching of [`ExpressionEvaluator`] objects
/// for [`PartitionSpec`]s based on partition spec id.
#[derive(Debug)]
struct ExpressionEvaluatorCache(RwLock<HashMap<i32, Arc<ExpressionEvaluator>>>);
impl ExpressionEvaluatorCache {
/// Creates a new [`ExpressionEvaluatorCache`]
/// with an empty internal HashMap.
fn new() -> Self {
Self(RwLock::new(HashMap::new()))
}
/// Retrieves a [`ExpressionEvaluator`] from the cache
/// or computes it if not present.
fn get(
&self,
spec_id: i32,
partition_filter: &BoundPredicate,
) -> Result<Arc<ExpressionEvaluator>> {
// we need a block here to ensure that the `read()` gets dropped before we hit the `write()`
// below, otherwise we hit deadlock
{
let read = self.0.read().map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"PartitionFilterCache RwLock was poisoned",
)
})?;
if read.contains_key(&spec_id) {
return Ok(read.get(&spec_id).unwrap().clone());
}
}
self.0
.write()
.map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"ManifestEvaluatorCache RwLock was poisoned",
)
})
.unwrap()
.insert(
spec_id,
Arc::new(ExpressionEvaluator::new(partition_filter.clone())),
);
let read = self
.0
.read()
.map_err(|_| {
Error::new(
ErrorKind::Unexpected,
"ManifestEvaluatorCache RwLock was poisoned",
)
})
.unwrap();
Ok(read.get(&spec_id).unwrap().clone())
}
}
/// A task to scan part of file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FileScanTask {
/// The start offset of the file to scan.
pub start: u64,
/// The length of the file to scan.
pub length: u64,
/// The number of records in the file to scan.
///
/// This is an optional field, and only available if we are
/// reading the entire data file.
pub record_count: Option<u64>,
/// The data file path corresponding to the task.
pub data_file_path: String,
/// The content type of the file to scan.
pub data_file_content: DataContentType,
/// The format of the file to scan.
pub data_file_format: DataFileFormat,
/// The schema of the file to scan.
pub schema: SchemaRef,
/// The field ids to project.
pub project_field_ids: Vec<i32>,
/// The predicate to filter.
#[serde(skip_serializing_if = "Option::is_none")]
pub predicate: Option<BoundPredicate>,
}
impl FileScanTask {
/// Returns the data file path of this file scan task.
pub fn data_file_path(&self) -> &str {
&self.data_file_path
}
/// Returns the project field id of this file scan task.
pub fn project_field_ids(&self) -> &[i32] {
&self.project_field_ids
}
/// Returns the predicate of this file scan task.
pub fn predicate(&self) -> Option<&BoundPredicate> {
self.predicate.as_ref()
}
/// Returns the schema of this file scan task as a reference
pub fn schema(&self) -> &Schema {
&self.schema
}
/// Returns the schema of this file scan task as a SchemaRef
pub fn schema_ref(&self) -> SchemaRef {
self.schema.clone()
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::sync::Arc;
use arrow_array::{
ArrayRef, BooleanArray, Float64Array, Int32Array, Int64Array, RecordBatch, StringArray,
};
use futures::{stream, TryStreamExt};
use parquet::arrow::{ArrowWriter, PARQUET_FIELD_ID_META_KEY};
use parquet::basic::Compression;
use parquet::file::properties::WriterProperties;
use tempfile::TempDir;
use tera::{Context, Tera};
use uuid::Uuid;
use crate::arrow::ArrowReaderBuilder;
use crate::expr::{BoundPredicate, Reference};
use crate::io::{FileIO, OutputFile};
use crate::scan::FileScanTask;
use crate::spec::{
DataContentType, DataFileBuilder, DataFileFormat, Datum, FormatVersion, Literal, Manifest,
ManifestContentType, ManifestEntry, ManifestListWriter, ManifestMetadata, ManifestStatus,
ManifestWriter, NestedField, PrimitiveType, Schema, Struct, TableMetadata, Type,
};
use crate::table::Table;
use crate::TableIdent;
struct TableTestFixture {
table_location: String,
table: Table,
}
impl TableTestFixture {
fn new() -> Self {
let tmp_dir = TempDir::new().unwrap();
let table_location = tmp_dir.path().join("table1");
let manifest_list1_location = table_location.join("metadata/manifests_list_1.avro");
let manifest_list2_location = table_location.join("metadata/manifests_list_2.avro");
let table_metadata1_location = table_location.join("metadata/v1.json");
let file_io = FileIO::from_path(table_location.as_os_str().to_str().unwrap())
.unwrap()
.build()
.unwrap();