1#![doc(
6 html_logo_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg",
7 html_favicon_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg"
8)]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10#![cfg_attr(not(test), deny(clippy::clone_on_ref_ptr))]
13#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
14
15pub mod boundary_stream;
19pub mod decoder;
20pub mod display;
21pub mod file;
22pub mod file_compression_type;
23pub mod file_format;
24pub mod file_groups;
25pub mod file_scan_config;
26pub mod file_sink_config;
27pub mod file_stream;
28pub mod memory;
29pub mod morsel;
30pub mod projection;
31#[cfg(feature = "proto")]
34mod proto;
35pub mod schema_adapter;
36pub mod sink;
37pub mod source;
38mod statistics;
39pub mod table_schema;
40
41#[cfg(test)]
42pub mod test_util;
43
44pub mod url;
45pub mod write;
46pub use self::file::as_file_source;
47pub use self::url::ListingTableUrl;
48use crate::file_groups::FileGroup;
49use arrow::datatypes::SchemaRef;
50use chrono::TimeZone;
51use datafusion_common::stats::{Precision, is_known_empty};
52use datafusion_common::{ColumnStatistics, Result, TableReference};
53use datafusion_common::{ScalarValue, Statistics};
54use datafusion_physical_expr::LexOrdering;
55use futures::Stream;
56use object_store::{ObjectMeta, path::Path};
57pub use statistics::compute_all_files_statistics;
58use std::any::Any;
59use std::pin::Pin;
60use std::sync::Arc;
61pub use table_schema::{TableSchema, TableSchemaBuilder};
62
63pub type FileExtensions = datafusion_common::extensions::Extensions;
69
70#[deprecated(
72 since = "54.0.0",
73 note = "This type is unused and will be removed in a future release"
74)]
75pub type PartitionedFileStream =
76 Pin<Box<dyn Stream<Item = Result<PartitionedFile>> + Send + Sync + 'static>>;
77
78#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
84pub struct FileRange {
85 pub start: i64,
87 pub end: i64,
89}
90
91impl FileRange {
92 pub fn contains(&self, offset: i64) -> bool {
94 offset >= self.start && offset < self.end
95 }
96}
97
98#[derive(Debug, Clone)]
99pub struct PartitionedFile {
118 pub object_meta: ObjectMeta,
120 pub partition_values: Vec<ScalarValue>,
131 pub range: Option<FileRange>,
133 pub statistics: Option<Arc<Statistics>>,
142 pub ordering: Option<LexOrdering>,
152 pub extensions: FileExtensions,
156 pub metadata_size_hint: Option<usize>,
158 pub table_reference: Option<TableReference>,
159 pub arrow_schema: Option<SchemaRef>,
169}
170
171impl PartitionedFile {
172 pub fn new(path: impl Into<String>, size: u64) -> Self {
174 Self {
175 arrow_schema: None,
176 object_meta: ObjectMeta {
177 location: Path::from(path.into()),
178 last_modified: chrono::Utc.timestamp_nanos(0),
179 size,
180 e_tag: None,
181 version: None,
182 },
183 partition_values: vec![],
184 range: None,
185 statistics: None,
186 ordering: None,
187 extensions: FileExtensions::new(),
188 metadata_size_hint: None,
189 table_reference: None,
190 }
191 }
192
193 pub fn new_from_meta(object_meta: ObjectMeta) -> Self {
195 Self {
196 arrow_schema: None,
197 object_meta,
198 partition_values: vec![],
199 range: None,
200 statistics: None,
201 ordering: None,
202 extensions: FileExtensions::new(),
203 metadata_size_hint: None,
204 table_reference: None,
205 }
206 }
207
208 pub fn new_with_range(path: String, size: u64, start: i64, end: i64) -> Self {
210 Self {
211 arrow_schema: None,
212 object_meta: ObjectMeta {
213 location: Path::from(path),
214 last_modified: chrono::Utc.timestamp_nanos(0),
215 size,
216 e_tag: None,
217 version: None,
218 },
219 partition_values: vec![],
220 range: Some(FileRange { start, end }),
221 statistics: None,
222 ordering: None,
223 extensions: FileExtensions::new(),
224 metadata_size_hint: None,
225 table_reference: None,
226 }
227 .with_range(start, end)
228 }
229
230 pub fn with_arrow_schema(mut self, schema: SchemaRef) -> Self {
235 self.arrow_schema = Some(schema);
236 self
237 }
238
239 pub fn with_partition_values(mut self, partition_values: Vec<ScalarValue>) -> Self {
242 self.partition_values = partition_values;
243 self
244 }
245
246 pub fn with_table_reference(
247 mut self,
248 table_reference: Option<TableReference>,
249 ) -> Self {
250 self.table_reference = table_reference;
251 self
252 }
253
254 pub fn effective_size(&self) -> u64 {
256 if let Some(range) = &self.range {
257 (range.end - range.start) as u64
258 } else {
259 self.object_meta.size
260 }
261 }
262
263 pub fn range(&self) -> (u64, u64) {
265 if let Some(range) = &self.range {
266 (range.start as u64, range.end as u64)
267 } else {
268 (0, self.object_meta.size)
269 }
270 }
271
272 pub fn with_metadata_size_hint(mut self, metadata_size_hint: usize) -> Self {
276 self.metadata_size_hint = Some(metadata_size_hint);
277 self
278 }
279
280 pub fn from_path(path: String) -> Result<Self> {
282 let size = std::fs::metadata(path.clone())?.len();
283 Ok(Self::new(path, size))
284 }
285
286 pub fn path(&self) -> &Path {
288 &self.object_meta.location
289 }
290
291 pub fn with_range(mut self, start: i64, end: i64) -> Self {
293 self.range = Some(FileRange { start, end });
294 self
295 }
296
297 pub fn with_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
305 self.extensions.insert(value);
306 self
307 }
308
309 pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
311 self.extensions.get::<T>()
312 }
313
314 #[deprecated(
319 since = "54.0.0",
320 note = "use `with_extension`; the extension is keyed by its concrete type"
321 )]
322 pub fn with_extensions(mut self, extensions: Arc<dyn Any + Send + Sync>) -> Self {
323 #[expect(deprecated)]
324 self.extensions.insert_dyn(extensions);
325 self
326 }
327
328 pub fn with_statistics(mut self, file_statistics: Arc<Statistics>) -> Self {
340 if self.partition_values.is_empty() {
341 self.statistics = Some(file_statistics);
343 } else {
344 let mut stats = Arc::unwrap_or_clone(file_statistics);
346 for partition_value in &self.partition_values {
347 let (null_count, min_max, distinct_count) = if partition_value.is_null() {
348 (stats.num_rows, Precision::Absent, Precision::Exact(0))
349 } else {
350 (
351 Precision::Exact(0),
352 Precision::Exact(partition_value.clone()),
353 Precision::Exact(1),
354 )
355 };
356 let col_stats = ColumnStatistics {
357 null_count,
358 max_value: min_max.clone(),
359 min_value: min_max,
360 distinct_count,
361 sum_value: Precision::Absent,
362 byte_size: partition_value
363 .data_type()
364 .primitive_width()
365 .map(|w| stats.num_rows.multiply(&Precision::Exact(w)))
366 .unwrap_or_else(|| Precision::Absent),
367 };
368 stats.column_statistics.push(col_stats);
369 }
370 self.statistics = Some(Arc::new(stats));
371 }
372 self
373 }
374
375 pub fn has_statistics(&self) -> bool {
379 if let Some(stats) = &self.statistics {
380 stats.column_statistics.iter().any(|col_stats| {
381 col_stats.null_count != Precision::Absent
382 || col_stats.max_value != Precision::Absent
383 || col_stats.min_value != Precision::Absent
384 || col_stats.sum_value != Precision::Absent
385 || col_stats.distinct_count != Precision::Absent
386 })
387 } else {
388 false
389 }
390 }
391
392 pub fn with_ordering(mut self, ordering: Option<LexOrdering>) -> Self {
397 self.ordering = ordering;
398 self
399 }
400}
401
402impl From<ObjectMeta> for PartitionedFile {
403 fn from(object_meta: ObjectMeta) -> Self {
404 PartitionedFile {
405 object_meta,
406 arrow_schema: None,
407 partition_values: vec![],
408 range: None,
409 statistics: None,
410 ordering: None,
411 extensions: FileExtensions::new(),
412 metadata_size_hint: None,
413 table_reference: None,
414 }
415 }
416}
417
418#[doc(hidden)]
462pub fn generate_test_files(num_files: usize, overlap_factor: f64) -> Vec<FileGroup> {
463 let mut files = Vec::with_capacity(num_files);
464 if num_files == 0 {
465 return vec![];
466 }
467 let range_size = if overlap_factor == 0.0 {
468 100 / num_files as i64
469 } else {
470 (100.0 / (overlap_factor * num_files as f64)).max(1.0) as i64
471 };
472
473 for i in 0..num_files {
474 let base = (i as f64 * range_size as f64 * (1.0 - overlap_factor)) as i64;
475 let min = base as f64;
476 let max = (base + range_size) as f64;
477
478 let file = PartitionedFile {
479 arrow_schema: None,
480 object_meta: ObjectMeta {
481 location: Path::from(format!("file_{i}.parquet")),
482 last_modified: chrono::Utc::now(),
483 size: 1000,
484 e_tag: None,
485 version: None,
486 },
487 partition_values: vec![],
488 range: None,
489 statistics: Some(Arc::new(Statistics {
490 num_rows: Precision::Exact(100),
491 total_byte_size: Precision::Exact(1000),
492 column_statistics: vec![ColumnStatistics {
493 null_count: Precision::Exact(0),
494 max_value: Precision::Exact(ScalarValue::Float64(Some(max))),
495 min_value: Precision::Exact(ScalarValue::Float64(Some(min))),
496 sum_value: Precision::Absent,
497 distinct_count: Precision::Absent,
498 byte_size: Precision::Absent,
499 }],
500 })),
501 ordering: None,
502 extensions: FileExtensions::new(),
503 metadata_size_hint: None,
504 table_reference: None,
505 };
506 files.push(file);
507 }
508
509 vec![FileGroup::new(files)]
510}
511
512#[doc(hidden)]
520pub fn verify_sort_integrity(file_groups: &[FileGroup]) -> bool {
521 for group in file_groups {
522 let files = group
525 .iter()
526 .filter(|file| !file.statistics.as_deref().is_some_and(is_known_empty))
527 .collect::<Vec<_>>();
528 for i in 1..files.len() {
529 let prev_file = files[i - 1];
530 let curr_file = files[i];
531
532 if let (Some(prev_stats), Some(curr_stats)) =
534 (&prev_file.statistics, &curr_file.statistics)
535 {
536 let prev_max = &prev_stats.column_statistics[0].max_value;
537 let curr_min = &curr_stats.column_statistics[0].min_value;
538 if curr_min.get_value().unwrap() <= prev_max.get_value().unwrap() {
539 return false;
540 }
541 }
542 }
543 }
544 true
545}
546
547#[cfg(test)]
548mod tests {
549 use super::ListingTableUrl;
550 use arrow::{
551 array::{ArrayRef, Int32Array, RecordBatch},
552 datatypes::{DataType, Field, Schema, SchemaRef},
553 };
554 use datafusion_execution::object_store::{
555 DefaultObjectStoreRegistry, ObjectStoreRegistry,
556 };
557 use object_store::{local::LocalFileSystem, path::Path};
558 use std::{collections::HashMap, ops::Not, sync::Arc};
559 use url::Url;
560
561 pub fn make_partition(sz: i32) -> RecordBatch {
563 let seq_start = 0;
564 let seq_end = sz;
565 let values = (seq_start..seq_end).collect::<Vec<_>>();
566 let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, true)]));
567 let arr = Arc::new(Int32Array::from(values));
568
569 RecordBatch::try_new(schema, vec![arr as ArrayRef]).unwrap()
570 }
571
572 pub fn aggr_test_schema() -> SchemaRef {
574 let mut f1 = Field::new("c1", DataType::Utf8, false);
575 f1.set_metadata(HashMap::from_iter(vec![("testing".into(), "test".into())]));
576 let schema = Schema::new(vec![
577 f1,
578 Field::new("c2", DataType::UInt32, false),
579 Field::new("c3", DataType::Int8, false),
580 Field::new("c4", DataType::Int16, false),
581 Field::new("c5", DataType::Int32, false),
582 Field::new("c6", DataType::Int64, false),
583 Field::new("c7", DataType::UInt8, false),
584 Field::new("c8", DataType::UInt16, false),
585 Field::new("c9", DataType::UInt32, false),
586 Field::new("c10", DataType::UInt64, false),
587 Field::new("c11", DataType::Float32, false),
588 Field::new("c12", DataType::Float64, false),
589 Field::new("c13", DataType::Utf8, false),
590 ]);
591
592 Arc::new(schema)
593 }
594
595 #[test]
596 fn test_object_store_listing_url() {
597 let listing = ListingTableUrl::parse("file:///").unwrap();
598 let store = listing.object_store();
599 assert_eq!(store.as_str(), "file:///");
600
601 let listing = ListingTableUrl::parse("s3://bucket/").unwrap();
602 let store = listing.object_store();
603 assert_eq!(store.as_str(), "s3://bucket/");
604 }
605
606 #[test]
607 fn test_get_store_hdfs() {
608 let sut = DefaultObjectStoreRegistry::default();
609 let url = Url::parse("hdfs://localhost:8020").unwrap();
610 sut.register_store(&url, Arc::new(LocalFileSystem::new()));
611 let url = ListingTableUrl::parse("hdfs://localhost:8020/key").unwrap();
612 sut.get_store(url.as_ref()).unwrap();
613 }
614
615 #[test]
616 fn test_get_store_s3() {
617 let sut = DefaultObjectStoreRegistry::default();
618 let url = Url::parse("s3://bucket/key").unwrap();
619 sut.register_store(&url, Arc::new(LocalFileSystem::new()));
620 let url = ListingTableUrl::parse("s3://bucket/key").unwrap();
621 sut.get_store(url.as_ref()).unwrap();
622 }
623
624 #[test]
625 fn test_get_store_file() {
626 let sut = DefaultObjectStoreRegistry::default();
627 let url = ListingTableUrl::parse("file:///bucket/key").unwrap();
628 sut.get_store(url.as_ref()).unwrap();
629 }
630
631 #[test]
632 fn test_get_store_local() {
633 let sut = DefaultObjectStoreRegistry::default();
634 let url = ListingTableUrl::parse("../").unwrap();
635 sut.get_store(url.as_ref()).unwrap();
636 }
637
638 #[test]
639 fn test_with_statistics_appends_partition_column_stats() {
640 use crate::PartitionedFile;
641 use datafusion_common::stats::Precision;
642 use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
643
644 let mut pf = PartitionedFile::new(
646 "test.parquet",
647 100, );
649 pf.partition_values = vec![
650 ScalarValue::Date32(Some(20148)), ];
652
653 let file_stats = Arc::new(Statistics {
655 num_rows: Precision::Exact(2),
656 total_byte_size: Precision::Exact(16),
657 column_statistics: vec![ColumnStatistics {
658 null_count: Precision::Exact(0),
659 max_value: Precision::Exact(ScalarValue::Int32(Some(4))),
660 min_value: Precision::Exact(ScalarValue::Int32(Some(3))),
661 sum_value: Precision::Absent,
662 distinct_count: Precision::Absent,
663 byte_size: Precision::Absent,
664 }],
665 });
666
667 let pf = pf.with_statistics(file_stats);
669
670 let stats = pf.statistics.unwrap();
672 assert_eq!(
673 stats.column_statistics.len(),
674 2,
675 "Expected 2 columns (id + date partition)"
676 );
677
678 let partition_col_stats = &stats.column_statistics[1];
680 assert_eq!(
681 partition_col_stats.null_count,
682 Precision::Exact(0),
683 "Partition column null_count should be Exact(0)"
684 );
685 assert_eq!(
686 partition_col_stats.min_value,
687 Precision::Exact(ScalarValue::Date32(Some(20148))),
688 "Partition column min should match partition value"
689 );
690 assert_eq!(
691 partition_col_stats.max_value,
692 Precision::Exact(ScalarValue::Date32(Some(20148))),
693 "Partition column max should match partition value"
694 );
695 assert_eq!(
696 partition_col_stats.distinct_count,
697 Precision::Exact(1),
698 "Partition column distinct_count should be Exact(1)"
699 );
700 }
701
702 #[test]
703 fn test_with_statistics_null_partition_value() {
704 use crate::PartitionedFile;
705 use datafusion_common::stats::Precision;
706 use datafusion_common::{ScalarValue, Statistics};
707
708 let mut pf = PartitionedFile::new("test.parquet", 100);
709 pf.partition_values = vec![ScalarValue::Date32(None)];
710
711 let file_stats = Arc::new(Statistics {
712 num_rows: Precision::Exact(2),
713 total_byte_size: Precision::Exact(16),
714 column_statistics: vec![],
715 });
716
717 let stats = pf.with_statistics(file_stats).statistics.unwrap();
718 let partition_col_stats = &stats.column_statistics[0];
719 assert_eq!(partition_col_stats.null_count, Precision::Exact(2));
720 assert_eq!(partition_col_stats.min_value, Precision::Absent);
721 assert_eq!(partition_col_stats.max_value, Precision::Absent);
722 assert_eq!(partition_col_stats.distinct_count, Precision::Exact(0));
723 }
724
725 #[test]
726 fn test_url_contains() {
727 let url = ListingTableUrl::parse("file:///var/data/mytable/").unwrap();
728
729 assert!(url.contains(
731 &Path::parse("/var/data/mytable/data.parquet").unwrap(),
732 true
733 ));
734
735 assert!(url.contains(
737 &Path::parse("/var/data/mytable/data.parquet").unwrap(),
738 false
739 ));
740
741 assert!(
744 url.contains(
745 &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
746 true
747 )
748 .not()
749 );
750
751 assert!(url.contains(
753 &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
754 false
755 ));
756
757 assert!(url.contains(
759 &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
760 false
761 ));
762
763 assert!(url.contains(
767 &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
768 true
769 ));
770
771 assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), true));
773
774 assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), false));
776 }
777}