forked from delta-io/delta-rs
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtable_provider.rs
More file actions
1619 lines (1446 loc) · 58.2 KB
/
Copy pathtable_provider.rs
File metadata and controls
1619 lines (1446 loc) · 58.2 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
use std::any::Any;
use std::borrow::Cow;
use std::collections::HashSet as StdHashSet;
use std::fmt;
use std::sync::Arc;
use arrow::array::BooleanArray;
use arrow::compute::filter_record_batch;
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use arrow::error::ArrowError;
use chrono::{DateTime, TimeZone, Utc};
use datafusion::catalog::{ScanArgs, ScanResult, TableProvider};
use datafusion::catalog::memory::DataSourceExec;
use datafusion::common::pruning::PruningStatistics;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::common::{Column, ColumnStatistics, DFSchemaRef, Result, Statistics, ToDFSchema};
use datafusion::config::{ConfigOptions, TableParquetOptions};
use datafusion::datasource::TableType;
use datafusion::datasource::physical_plan::FileGroup;
use datafusion::datasource::physical_plan::{FileScanConfigBuilder, ParquetSource};
use datafusion::datasource::sink::DataSinkExec;
use datafusion::datasource::table_schema::TableSchema;
use datafusion::error::DataFusionError;
use datafusion::execution::{SendableRecordBatchStream, TaskContext};
use datafusion::logical_expr::dml::InsertOp;
use datafusion::logical_expr::simplify::SimplifyContext;
use datafusion::logical_expr::utils::split_conjunction;
use datafusion::logical_expr::{BinaryExpr, LogicalPlan, Operator};
use datafusion::optimizer::simplify_expressions::ExprSimplifier;
use datafusion::physical_optimizer::pruning::PruningPredicate;
use datafusion::physical_plan::filter_pushdown::{FilterDescription, FilterPushdownPhase};
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, PhysicalExpr, PlanProperties,
};
use datafusion::{
catalog::Session,
common::{HashMap, HashSet},
datasource::listing::PartitionedFile,
logical_expr::{TableProviderFilterPushDown, utils::conjunction},
prelude::Expr,
scalar::ScalarValue,
};
use delta_kernel::Version;
use futures::future::BoxFuture;
use itertools::Itertools;
use object_store::ObjectMeta;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;
use crate::delta_datafusion::file_id::{file_id_data_type, wrap_file_id_value};
use crate::delta_datafusion::table_provider::next::SnapshotWrapper;
use crate::delta_datafusion::{
DataFusionMixins as _, DeltaSessionExt, FindFilesExprProperties, LogDataHandler,
get_null_of_arrow_type, to_correct_scalar_value,
};
use crate::kernel::transaction::PROTOCOL;
use crate::kernel::{Add, EagerSnapshot, Snapshot};
use crate::logstore::LogStore;
use crate::protocol::SaveMode;
use crate::table::normalize_table_url;
use crate::{DeltaResult, DeltaTable, DeltaTableError, logstore::LogStoreRef};
use crate::delta_datafusion::expr_adapter::build_expr_adapter_factory;
mod data_sink;
pub(crate) mod next;
const PATH_COLUMN: &str = "__delta_rs_path";
#[derive(Debug, Clone)]
/// Used to specify if additional metadata columns are exposed to the user
pub struct DeltaScanConfigBuilder {
/// Include the source path for each record. The name of this column is determined by `file_column_name`
pub(super) include_file_column: bool,
/// Column name that contains the source path.
///
/// If include_file_column is true and the name is None then it will be auto-generated
/// Otherwise the user provided name will be used
pub(super) file_column_name: Option<String>,
/// Whether to wrap partition values in a dictionary encoding to potentially save space
pub(super) wrap_partition_values: Option<bool>,
/// Whether to push down filter in end result or just prune the files
pub(super) enable_parquet_pushdown: bool,
/// Schema to scan table with
pub(super) schema: Option<SchemaRef>,
}
impl Default for DeltaScanConfigBuilder {
fn default() -> Self {
DeltaScanConfigBuilder {
include_file_column: false,
file_column_name: None,
wrap_partition_values: None,
enable_parquet_pushdown: true,
schema: None,
}
}
}
impl DeltaScanConfigBuilder {
/// Construct a new instance of `DeltaScanConfigBuilder`
pub fn new() -> Self {
Self::default()
}
/// Indicate that a column containing a records file path is included.
/// Column name is generated and can be determined once this Config is built
pub fn with_file_column(mut self, include: bool) -> Self {
self.include_file_column = include;
self.file_column_name = None;
self
}
/// Indicate that a column containing a records file path is included and column name is user defined.
pub fn with_file_column_name<S: ToString>(mut self, name: &S) -> Self {
self.file_column_name = Some(name.to_string());
self.include_file_column = true;
self
}
/// Whether to wrap partition values in a dictionary encoding
pub fn wrap_partition_values(mut self, wrap: bool) -> Self {
self.wrap_partition_values = Some(wrap);
self
}
/// Allow pushdown of the scan filter
/// When disabled the filter will only be used for pruning files
pub fn with_parquet_pushdown(mut self, pushdown: bool) -> Self {
self.enable_parquet_pushdown = pushdown;
self
}
/// Use the provided [SchemaRef] for the [DeltaScan]
pub fn with_schema(mut self, schema: SchemaRef) -> Self {
self.schema = Some(schema);
self
}
/// Build a DeltaScanConfig and ensure no column name conflicts occur during downstream processing
pub fn build(&self, snapshot: &EagerSnapshot) -> DeltaResult<DeltaScanConfig> {
let file_column_name = if self.include_file_column {
let input_schema = snapshot.input_schema();
let mut column_names: HashSet<&String> = HashSet::new();
for field in input_schema.fields.iter() {
column_names.insert(field.name());
}
match &self.file_column_name {
Some(name) => {
if column_names.contains(name) {
return Err(DeltaTableError::Generic(format!(
"Unable to add file path column since column with name {name} exists"
)));
}
Some(name.to_owned())
}
None => {
let prefix = PATH_COLUMN;
let mut idx = 0;
let mut name = prefix.to_owned();
while column_names.contains(&name) {
idx += 1;
name = format!("{prefix}_{idx}");
}
Some(name)
}
}
} else {
None
};
Ok(DeltaScanConfig {
file_column_name,
wrap_partition_values: self.wrap_partition_values.unwrap_or(true),
enable_parquet_pushdown: self.enable_parquet_pushdown,
schema: self.schema.clone(),
schema_force_view_types: true,
virtual_columns: None,
requested_columns: None,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Include additional metadata columns during a [`DeltaScan`]
pub struct DeltaScanConfig {
/// Include the source path for each record
pub file_column_name: Option<String>,
/// Wrap partition values in a dictionary encoding, defaults to true
pub wrap_partition_values: bool,
/// Allow pushdown of the scan filter, defaults to true
pub enable_parquet_pushdown: bool,
/// If true, parquet reader will read columns of `Utf8`/`Utf8Large`
/// with Utf8View, and `Binary`/`BinaryLarge` with `BinaryView`
pub schema_force_view_types: bool,
/// Schema to read as
pub schema: Option<SchemaRef>,
/// Virtual columns derived automatically in [`DeltaScanBuilder::build`] by
/// diffing the caller-supplied schema against the table's physical schema.
/// Not part of the public API — do not set manually.
pub(crate) virtual_columns: Option<StdHashSet<String>>,
/// Requested output columns in order (including virtual columns)
/// Used to build projection that null-fills virtual columns
pub requested_columns: Option<Vec<String>>,
}
impl Default for DeltaScanConfig {
fn default() -> Self {
Self::new()
}
}
impl DeltaScanConfig {
/// Create a new default [`DeltaScanConfig`]
pub fn new() -> Self {
Self {
file_column_name: None,
wrap_partition_values: true,
enable_parquet_pushdown: true,
schema_force_view_types: true,
schema: None,
virtual_columns: None,
requested_columns: None,
}
}
pub fn new_from_session(session: &dyn Session) -> Self {
let config_options = session.config().options();
Self {
file_column_name: None,
wrap_partition_values: true,
enable_parquet_pushdown: config_options.execution.parquet.pushdown_filters,
schema_force_view_types: config_options.execution.parquet.schema_force_view_types,
schema: None,
virtual_columns: None,
requested_columns: None,
}
}
pub fn with_file_column_name<S: ToString>(mut self, name: S) -> Self {
self.file_column_name = Some(name.to_string());
self
}
/// Whether to wrap partition values in a dictionary encoding
pub fn with_wrap_partition_values(mut self, wrap: bool) -> Self {
self.wrap_partition_values = wrap;
self
}
/// Allow pushdown of the scan filter
pub fn with_parquet_pushdown(mut self, pushdown: bool) -> Self {
self.enable_parquet_pushdown = pushdown;
self
}
/// Use the provided [SchemaRef] for the [DeltaScan]
///
/// This schema will be used when reading data from the underlying files.
/// The column names must match those in the table schema, but can have
/// different (yet compatible) types - e.g. string view types can be used
pub fn with_schema(mut self, schema: SchemaRef) -> Self {
self.schema = Some(schema);
self
}
pub fn with_requested_columns(mut self, columns: Vec<String>) -> Self {
self.requested_columns = Some(columns);
self
}
}
pub struct DeltaScanBuilder<'a> {
snapshot: &'a EagerSnapshot,
log_store: LogStoreRef,
filter: Option<Expr>,
session: &'a dyn Session,
projection: Option<&'a Vec<usize>>,
projection_deep: Option<&'a std::collections::HashMap<usize, Vec<String>>>,
limit: Option<usize>,
files: Option<&'a [Add]>,
config: Option<DeltaScanConfig>,
}
impl<'a> DeltaScanBuilder<'a> {
pub fn new(
snapshot: &'a EagerSnapshot,
log_store: LogStoreRef,
session: &'a dyn Session,
) -> Self {
DeltaScanBuilder {
snapshot,
log_store,
filter: None,
session,
projection: None,
projection_deep: None,
limit: None,
files: None,
config: None,
}
}
pub fn with_filter(mut self, filter: Option<Expr>) -> Self {
self.filter = filter;
self
}
pub fn with_files(mut self, files: &'a [Add]) -> Self {
self.files = Some(files);
self
}
pub fn with_projection(mut self, projection: Option<&'a Vec<usize>>) -> Self {
self.projection = projection;
self
}
pub fn with_projection_deep(
mut self,
projection_deep: Option<&'a std::collections::HashMap<usize, Vec<String>>>,
) -> Self {
self.projection_deep = projection_deep;
self
}
pub fn with_limit(mut self, limit: Option<usize>) -> Self {
self.limit = limit;
self
}
pub fn with_scan_config(mut self, config: DeltaScanConfig) -> Self {
self.config = Some(config);
self
}
pub async fn build(self) -> DeltaResult<DeltaScan> {
PROTOCOL.can_read_from(self.snapshot)?;
let config = match self.config {
Some(config) => config,
None => DeltaScanConfigBuilder::new().build(self.snapshot)?,
};
let schema = match config.schema.clone() {
Some(value) => value,
None => self.snapshot.read_schema(),
};
// Auto-derive virtual columns: any field present in the caller-supplied
// schema but absent from the table's physical schema (and not a partition
// column) is treated as virtual and will be null-filled during the scan.
// This means callers only need to pass `with_schema(extended)` — there is
// no need to explicitly mark virtual columns.
let config = if config.virtual_columns.is_none() {
let physical_schema = self.snapshot.read_schema();
let partition_cols = self.snapshot.metadata().partition_columns();
let physical_names: StdHashSet<&str> = physical_schema
.fields()
.iter()
.map(|f| f.name().as_str())
.collect();
let virtual_cols: StdHashSet<String> = schema
.fields()
.iter()
.filter(|f| {
!physical_names.contains(f.name().as_str())
&& !partition_cols.contains(f.name())
})
.map(|f| f.name().clone())
.collect();
if virtual_cols.is_empty() {
config
} else {
DeltaScanConfig { virtual_columns: Some(virtual_cols), ..config }
}
} else {
config
};
let logical_schema = df_logical_schema(
self.snapshot,
&config.file_column_name,
Some(schema.clone()),
)?;
let logical_schema = if config.virtual_columns.is_some() {
// TODO: can we keep just a patch of the schema?
// When virtual columns are present, keep full logical_schema
// PhysicalExprAdapter will handle the adaptation
// Otherwise, subset logical_schema based on projection indices
logical_schema
} else if let Some(used_columns) = self.projection {
let extra_fields = self.filter
.iter()
.flat_map(|expr| expr.column_refs())
.map(|c| logical_schema.index_of(c.name.as_str()))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.filter(|idx| !used_columns.contains(idx));
let fields = used_columns.iter()
.copied()
.chain(extra_fields)
.map(|idx| logical_schema.field(idx).to_owned())
.collect::<Vec<_>>();
Arc::new(Schema::new(fields))
} else {
logical_schema
};
let df_schema = Arc::new(logical_schema.clone().to_dfschema()?);
let logical_filter = self
.filter
.clone()
.map(|expr| simplify_expr(self.session, df_schema.clone(), expr))
.transpose()?;
// only inexact filters should be pushed down to the data source, doing otherwise
// will make stats inexact and disable datafusion optimizations like AggregateStatistics
let pushdown_filter = self
.filter
.and_then(|expr| {
let predicates = split_conjunction(&expr);
let pushdown_filters =
get_pushdown_filters(&predicates, self.snapshot.metadata().partition_columns());
let filtered_predicates = predicates
.into_iter()
.zip(pushdown_filters.into_iter())
.filter_map(|(filter, pushdown)| {
if pushdown == TableProviderFilterPushDown::Inexact {
Some(filter.clone())
} else {
None
}
});
conjunction(filtered_predicates)
})
.map(|expr| simplify_expr(self.session, df_schema.clone(), expr))
.transpose()?;
// Perform Pruning of files to scan
let (files, files_scanned, files_pruned, pruning_mask) = match self.files {
Some(files) => {
let files = files.to_owned();
let files_scanned = files.len();
(files, files_scanned, 0, None)
}
None => {
// early return in case we have no push down filters or limit
if logical_filter.is_none() && self.limit.is_none() {
let files = self
.snapshot
.log_data()
.iter()
.map(|f| f.add_action_no_stats())
.collect_vec();
let files_scanned = files.len();
(files, files_scanned, 0, None)
} else {
let num_containers = self.snapshot.num_containers();
let files_to_prune = if let Some(predicate) = &logical_filter {
let pruning_predicate =
PruningPredicate::try_new(predicate.clone(), logical_schema.clone())?;
pruning_predicate.prune(self.snapshot)?
} else {
vec![true; num_containers]
};
// needed to enforce limit and deal with missing statistics
// rust port of https://github.com/delta-io/delta/pull/1495
let mut pruned_without_stats = Vec::new();
let mut rows_collected = 0;
let mut files = Vec::with_capacity(num_containers);
use rand::seq::SliceRandom;
let mut indices = (0..num_containers).collect::<Vec<_>>();
if self.limit.is_some() && std::env::var("DELTA_RS_SHUFFLE_FILES").is_ok() {
let mut rng = rand::thread_rng();
indices.shuffle(&mut rng);
}
let log_data_handler = self.snapshot.log_data();
for i in indices {
let file_view = log_data_handler.get(i).unwrap();
let keep = files_to_prune[i];
// prune file based on predicate pushdown
let action = file_view.add_action_no_stats();
let num_records = file_view.num_records();
if keep {
// prune file based on limit pushdown
if let Some(limit) = self.limit {
if let Some(num_records) = num_records {
if rows_collected <= limit as i64 {
rows_collected += num_records as i64;
files.push(action.to_owned());
} else {
break;
}
} else {
// some files are missing stats; skipping but storing them
// in a list in case we can't reach the target limit
pruned_without_stats.push(action.to_owned());
}
} else {
files.push(action.to_owned());
}
}
}
if let Some(limit) = self.limit
&& rows_collected < limit as i64
{
files.extend(pruned_without_stats);
}
let files_scanned = files.len();
let files_pruned = num_containers - files_scanned;
(files, files_scanned, files_pruned, Some(files_to_prune))
}
}
};
// TODO we group files together by their partition values. If the table is partitioned
// and partitions are somewhat evenly distributed, probably not the worst choice ...
// However we may want to do some additional balancing in case we are far off from the above.
let mut file_groups: HashMap<Vec<ScalarValue>, Vec<PartitionedFile>> = HashMap::new();
let table_partition_cols = &self.snapshot.metadata().partition_columns();
for action in files.iter() {
let mut part = partitioned_file_from_action(action, table_partition_cols, &schema);
if config.file_column_name.is_some() {
let partition_value = if config.wrap_partition_values {
wrap_file_id_value(action.path.clone())
} else {
ScalarValue::Utf8(Some(action.path.clone()))
};
part.partition_values.push(partition_value);
}
file_groups
.entry(part.partition_values.clone())
.or_default()
.push(part);
}
let file_schema = Arc::new(Schema::new(
schema
.fields()
.iter()
.filter(|f| {
!table_partition_cols.contains(f.name())
&& !config
.virtual_columns
.as_ref()
.map(|vc| vc.contains(f.name()))
.unwrap_or(false)
})
.cloned()
.collect::<Vec<arrow::datatypes::FieldRef>>(),
));
// When virtual columns are present, translate projection to physical schema space
// Filter out virtual column indices since they don't exist in physical files
// If all requested columns are virtual we still need at least one physical column
// to drive row production; ProjectionExec will project everything to nulls.
// Reading a single column is far cheaper than reading all of them (the old `None` fallback).
let file_projection = if let Some(virtual_cols) = &config.virtual_columns {
self.projection.and_then(|proj| {
let physical_indices: Vec<usize> = proj
.iter()
.filter_map(|&idx| {
let field = schema.field(idx);
if virtual_cols.contains(field.name()) {
None
} else {
file_schema.index_of(field.name()).ok()
}
})
.collect();
if physical_indices.is_empty() {
if file_schema.fields().is_empty() {
None
} else {
Some(vec![0usize])
}
} else {
Some(physical_indices)
}
})
} else {
self.projection.map(|v| v.to_vec())
};
let mut table_partition_cols = table_partition_cols
.iter()
.map(|name| schema.field_with_name(name).map(|f| f.to_owned()))
.collect::<Result<Vec<_>, ArrowError>>()?;
if let Some(file_column_name) = &config.file_column_name {
let field_name_datatype = if config.wrap_partition_values {
file_id_data_type()
} else {
DataType::Utf8
};
table_partition_cols.push(Field::new(
file_column_name.clone(),
field_name_datatype,
false,
));
}
// FIXME - where is the correct place to marry file pruning with statistics pruning?
// Temporarily re-generating the log handler, just so that we can compute the stats.
// Should we update datafusion_table_statistics to optionally take the mask?
let stats = if let Some(mask) = pruning_mask {
let es = self.snapshot.snapshot();
let mut pruned_batches = Vec::new();
let mut mask_offset = 0;
for batch in self.snapshot.files()? {
let batch_size = batch.num_rows();
let batch_mask = &mask[mask_offset..mask_offset + batch_size];
let batch_mask_array = BooleanArray::from(batch_mask.to_vec());
let pruned_batch = filter_record_batch(batch, &batch_mask_array)?;
if pruned_batch.num_rows() > 0 {
pruned_batches.push(pruned_batch);
}
mask_offset += batch_size;
}
LogDataHandler::new(&pruned_batches, es.table_configuration()).statistics()
} else {
self.snapshot.log_data().statistics()
};
let stats = stats.unwrap_or(Statistics::new_unknown(&schema));
// DF52's TableSchema outputs columns as: file_schema + partition_columns
// Source stats are indexed by TableConfiguration.schema() field order, which may differ
// from the scan schema order. We need name-based remapping, not index-based.
let partition_col_names = self.snapshot.metadata().partition_columns();
// Build name -> ColumnStatistics map from source stats (keyed by TableConfiguration schema order)
let source_schema = self.snapshot.schema();
let stats_by_name: HashMap<String, ColumnStatistics> = source_schema
.fields()
.enumerate()
.filter_map(|(idx, field)| {
stats
.column_statistics
.get(idx)
.map(|s| (field.name().to_string(), s.clone()))
})
.collect();
// Build stats in DF52 order: file_schema columns first, then partition_columns
// file_schema columns are in file_schema field order (non-partition from logical_schema)
let file_col_stats: Vec<ColumnStatistics> = file_schema
.fields()
.iter()
.map(|f| {
stats_by_name
.get(f.name())
.cloned()
.unwrap_or_else(ColumnStatistics::new_unknown)
})
.collect();
// Partition columns must be in metadata.partition_columns() order (not schema encounter order)
let partition_col_stats: Vec<ColumnStatistics> = partition_col_names
.iter()
.map(|name| {
stats_by_name
.get(name)
.cloned()
.unwrap_or_else(ColumnStatistics::new_unknown)
})
.collect();
// Combine: file columns first, then partition columns
let mut reordered_stats = file_col_stats;
reordered_stats.extend(partition_col_stats);
let stats = Statistics {
num_rows: stats.num_rows,
total_byte_size: stats.total_byte_size,
column_statistics: reordered_stats,
};
// Add unknown stats for file_column if present (it's added as partition field but not in original schema)
let stats = if config.file_column_name.is_some() {
let mut col_stats = stats.column_statistics;
col_stats.push(ColumnStatistics::new_unknown());
Statistics {
num_rows: stats.num_rows,
total_byte_size: stats.total_byte_size,
column_statistics: col_stats,
}
} else {
stats
};
let parquet_options = TableParquetOptions {
global: self.session.config().options().execution.parquet.clone(),
..Default::default()
};
let partition_fields: Vec<Arc<Field>> =
table_partition_cols.into_iter().map(Arc::new).collect();
let table_schema = TableSchema::new(file_schema.clone(), partition_fields);
let mut file_source =
ParquetSource::new(table_schema).with_table_parquet_options(parquet_options);
// Sometimes (i.e Merge) we want to prune files that don't make the
// filter and read the entire contents for files that do match the
// filter
if let Some(predicate) = pushdown_filter
&& config.enable_parquet_pushdown
{
file_source = file_source.with_predicate(predicate);
};
let file_scan_config =
FileScanConfigBuilder::new(self.log_store.object_store_url(), Arc::new(file_source))
.with_file_groups(
// If all files were filtered out, we still need to emit at least one partition to
// pass datafusion sanity checks.
//
// See https://github.com/apache/datafusion/issues/11322
if file_groups.is_empty() {
vec![FileGroup::from(vec![])]
} else {
file_groups.into_values().map(FileGroup::from).collect()
},
)
.with_statistics(stats)
// Remap projection_deep keys from logical (schema) index space to
// file_schema index space, mirroring what file_projection does above.
// Virtual and partition columns are absent from file_schema so they
// are dropped from the map via index_of returning Err.
.with_deep_projection(file_projection, self.projection_deep.map(|deep| {
deep.iter()
.filter_map(|(schema_idx, subfields)| {
file_schema
.index_of(schema.field(*schema_idx).name())
.ok()
.map(|file_idx| (file_idx, subfields.clone()))
})
.collect::<std::collections::HashMap<usize, Vec<String>>>()
}))?
.with_limit(self.limit)
// @Hstack fixme
.with_expr_adapter(build_expr_adapter_factory())
.build();
let metrics = ExecutionPlanMetricsSet::new();
MetricBuilder::new(&metrics)
.global_counter("files_scanned")
.add(files_scanned);
MetricBuilder::new(&metrics)
.global_counter("files_pruned")
.add(files_pruned);
let mut parquet_scan: Arc<dyn ExecutionPlan> = DataSourceExec::from_data_source(file_scan_config);
// When virtual columns + requested columns are present, wrap with ProjectionExec
// to project physical output to requested columns (null-filling virtuals)
if let (Some(requested_cols), Some(virtual_cols)) = (&config.requested_columns, &config.virtual_columns) {
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_expr::expressions::{Column as PhysicalColumn, Literal};
let output_schema = parquet_scan.schema();
let mut projection_exprs = Vec::new();
for col_name in requested_cols {
let field = logical_schema.field_with_name(col_name)?;
let expr: Arc<dyn PhysicalExpr> = if virtual_cols.contains(col_name) {
Arc::new(Literal::new(ScalarValue::try_from(field.data_type())?))
} else {
let idx = output_schema.index_of(col_name)?;
Arc::new(PhysicalColumn::new(col_name, idx))
};
projection_exprs.push((expr, col_name.clone()));
}
parquet_scan = Arc::new(ProjectionExec::try_new(projection_exprs, parquet_scan)?);
}
Ok(DeltaScan {
table_url: self.log_store.root_url().clone(),
parquet_scan,
config,
logical_schema,
metrics,
})
}
}
/// Builder for a datafusion [TableProvider] for a Delta table
///
/// A table provider can be built by providing either a log store, a Snapshot,
/// or an eager snapshot. If some Snapshot is provided, that will be used directly,
/// and no IO will be performed when building the provider.
#[derive(Debug)]
pub struct TableProviderBuilder {
log_store: Option<Arc<dyn LogStore>>,
snapshot: Option<SnapshotWrapper>,
file_column: Option<String>,
table_version: Option<Version>,
/// Predicates used only for file skipping in kernel log replay
file_skipping_predicates: Option<Vec<Expr>>,
}
impl Default for TableProviderBuilder {
fn default() -> Self {
Self::new()
}
}
impl TableProviderBuilder {
fn new() -> Self {
Self {
log_store: None,
snapshot: None,
file_column: None,
table_version: None,
file_skipping_predicates: None,
}
}
/// Provide the log store to use for the table provider
pub fn with_log_store(mut self, log_store: impl Into<Arc<dyn LogStore>>) -> Self {
self.log_store = Some(log_store.into());
self
}
/// Provide an eager snapshot to use for the table provider
pub fn with_eager_snapshot(mut self, snapshot: impl Into<Arc<EagerSnapshot>>) -> Self {
self.snapshot = Some(SnapshotWrapper::EagerSnapshot(snapshot.into()));
self
}
/// Provide a snapshot to use for the table provider
pub fn with_snapshot(mut self, snapshot: impl Into<Arc<Snapshot>>) -> Self {
self.snapshot = Some(SnapshotWrapper::Snapshot(snapshot.into()));
self
}
/// Specify the version of the table to provide
pub fn with_table_version(mut self, version: impl Into<Option<Version>>) -> Self {
self.table_version = version.into();
self
}
/// Specify the name of the file column to include in the scan
///
/// If specified, this will append a column to the table,
/// containing the source file path for each record.
pub fn with_file_column(mut self, file_column: impl ToString) -> Self {
self.file_column = Some(file_column.to_string());
self
}
/// Add predicates applied only during file skipping.
///
/// There are cases where we may want to skip files that definitely do
/// not contain any data that matches a predicate, but read all data
/// if any records may match, to rewrite the file with updated records.
///
/// The file skipping predicates will thus not be pushed into the parquet
/// scan. However any predicate that gets pushed into the scan during execution
/// planning will be applied.
pub(crate) fn with_file_skipping_predicates(
mut self,
file_skipping_predicates: impl IntoIterator<Item = Expr>,
) -> Self {
self.file_skipping_predicates = Some(file_skipping_predicates.into_iter().collect());
self
}
pub async fn build(self) -> Result<next::DeltaScan> {
let mut config = DeltaScanConfig::new();
if let Some(file_column) = self.file_column {
config = config.with_file_column_name(file_column);
}
let snapshot = match self.snapshot {
Some(wrapper) => wrapper,
None => {
if let Some(log_store) = self.log_store.as_ref() {
SnapshotWrapper::Snapshot(
Snapshot::try_new(
log_store,
Default::default(),
self.table_version.map(|v| v as i64),
)
.await?
.into(),
)
} else {
return Err(DataFusionError::Plan(
"Either a log store or a snapshot must be provided to build a Delta TableProvider".to_string(),
));
}
}
};
let mut provider = next::DeltaScan::new(snapshot, config)?;
if let Some(skipping) = self.file_skipping_predicates {
// validate that the expressions contain no illegal variants
// that are not eligible for file skipping, e.g. volatile functions.
for term in &skipping {
let mut visitor = FindFilesExprProperties::default();
term.visit(&mut visitor)?;
visitor.result?;
}
provider = provider.with_file_skipping_predicate(skipping);
}
Ok(provider)
}
}
impl std::future::IntoFuture for TableProviderBuilder {
type Output = Result<Arc<dyn TableProvider>>;
type IntoFuture = BoxFuture<'static, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
let this = self;
Box::pin(async move { Ok(Arc::new(this.build().await?) as _) })
}
}
impl DeltaTable {
/// Get a table provider for the table referenced by this DeltaTable.
///
/// See [`TableProviderBuilder`] for options when building the provider.
pub fn table_provider(&self) -> TableProviderBuilder {
let mut builder = TableProviderBuilder::new();
if let Ok(state) = self.snapshot() {
builder = builder.with_eager_snapshot(state.snapshot().clone());
} else {
builder = builder.with_log_store(self.log_store());
}
builder
}
/// Ensure the provided DataFusion session is prepared to read this table.
///
/// This registers the table's root object store with the session's `RuntimeEnv` if missing.
/// Registration is idempotent and will not overwrite an existing mapping.
///
/// If the session already has an object store registered for the table's URL but it is stale or
/// incorrect, this method will not replace it. To override an existing mapping, call
/// `RuntimeEnv::register_object_store` directly.
///
/// ```rust,no_run
/// use datafusion::prelude::SessionContext;
/// use deltalake_core::{DeltaResult, DeltaTable};
///
/// # fn main() -> DeltaResult<()> {
/// let table = DeltaTable::new_in_memory();
/// let ctx = SessionContext::new();
/// let state = ctx.state();
/// table.update_datafusion_session(&state)?;
/// # Ok(())
/// # }
/// ```
pub fn update_datafusion_session(&self, session: &dyn Session) -> DeltaResult<()> {
crate::delta_datafusion::DeltaSessionExt::ensure_object_store_registered(
session,
self.log_store().as_ref(),
None,
)
}
}
pub(crate) fn update_datafusion_session(
log_store: &dyn LogStore,
session: &dyn Session,
operation_id: Option<Uuid>,
) -> DeltaResult<()> {
crate::delta_datafusion::DeltaSessionExt::ensure_object_store_registered(
session,
log_store,
operation_id,