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 decoder;
32pub mod display;
33pub mod file;
34pub mod file_compression_type;
35pub mod file_format;
36pub mod file_groups;
37pub mod file_scan_config;
38pub mod file_sink_config;
39pub mod file_stream;
40pub mod memory;
41pub mod morsel;
42pub mod projection;
43pub mod schema_adapter;
44pub mod sink;
45pub mod source;
46mod statistics;
47pub mod table_schema;
48
49#[cfg(test)]
50pub mod test_util;
51
52pub mod url;
53pub mod write;
54pub use self::file::as_file_source;
55pub use self::url::ListingTableUrl;
56use crate::file_groups::FileGroup;
57use chrono::TimeZone;
58use datafusion_common::stats::Precision;
59use datafusion_common::{ColumnStatistics, Result, TableReference, exec_datafusion_err};
60use datafusion_common::{ScalarValue, Statistics};
61use datafusion_physical_expr::LexOrdering;
62use futures::{Stream, StreamExt};
63use object_store::{GetOptions, GetRange, ObjectStore};
64use object_store::{ObjectMeta, path::Path};
65pub use table_schema::TableSchema;
66#[expect(deprecated)]
68pub use statistics::add_row_stats;
69pub use statistics::compute_all_files_statistics;
70use std::any::Any;
71use std::ops::Range;
72use std::pin::Pin;
73use std::sync::Arc;
74
75pub type FileExtensions = datafusion_common::extensions::Extensions;
81
82#[deprecated(
84 since = "54.0.0",
85 note = "This type is unused and will be removed in a future release"
86)]
87pub type PartitionedFileStream =
88 Pin<Box<dyn Stream<Item = Result<PartitionedFile>> + Send + Sync + 'static>>;
89
90#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
94pub struct FileRange {
95 pub start: i64,
97 pub end: i64,
99}
100
101impl FileRange {
102 pub fn contains(&self, offset: i64) -> bool {
104 offset >= self.start && offset < self.end
105 }
106}
107
108#[derive(Debug, Clone)]
109pub struct PartitionedFile {
128 pub object_meta: ObjectMeta,
130 pub partition_values: Vec<ScalarValue>,
141 pub range: Option<FileRange>,
143 pub statistics: Option<Arc<Statistics>>,
152 pub ordering: Option<LexOrdering>,
162 pub extensions: FileExtensions,
166 pub metadata_size_hint: Option<usize>,
168 pub table_reference: Option<TableReference>,
169}
170
171impl PartitionedFile {
172 pub fn new(path: impl Into<String>, size: u64) -> Self {
174 Self {
175 object_meta: ObjectMeta {
176 location: Path::from(path.into()),
177 last_modified: chrono::Utc.timestamp_nanos(0),
178 size,
179 e_tag: None,
180 version: None,
181 },
182 partition_values: vec![],
183 range: None,
184 statistics: None,
185 ordering: None,
186 extensions: FileExtensions::new(),
187 metadata_size_hint: None,
188 table_reference: None,
189 }
190 }
191
192 pub fn new_from_meta(object_meta: ObjectMeta) -> Self {
194 Self {
195 object_meta,
196 partition_values: vec![],
197 range: None,
198 statistics: None,
199 ordering: None,
200 extensions: FileExtensions::new(),
201 metadata_size_hint: None,
202 table_reference: None,
203 }
204 }
205
206 pub fn new_with_range(path: String, size: u64, start: i64, end: i64) -> Self {
208 Self {
209 object_meta: ObjectMeta {
210 location: Path::from(path),
211 last_modified: chrono::Utc.timestamp_nanos(0),
212 size,
213 e_tag: None,
214 version: None,
215 },
216 partition_values: vec![],
217 range: Some(FileRange { start, end }),
218 statistics: None,
219 ordering: None,
220 extensions: FileExtensions::new(),
221 metadata_size_hint: None,
222 table_reference: None,
223 }
224 .with_range(start, end)
225 }
226
227 pub fn with_partition_values(mut self, partition_values: Vec<ScalarValue>) -> Self {
230 self.partition_values = partition_values;
231 self
232 }
233
234 pub fn with_table_reference(
235 mut self,
236 table_reference: Option<TableReference>,
237 ) -> Self {
238 self.table_reference = table_reference;
239 self
240 }
241
242 pub fn effective_size(&self) -> u64 {
244 if let Some(range) = &self.range {
245 (range.end - range.start) as u64
246 } else {
247 self.object_meta.size
248 }
249 }
250
251 pub fn range(&self) -> (u64, u64) {
253 if let Some(range) = &self.range {
254 (range.start as u64, range.end as u64)
255 } else {
256 (0, self.object_meta.size)
257 }
258 }
259
260 pub fn with_metadata_size_hint(mut self, metadata_size_hint: usize) -> Self {
264 self.metadata_size_hint = Some(metadata_size_hint);
265 self
266 }
267
268 pub fn from_path(path: String) -> Result<Self> {
270 let size = std::fs::metadata(path.clone())?.len();
271 Ok(Self::new(path, size))
272 }
273
274 pub fn path(&self) -> &Path {
276 &self.object_meta.location
277 }
278
279 pub fn with_range(mut self, start: i64, end: i64) -> Self {
281 self.range = Some(FileRange { start, end });
282 self
283 }
284
285 pub fn with_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
293 self.extensions.insert(value);
294 self
295 }
296
297 pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
299 self.extensions.get::<T>()
300 }
301
302 #[deprecated(
307 since = "54.0.0",
308 note = "use `with_extension`; the extension is keyed by its concrete type"
309 )]
310 pub fn with_extensions(mut self, extensions: Arc<dyn Any + Send + Sync>) -> Self {
311 #[expect(deprecated)]
312 self.extensions.insert_dyn(extensions);
313 self
314 }
315
316 pub fn with_statistics(mut self, file_statistics: Arc<Statistics>) -> Self {
328 if self.partition_values.is_empty() {
329 self.statistics = Some(file_statistics);
331 } else {
332 let mut stats = Arc::unwrap_or_clone(file_statistics);
334 for partition_value in &self.partition_values {
335 let (null_count, min_max, distinct_count) = if partition_value.is_null() {
336 (stats.num_rows, Precision::Absent, Precision::Exact(0))
337 } else {
338 (
339 Precision::Exact(0),
340 Precision::Exact(partition_value.clone()),
341 Precision::Exact(1),
342 )
343 };
344 let col_stats = ColumnStatistics {
345 null_count,
346 max_value: min_max.clone(),
347 min_value: min_max,
348 distinct_count,
349 sum_value: Precision::Absent,
350 byte_size: partition_value
351 .data_type()
352 .primitive_width()
353 .map(|w| stats.num_rows.multiply(&Precision::Exact(w)))
354 .unwrap_or_else(|| Precision::Absent),
355 };
356 stats.column_statistics.push(col_stats);
357 }
358 self.statistics = Some(Arc::new(stats));
359 }
360 self
361 }
362
363 pub fn has_statistics(&self) -> bool {
367 if let Some(stats) = &self.statistics {
368 stats.column_statistics.iter().any(|col_stats| {
369 col_stats.null_count != Precision::Absent
370 || col_stats.max_value != Precision::Absent
371 || col_stats.min_value != Precision::Absent
372 || col_stats.sum_value != Precision::Absent
373 || col_stats.distinct_count != Precision::Absent
374 })
375 } else {
376 false
377 }
378 }
379
380 pub fn with_ordering(mut self, ordering: Option<LexOrdering>) -> Self {
385 self.ordering = ordering;
386 self
387 }
388}
389
390impl From<ObjectMeta> for PartitionedFile {
391 fn from(object_meta: ObjectMeta) -> Self {
392 PartitionedFile {
393 object_meta,
394 partition_values: vec![],
395 range: None,
396 statistics: None,
397 ordering: None,
398 extensions: FileExtensions::new(),
399 metadata_size_hint: None,
400 table_reference: None,
401 }
402 }
403}
404
405pub enum RangeCalculation {
419 Range(Option<Range<u64>>),
420 TerminateEarly,
421}
422
423pub async fn calculate_range(
434 file: &PartitionedFile,
435 store: &Arc<dyn ObjectStore>,
436 terminator: Option<u8>,
437) -> Result<RangeCalculation> {
438 let location = &file.object_meta.location;
439 let file_size = file.object_meta.size;
440 let newline = terminator.unwrap_or(b'\n');
441
442 match file.range {
443 None => Ok(RangeCalculation::Range(None)),
444 Some(FileRange { start, end }) => {
445 let start: u64 = start.try_into().map_err(|_| {
446 exec_datafusion_err!("Expect start range to fit in u64, got {start}")
447 })?;
448 let end: u64 = end.try_into().map_err(|_| {
449 exec_datafusion_err!("Expect end range to fit in u64, got {end}")
450 })?;
451
452 let start_delta = if start != 0 {
453 find_first_newline(store, location, start - 1, file_size, newline).await?
454 } else {
455 0
456 };
457
458 if start + start_delta > end {
459 return Ok(RangeCalculation::TerminateEarly);
460 }
461
462 let end_delta = if end != file_size {
463 find_first_newline(store, location, end - 1, file_size, newline).await?
464 } else {
465 0
466 };
467
468 let range = start + start_delta..end + end_delta;
469
470 if range.start >= range.end {
471 return Ok(RangeCalculation::TerminateEarly);
472 }
473
474 Ok(RangeCalculation::Range(Some(range)))
475 }
476 }
477}
478
479async fn find_first_newline(
490 object_store: &Arc<dyn ObjectStore>,
491 location: &Path,
492 start: u64,
493 end: u64,
494 newline: u8,
495) -> Result<u64> {
496 let options = GetOptions {
497 range: Some(GetRange::Bounded(start..end)),
498 ..Default::default()
499 };
500
501 let result = object_store.get_opts(location, options).await?;
502 let mut result_stream = result.into_stream();
503
504 let mut index = 0;
505
506 while let Some(chunk) = result_stream.next().await.transpose()? {
507 if let Some(position) = chunk.iter().position(|&byte| byte == newline) {
508 let position = position as u64;
509 return Ok(index + position);
510 }
511
512 index += chunk.len() as u64;
513 }
514
515 Ok(index)
516}
517
518pub fn generate_test_files(num_files: usize, overlap_factor: f64) -> Vec<FileGroup> {
558 let mut files = Vec::with_capacity(num_files);
559 if num_files == 0 {
560 return vec![];
561 }
562 let range_size = if overlap_factor == 0.0 {
563 100 / num_files as i64
564 } else {
565 (100.0 / (overlap_factor * num_files as f64)).max(1.0) as i64
566 };
567
568 for i in 0..num_files {
569 let base = (i as f64 * range_size as f64 * (1.0 - overlap_factor)) as i64;
570 let min = base as f64;
571 let max = (base + range_size) as f64;
572
573 let file = PartitionedFile {
574 object_meta: ObjectMeta {
575 location: Path::from(format!("file_{i}.parquet")),
576 last_modified: chrono::Utc::now(),
577 size: 1000,
578 e_tag: None,
579 version: None,
580 },
581 partition_values: vec![],
582 range: None,
583 statistics: Some(Arc::new(Statistics {
584 num_rows: Precision::Exact(100),
585 total_byte_size: Precision::Exact(1000),
586 column_statistics: vec![ColumnStatistics {
587 null_count: Precision::Exact(0),
588 max_value: Precision::Exact(ScalarValue::Float64(Some(max))),
589 min_value: Precision::Exact(ScalarValue::Float64(Some(min))),
590 sum_value: Precision::Absent,
591 distinct_count: Precision::Absent,
592 byte_size: Precision::Absent,
593 }],
594 })),
595 ordering: None,
596 extensions: FileExtensions::new(),
597 metadata_size_hint: None,
598 table_reference: None,
599 };
600 files.push(file);
601 }
602
603 vec![FileGroup::new(files)]
604}
605
606pub fn verify_sort_integrity(file_groups: &[FileGroup]) -> bool {
609 for group in file_groups {
610 let files = group.iter().collect::<Vec<_>>();
611 for i in 1..files.len() {
612 let prev_file = files[i - 1];
613 let curr_file = files[i];
614
615 if let (Some(prev_stats), Some(curr_stats)) =
617 (&prev_file.statistics, &curr_file.statistics)
618 {
619 let prev_max = &prev_stats.column_statistics[0].max_value;
620 let curr_min = &curr_stats.column_statistics[0].min_value;
621 if curr_min.get_value().unwrap() <= prev_max.get_value().unwrap() {
622 return false;
623 }
624 }
625 }
626 }
627 true
628}
629
630#[cfg(test)]
631mod tests {
632 use super::ListingTableUrl;
633 use arrow::{
634 array::{ArrayRef, Int32Array, RecordBatch},
635 datatypes::{DataType, Field, Schema, SchemaRef},
636 };
637 use datafusion_execution::object_store::{
638 DefaultObjectStoreRegistry, ObjectStoreRegistry,
639 };
640 use object_store::{ObjectStoreExt, local::LocalFileSystem, path::Path};
641 use std::{collections::HashMap, ops::Not, sync::Arc};
642 use url::Url;
643
644 pub fn make_partition(sz: i32) -> RecordBatch {
646 let seq_start = 0;
647 let seq_end = sz;
648 let values = (seq_start..seq_end).collect::<Vec<_>>();
649 let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, true)]));
650 let arr = Arc::new(Int32Array::from(values));
651
652 RecordBatch::try_new(schema, vec![arr as ArrayRef]).unwrap()
653 }
654
655 pub fn aggr_test_schema() -> SchemaRef {
657 let mut f1 = Field::new("c1", DataType::Utf8, false);
658 f1.set_metadata(HashMap::from_iter(vec![("testing".into(), "test".into())]));
659 let schema = Schema::new(vec![
660 f1,
661 Field::new("c2", DataType::UInt32, false),
662 Field::new("c3", DataType::Int8, false),
663 Field::new("c4", DataType::Int16, false),
664 Field::new("c5", DataType::Int32, false),
665 Field::new("c6", DataType::Int64, false),
666 Field::new("c7", DataType::UInt8, false),
667 Field::new("c8", DataType::UInt16, false),
668 Field::new("c9", DataType::UInt32, false),
669 Field::new("c10", DataType::UInt64, false),
670 Field::new("c11", DataType::Float32, false),
671 Field::new("c12", DataType::Float64, false),
672 Field::new("c13", DataType::Utf8, false),
673 ]);
674
675 Arc::new(schema)
676 }
677
678 #[test]
679 fn test_object_store_listing_url() {
680 let listing = ListingTableUrl::parse("file:///").unwrap();
681 let store = listing.object_store();
682 assert_eq!(store.as_str(), "file:///");
683
684 let listing = ListingTableUrl::parse("s3://bucket/").unwrap();
685 let store = listing.object_store();
686 assert_eq!(store.as_str(), "s3://bucket/");
687 }
688
689 #[test]
690 fn test_get_store_hdfs() {
691 let sut = DefaultObjectStoreRegistry::default();
692 let url = Url::parse("hdfs://localhost:8020").unwrap();
693 sut.register_store(&url, Arc::new(LocalFileSystem::new()));
694 let url = ListingTableUrl::parse("hdfs://localhost:8020/key").unwrap();
695 sut.get_store(url.as_ref()).unwrap();
696 }
697
698 #[test]
699 fn test_get_store_s3() {
700 let sut = DefaultObjectStoreRegistry::default();
701 let url = Url::parse("s3://bucket/key").unwrap();
702 sut.register_store(&url, Arc::new(LocalFileSystem::new()));
703 let url = ListingTableUrl::parse("s3://bucket/key").unwrap();
704 sut.get_store(url.as_ref()).unwrap();
705 }
706
707 #[test]
708 fn test_get_store_file() {
709 let sut = DefaultObjectStoreRegistry::default();
710 let url = ListingTableUrl::parse("file:///bucket/key").unwrap();
711 sut.get_store(url.as_ref()).unwrap();
712 }
713
714 #[test]
715 fn test_get_store_local() {
716 let sut = DefaultObjectStoreRegistry::default();
717 let url = ListingTableUrl::parse("../").unwrap();
718 sut.get_store(url.as_ref()).unwrap();
719 }
720
721 #[test]
722 fn test_with_statistics_appends_partition_column_stats() {
723 use crate::PartitionedFile;
724 use datafusion_common::stats::Precision;
725 use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
726
727 let mut pf = PartitionedFile::new(
729 "test.parquet",
730 100, );
732 pf.partition_values = vec![
733 ScalarValue::Date32(Some(20148)), ];
735
736 let file_stats = Arc::new(Statistics {
738 num_rows: Precision::Exact(2),
739 total_byte_size: Precision::Exact(16),
740 column_statistics: vec![ColumnStatistics {
741 null_count: Precision::Exact(0),
742 max_value: Precision::Exact(ScalarValue::Int32(Some(4))),
743 min_value: Precision::Exact(ScalarValue::Int32(Some(3))),
744 sum_value: Precision::Absent,
745 distinct_count: Precision::Absent,
746 byte_size: Precision::Absent,
747 }],
748 });
749
750 let pf = pf.with_statistics(file_stats);
752
753 let stats = pf.statistics.unwrap();
755 assert_eq!(
756 stats.column_statistics.len(),
757 2,
758 "Expected 2 columns (id + date partition)"
759 );
760
761 let partition_col_stats = &stats.column_statistics[1];
763 assert_eq!(
764 partition_col_stats.null_count,
765 Precision::Exact(0),
766 "Partition column null_count should be Exact(0)"
767 );
768 assert_eq!(
769 partition_col_stats.min_value,
770 Precision::Exact(ScalarValue::Date32(Some(20148))),
771 "Partition column min should match partition value"
772 );
773 assert_eq!(
774 partition_col_stats.max_value,
775 Precision::Exact(ScalarValue::Date32(Some(20148))),
776 "Partition column max should match partition value"
777 );
778 assert_eq!(
779 partition_col_stats.distinct_count,
780 Precision::Exact(1),
781 "Partition column distinct_count should be Exact(1)"
782 );
783 }
784
785 #[test]
786 fn test_with_statistics_null_partition_value() {
787 use crate::PartitionedFile;
788 use datafusion_common::stats::Precision;
789 use datafusion_common::{ScalarValue, Statistics};
790
791 let mut pf = PartitionedFile::new("test.parquet", 100);
792 pf.partition_values = vec![ScalarValue::Date32(None)];
793
794 let file_stats = Arc::new(Statistics {
795 num_rows: Precision::Exact(2),
796 total_byte_size: Precision::Exact(16),
797 column_statistics: vec![],
798 });
799
800 let stats = pf.with_statistics(file_stats).statistics.unwrap();
801 let partition_col_stats = &stats.column_statistics[0];
802 assert_eq!(partition_col_stats.null_count, Precision::Exact(2));
803 assert_eq!(partition_col_stats.min_value, Precision::Absent);
804 assert_eq!(partition_col_stats.max_value, Precision::Absent);
805 assert_eq!(partition_col_stats.distinct_count, Precision::Exact(0));
806 }
807
808 #[test]
809 fn test_url_contains() {
810 let url = ListingTableUrl::parse("file:///var/data/mytable/").unwrap();
811
812 assert!(url.contains(
814 &Path::parse("/var/data/mytable/data.parquet").unwrap(),
815 true
816 ));
817
818 assert!(url.contains(
820 &Path::parse("/var/data/mytable/data.parquet").unwrap(),
821 false
822 ));
823
824 assert!(
827 url.contains(
828 &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
829 true
830 )
831 .not()
832 );
833
834 assert!(url.contains(
836 &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
837 false
838 ));
839
840 assert!(url.contains(
842 &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
843 false
844 ));
845
846 assert!(url.contains(
850 &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
851 true
852 ));
853
854 assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), true));
856
857 assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), false));
859 }
860
861 #[tokio::test]
863 async fn test_calculate_range_single_line_file() {
864 use super::{PartitionedFile, RangeCalculation, calculate_range};
865 use object_store::ObjectStore;
866 use object_store::memory::InMemory;
867
868 let content = r#"{"id":1,"data":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}"#;
869 let file_size = content.len() as u64;
870
871 let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
872 let path = Path::from("test.json");
873 store.put(&path, content.into()).await.unwrap();
874
875 let mid = file_size / 2;
876 let partitioned_file = PartitionedFile::new_with_range(
877 path.to_string(),
878 file_size,
879 mid as i64,
880 file_size as i64,
881 );
882
883 let result = calculate_range(&partitioned_file, &store, None).await;
884
885 assert!(matches!(result, Ok(RangeCalculation::TerminateEarly)));
886 }
887}