1#![doc(
19 html_logo_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg",
20 html_favicon_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg"
21)]
22#![cfg_attr(docsrs, feature(doc_cfg))]
23#![cfg_attr(not(test), deny(clippy::clone_on_ref_ptr))]
26#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
27
28pub mod boundary_stream;
32pub mod decoder;
33pub mod display;
34pub mod file;
35pub mod file_compression_type;
36pub mod file_format;
37pub mod file_groups;
38pub mod file_scan_config;
39pub mod file_sink_config;
40pub mod file_stream;
41pub mod memory;
42pub mod morsel;
43pub mod projection;
44#[cfg(feature = "proto")]
47mod proto;
48pub mod schema_adapter;
49pub mod sink;
50pub mod source;
51mod statistics;
52pub mod table_schema;
53
54#[cfg(test)]
55pub mod test_util;
56
57pub mod url;
58pub mod write;
59pub use self::file::as_file_source;
60pub use self::url::ListingTableUrl;
61use crate::file_groups::FileGroup;
62use arrow::datatypes::SchemaRef;
63use chrono::TimeZone;
64use datafusion_common::stats::Precision;
65use datafusion_common::{ColumnStatistics, Result, TableReference};
66use datafusion_common::{ScalarValue, Statistics};
67use datafusion_physical_expr::LexOrdering;
68use futures::Stream;
69use object_store::{ObjectMeta, path::Path};
70pub use statistics::compute_all_files_statistics;
71use std::any::Any;
72use std::pin::Pin;
73use std::sync::Arc;
74pub use table_schema::{TableSchema, TableSchemaBuilder};
75
76pub type FileExtensions = datafusion_common::extensions::Extensions;
82
83#[deprecated(
85 since = "54.0.0",
86 note = "This type is unused and will be removed in a future release"
87)]
88pub type PartitionedFileStream =
89 Pin<Box<dyn Stream<Item = Result<PartitionedFile>> + Send + Sync + 'static>>;
90
91#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
95pub struct FileRange {
96 pub start: i64,
98 pub end: i64,
100}
101
102impl FileRange {
103 pub fn contains(&self, offset: i64) -> bool {
105 offset >= self.start && offset < self.end
106 }
107}
108
109#[derive(Debug, Clone)]
110pub struct PartitionedFile {
129 pub object_meta: ObjectMeta,
131 pub partition_values: Vec<ScalarValue>,
142 pub range: Option<FileRange>,
144 pub statistics: Option<Arc<Statistics>>,
153 pub ordering: Option<LexOrdering>,
163 pub extensions: FileExtensions,
167 pub metadata_size_hint: Option<usize>,
169 pub table_reference: Option<TableReference>,
170 pub arrow_schema: Option<SchemaRef>,
180}
181
182impl PartitionedFile {
183 pub fn new(path: impl Into<String>, size: u64) -> Self {
185 Self {
186 arrow_schema: None,
187 object_meta: ObjectMeta {
188 location: Path::from(path.into()),
189 last_modified: chrono::Utc.timestamp_nanos(0),
190 size,
191 e_tag: None,
192 version: None,
193 },
194 partition_values: vec![],
195 range: None,
196 statistics: None,
197 ordering: None,
198 extensions: FileExtensions::new(),
199 metadata_size_hint: None,
200 table_reference: None,
201 }
202 }
203
204 pub fn new_from_meta(object_meta: ObjectMeta) -> Self {
206 Self {
207 arrow_schema: None,
208 object_meta,
209 partition_values: vec![],
210 range: None,
211 statistics: None,
212 ordering: None,
213 extensions: FileExtensions::new(),
214 metadata_size_hint: None,
215 table_reference: None,
216 }
217 }
218
219 pub fn new_with_range(path: String, size: u64, start: i64, end: i64) -> Self {
221 Self {
222 arrow_schema: None,
223 object_meta: ObjectMeta {
224 location: Path::from(path),
225 last_modified: chrono::Utc.timestamp_nanos(0),
226 size,
227 e_tag: None,
228 version: None,
229 },
230 partition_values: vec![],
231 range: Some(FileRange { start, end }),
232 statistics: None,
233 ordering: None,
234 extensions: FileExtensions::new(),
235 metadata_size_hint: None,
236 table_reference: None,
237 }
238 .with_range(start, end)
239 }
240
241 pub fn with_arrow_schema(mut self, schema: SchemaRef) -> Self {
246 self.arrow_schema = Some(schema);
247 self
248 }
249
250 pub fn with_partition_values(mut self, partition_values: Vec<ScalarValue>) -> Self {
253 self.partition_values = partition_values;
254 self
255 }
256
257 pub fn with_table_reference(
258 mut self,
259 table_reference: Option<TableReference>,
260 ) -> Self {
261 self.table_reference = table_reference;
262 self
263 }
264
265 pub fn effective_size(&self) -> u64 {
267 if let Some(range) = &self.range {
268 (range.end - range.start) as u64
269 } else {
270 self.object_meta.size
271 }
272 }
273
274 pub fn range(&self) -> (u64, u64) {
276 if let Some(range) = &self.range {
277 (range.start as u64, range.end as u64)
278 } else {
279 (0, self.object_meta.size)
280 }
281 }
282
283 pub fn with_metadata_size_hint(mut self, metadata_size_hint: usize) -> Self {
287 self.metadata_size_hint = Some(metadata_size_hint);
288 self
289 }
290
291 pub fn from_path(path: String) -> Result<Self> {
293 let size = std::fs::metadata(path.clone())?.len();
294 Ok(Self::new(path, size))
295 }
296
297 pub fn path(&self) -> &Path {
299 &self.object_meta.location
300 }
301
302 pub fn with_range(mut self, start: i64, end: i64) -> Self {
304 self.range = Some(FileRange { start, end });
305 self
306 }
307
308 pub fn with_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
316 self.extensions.insert(value);
317 self
318 }
319
320 pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
322 self.extensions.get::<T>()
323 }
324
325 #[deprecated(
330 since = "54.0.0",
331 note = "use `with_extension`; the extension is keyed by its concrete type"
332 )]
333 pub fn with_extensions(mut self, extensions: Arc<dyn Any + Send + Sync>) -> Self {
334 #[expect(deprecated)]
335 self.extensions.insert_dyn(extensions);
336 self
337 }
338
339 pub fn with_statistics(mut self, file_statistics: Arc<Statistics>) -> Self {
351 if self.partition_values.is_empty() {
352 self.statistics = Some(file_statistics);
354 } else {
355 let mut stats = Arc::unwrap_or_clone(file_statistics);
357 for partition_value in &self.partition_values {
358 let (null_count, min_max, distinct_count) = if partition_value.is_null() {
359 (stats.num_rows, Precision::Absent, Precision::Exact(0))
360 } else {
361 (
362 Precision::Exact(0),
363 Precision::Exact(partition_value.clone()),
364 Precision::Exact(1),
365 )
366 };
367 let col_stats = ColumnStatistics {
368 null_count,
369 max_value: min_max.clone(),
370 min_value: min_max,
371 distinct_count,
372 sum_value: Precision::Absent,
373 byte_size: partition_value
374 .data_type()
375 .primitive_width()
376 .map(|w| stats.num_rows.multiply(&Precision::Exact(w)))
377 .unwrap_or_else(|| Precision::Absent),
378 };
379 stats.column_statistics.push(col_stats);
380 }
381 self.statistics = Some(Arc::new(stats));
382 }
383 self
384 }
385
386 pub fn has_statistics(&self) -> bool {
390 if let Some(stats) = &self.statistics {
391 stats.column_statistics.iter().any(|col_stats| {
392 col_stats.null_count != Precision::Absent
393 || col_stats.max_value != Precision::Absent
394 || col_stats.min_value != Precision::Absent
395 || col_stats.sum_value != Precision::Absent
396 || col_stats.distinct_count != Precision::Absent
397 })
398 } else {
399 false
400 }
401 }
402
403 pub fn with_ordering(mut self, ordering: Option<LexOrdering>) -> Self {
408 self.ordering = ordering;
409 self
410 }
411}
412
413impl From<ObjectMeta> for PartitionedFile {
414 fn from(object_meta: ObjectMeta) -> Self {
415 PartitionedFile {
416 object_meta,
417 arrow_schema: None,
418 partition_values: vec![],
419 range: None,
420 statistics: None,
421 ordering: None,
422 extensions: FileExtensions::new(),
423 metadata_size_hint: None,
424 table_reference: None,
425 }
426 }
427}
428
429pub fn generate_test_files(num_files: usize, overlap_factor: f64) -> Vec<FileGroup> {
469 let mut files = Vec::with_capacity(num_files);
470 if num_files == 0 {
471 return vec![];
472 }
473 let range_size = if overlap_factor == 0.0 {
474 100 / num_files as i64
475 } else {
476 (100.0 / (overlap_factor * num_files as f64)).max(1.0) as i64
477 };
478
479 for i in 0..num_files {
480 let base = (i as f64 * range_size as f64 * (1.0 - overlap_factor)) as i64;
481 let min = base as f64;
482 let max = (base + range_size) as f64;
483
484 let file = PartitionedFile {
485 arrow_schema: None,
486 object_meta: ObjectMeta {
487 location: Path::from(format!("file_{i}.parquet")),
488 last_modified: chrono::Utc::now(),
489 size: 1000,
490 e_tag: None,
491 version: None,
492 },
493 partition_values: vec![],
494 range: None,
495 statistics: Some(Arc::new(Statistics {
496 num_rows: Precision::Exact(100),
497 total_byte_size: Precision::Exact(1000),
498 column_statistics: vec![ColumnStatistics {
499 null_count: Precision::Exact(0),
500 max_value: Precision::Exact(ScalarValue::Float64(Some(max))),
501 min_value: Precision::Exact(ScalarValue::Float64(Some(min))),
502 sum_value: Precision::Absent,
503 distinct_count: Precision::Absent,
504 byte_size: Precision::Absent,
505 }],
506 })),
507 ordering: None,
508 extensions: FileExtensions::new(),
509 metadata_size_hint: None,
510 table_reference: None,
511 };
512 files.push(file);
513 }
514
515 vec![FileGroup::new(files)]
516}
517
518pub fn verify_sort_integrity(file_groups: &[FileGroup]) -> bool {
521 for group in file_groups {
522 let files = group.iter().collect::<Vec<_>>();
523 for i in 1..files.len() {
524 let prev_file = files[i - 1];
525 let curr_file = files[i];
526
527 if let (Some(prev_stats), Some(curr_stats)) =
529 (&prev_file.statistics, &curr_file.statistics)
530 {
531 let prev_max = &prev_stats.column_statistics[0].max_value;
532 let curr_min = &curr_stats.column_statistics[0].min_value;
533 if curr_min.get_value().unwrap() <= prev_max.get_value().unwrap() {
534 return false;
535 }
536 }
537 }
538 }
539 true
540}
541
542#[cfg(test)]
543mod tests {
544 use super::ListingTableUrl;
545 use arrow::{
546 array::{ArrayRef, Int32Array, RecordBatch},
547 datatypes::{DataType, Field, Schema, SchemaRef},
548 };
549 use datafusion_execution::object_store::{
550 DefaultObjectStoreRegistry, ObjectStoreRegistry,
551 };
552 use object_store::{local::LocalFileSystem, path::Path};
553 use std::{collections::HashMap, ops::Not, sync::Arc};
554 use url::Url;
555
556 pub fn make_partition(sz: i32) -> RecordBatch {
558 let seq_start = 0;
559 let seq_end = sz;
560 let values = (seq_start..seq_end).collect::<Vec<_>>();
561 let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, true)]));
562 let arr = Arc::new(Int32Array::from(values));
563
564 RecordBatch::try_new(schema, vec![arr as ArrayRef]).unwrap()
565 }
566
567 pub fn aggr_test_schema() -> SchemaRef {
569 let mut f1 = Field::new("c1", DataType::Utf8, false);
570 f1.set_metadata(HashMap::from_iter(vec![("testing".into(), "test".into())]));
571 let schema = Schema::new(vec![
572 f1,
573 Field::new("c2", DataType::UInt32, false),
574 Field::new("c3", DataType::Int8, false),
575 Field::new("c4", DataType::Int16, false),
576 Field::new("c5", DataType::Int32, false),
577 Field::new("c6", DataType::Int64, false),
578 Field::new("c7", DataType::UInt8, false),
579 Field::new("c8", DataType::UInt16, false),
580 Field::new("c9", DataType::UInt32, false),
581 Field::new("c10", DataType::UInt64, false),
582 Field::new("c11", DataType::Float32, false),
583 Field::new("c12", DataType::Float64, false),
584 Field::new("c13", DataType::Utf8, false),
585 ]);
586
587 Arc::new(schema)
588 }
589
590 #[test]
591 fn test_object_store_listing_url() {
592 let listing = ListingTableUrl::parse("file:///").unwrap();
593 let store = listing.object_store();
594 assert_eq!(store.as_str(), "file:///");
595
596 let listing = ListingTableUrl::parse("s3://bucket/").unwrap();
597 let store = listing.object_store();
598 assert_eq!(store.as_str(), "s3://bucket/");
599 }
600
601 #[test]
602 fn test_get_store_hdfs() {
603 let sut = DefaultObjectStoreRegistry::default();
604 let url = Url::parse("hdfs://localhost:8020").unwrap();
605 sut.register_store(&url, Arc::new(LocalFileSystem::new()));
606 let url = ListingTableUrl::parse("hdfs://localhost:8020/key").unwrap();
607 sut.get_store(url.as_ref()).unwrap();
608 }
609
610 #[test]
611 fn test_get_store_s3() {
612 let sut = DefaultObjectStoreRegistry::default();
613 let url = Url::parse("s3://bucket/key").unwrap();
614 sut.register_store(&url, Arc::new(LocalFileSystem::new()));
615 let url = ListingTableUrl::parse("s3://bucket/key").unwrap();
616 sut.get_store(url.as_ref()).unwrap();
617 }
618
619 #[test]
620 fn test_get_store_file() {
621 let sut = DefaultObjectStoreRegistry::default();
622 let url = ListingTableUrl::parse("file:///bucket/key").unwrap();
623 sut.get_store(url.as_ref()).unwrap();
624 }
625
626 #[test]
627 fn test_get_store_local() {
628 let sut = DefaultObjectStoreRegistry::default();
629 let url = ListingTableUrl::parse("../").unwrap();
630 sut.get_store(url.as_ref()).unwrap();
631 }
632
633 #[test]
634 fn test_with_statistics_appends_partition_column_stats() {
635 use crate::PartitionedFile;
636 use datafusion_common::stats::Precision;
637 use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
638
639 let mut pf = PartitionedFile::new(
641 "test.parquet",
642 100, );
644 pf.partition_values = vec![
645 ScalarValue::Date32(Some(20148)), ];
647
648 let file_stats = Arc::new(Statistics {
650 num_rows: Precision::Exact(2),
651 total_byte_size: Precision::Exact(16),
652 column_statistics: vec![ColumnStatistics {
653 null_count: Precision::Exact(0),
654 max_value: Precision::Exact(ScalarValue::Int32(Some(4))),
655 min_value: Precision::Exact(ScalarValue::Int32(Some(3))),
656 sum_value: Precision::Absent,
657 distinct_count: Precision::Absent,
658 byte_size: Precision::Absent,
659 }],
660 });
661
662 let pf = pf.with_statistics(file_stats);
664
665 let stats = pf.statistics.unwrap();
667 assert_eq!(
668 stats.column_statistics.len(),
669 2,
670 "Expected 2 columns (id + date partition)"
671 );
672
673 let partition_col_stats = &stats.column_statistics[1];
675 assert_eq!(
676 partition_col_stats.null_count,
677 Precision::Exact(0),
678 "Partition column null_count should be Exact(0)"
679 );
680 assert_eq!(
681 partition_col_stats.min_value,
682 Precision::Exact(ScalarValue::Date32(Some(20148))),
683 "Partition column min should match partition value"
684 );
685 assert_eq!(
686 partition_col_stats.max_value,
687 Precision::Exact(ScalarValue::Date32(Some(20148))),
688 "Partition column max should match partition value"
689 );
690 assert_eq!(
691 partition_col_stats.distinct_count,
692 Precision::Exact(1),
693 "Partition column distinct_count should be Exact(1)"
694 );
695 }
696
697 #[test]
698 fn test_with_statistics_null_partition_value() {
699 use crate::PartitionedFile;
700 use datafusion_common::stats::Precision;
701 use datafusion_common::{ScalarValue, Statistics};
702
703 let mut pf = PartitionedFile::new("test.parquet", 100);
704 pf.partition_values = vec![ScalarValue::Date32(None)];
705
706 let file_stats = Arc::new(Statistics {
707 num_rows: Precision::Exact(2),
708 total_byte_size: Precision::Exact(16),
709 column_statistics: vec![],
710 });
711
712 let stats = pf.with_statistics(file_stats).statistics.unwrap();
713 let partition_col_stats = &stats.column_statistics[0];
714 assert_eq!(partition_col_stats.null_count, Precision::Exact(2));
715 assert_eq!(partition_col_stats.min_value, Precision::Absent);
716 assert_eq!(partition_col_stats.max_value, Precision::Absent);
717 assert_eq!(partition_col_stats.distinct_count, Precision::Exact(0));
718 }
719
720 #[test]
721 fn test_url_contains() {
722 let url = ListingTableUrl::parse("file:///var/data/mytable/").unwrap();
723
724 assert!(url.contains(
726 &Path::parse("/var/data/mytable/data.parquet").unwrap(),
727 true
728 ));
729
730 assert!(url.contains(
732 &Path::parse("/var/data/mytable/data.parquet").unwrap(),
733 false
734 ));
735
736 assert!(
739 url.contains(
740 &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
741 true
742 )
743 .not()
744 );
745
746 assert!(url.contains(
748 &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
749 false
750 ));
751
752 assert!(url.contains(
754 &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
755 false
756 ));
757
758 assert!(url.contains(
762 &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
763 true
764 ));
765
766 assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), true));
768
769 assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), false));
771 }
772}