Skip to main content

datafusion_datasource/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5#![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// Make sure fast / cheap clones on Arc are explicit:
11// https://github.com/apache/datafusion/issues/11143
12#![cfg_attr(not(test), deny(clippy::clone_on_ref_ptr))]
13#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
14
15//! A table that uses the `ObjectStore` listing capability
16//! to get the list of files to process.
17
18pub 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/// Protobuf conversions for [`FileRange`], [`PartitionedFile`] and
32/// [`FileGroup`], gated on the `proto` feature.
33#[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
63/// User-defined per-file extension data, keyed by concrete Rust type.
64///
65/// Re-exported from [`datafusion_common::extensions::Extensions`]; the same
66/// type backs `SessionConfig::extensions`, `ExtendedStatistics::extensions`,
67/// and other extension fields throughout DataFusion.
68pub type FileExtensions = datafusion_common::extensions::Extensions;
69
70/// Stream of files get listed from object store
71#[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/// A `[start, end)` byte range of a file. Non-overlapping ranges can be scanned
79/// in parallel. For Parquet, [`RowGroupRangeAssignment`] picks the row groups a
80/// range reads.
81///
82/// [`RowGroupRangeAssignment`]: datafusion_common::parquet_config::RowGroupRangeAssignment
83#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
84pub struct FileRange {
85    /// Range start
86    pub start: i64,
87    /// Range end
88    pub end: i64,
89}
90
91impl FileRange {
92    /// returns true if this file range contains the specified offset
93    pub fn contains(&self, offset: i64) -> bool {
94        offset >= self.start && offset < self.end
95    }
96}
97
98#[derive(Debug, Clone)]
99/// A single file or part of a file that should be read, along with its schema, statistics
100/// and partition column values that need to be appended to each row.
101///
102/// # Statistics
103///
104/// The [`Self::statistics`] field contains statistics for the **full table schema**,
105/// which includes both file columns and partition columns. When statistics are set via
106/// [`Self::with_statistics`], exact statistics for partition columns are automatically
107/// computed from [`Self::partition_values`]:
108///
109/// - `min = max = partition_value` (all rows in a file share the same partition value)
110/// - `null_count = 0` (every row has the file's partition value)
111/// - `distinct_count = 1` (single distinct value per file for each partition column)
112///
113/// A null partition value instead gives `null_count = num_rows`, `distinct_count = 0`
114/// and absent `min`/`max`.
115///
116/// This enables query optimizers to use partition column bounds for pruning and planning.
117pub struct PartitionedFile {
118    /// Path for the file (e.g. URL, filesystem path, etc)
119    pub object_meta: ObjectMeta,
120    /// Values of partition columns to be appended to each row.
121    ///
122    /// These MUST have the same count, order, and type than the [`table_partition_cols`].
123    ///
124    /// You may use [`wrap_partition_value_in_dict`] to wrap them if you have used [`wrap_partition_type_in_dict`] to wrap the column type.
125    ///
126    ///
127    /// [`wrap_partition_type_in_dict`]: crate::file_scan_config::wrap_partition_type_in_dict
128    /// [`wrap_partition_value_in_dict`]: crate::file_scan_config::wrap_partition_value_in_dict
129    /// [`table_partition_cols`]: https://github.com/apache/datafusion/blob/main/datafusion/core/src/datasource/file_format/options.rs#L87
130    pub partition_values: Vec<ScalarValue>,
131    /// An optional file range for a more fine-grained parallel execution
132    pub range: Option<FileRange>,
133    /// Optional statistics that describe the data in this file if known.
134    ///
135    /// DataFusion relies on these statistics for planning (in particular to sort file groups),
136    /// so if they are incorrect, incorrect answers may result.
137    ///
138    /// These statistics cover the full table schema: file columns plus partition columns.
139    /// When set via [`Self::with_statistics`], partition column statistics are automatically
140    /// computed from [`Self::partition_values`] with exact min/max/null_count/distinct_count.
141    pub statistics: Option<Arc<Statistics>>,
142    /// The known lexicographical ordering of the rows in this file, if any.
143    ///
144    /// This describes how the data within the file is sorted with respect to one or more
145    /// columns, and is used by the optimizer for planning operations that depend on input
146    /// ordering (e.g. merges, sorts, and certain aggregations).
147    ///
148    /// When available, this is typically inferred from file-level metadata exposed by the
149    /// underlying format (for example, Parquet `sorting_columns`), but it may also be set
150    /// explicitly via [`Self::with_ordering`].
151    pub ordering: Option<LexOrdering>,
152    /// User-defined per-file metadata, keyed by Rust type. Multiple
153    /// independent components can each attach their own data here without
154    /// conflict — see [`FileExtensions`].
155    pub extensions: FileExtensions,
156    /// The estimated size of the parquet metadata, in bytes
157    pub metadata_size_hint: Option<usize>,
158    pub table_reference: Option<TableReference>,
159    /// A user-provided physical Arrow schema for this file.
160    ///
161    /// This schema describes only the columns stored in the file. It must not
162    /// include partition columns; those are represented separately by
163    /// [`Self::partition_values`] and the scan's table partition columns.
164    ///
165    /// When provided, this field will be used by the Parquet reader to avoid
166    /// parsing the Arrow schema from the `ARROW:schema` metadata key. Other
167    /// built-in file sources ignore it for now.
168    pub arrow_schema: Option<SchemaRef>,
169}
170
171impl PartitionedFile {
172    /// Create a simple file without metadata or partition
173    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    /// Create a file from a known ObjectMeta without partition
194    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    /// Create a file range without metadata or partition
209    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    /// Provide a physical Arrow schema for this file.
231    ///
232    /// The schema must describe only columns stored in the file and must not
233    /// include partition columns. See [`Self::arrow_schema`] for details.
234    pub fn with_arrow_schema(mut self, schema: SchemaRef) -> Self {
235        self.arrow_schema = Some(schema);
236        self
237    }
238
239    /// Attach partition values to this file.
240    /// This replaces any existing partition values.
241    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    /// Size of the file to be scanned (taking into account the range, if present).
255    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    /// Effective range of the file to be scanned.
264    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    /// Provide a hint to the size of the file metadata. If a hint is provided
273    /// the reader will try and fetch the last `size_hint` bytes of the parquet file optimistically.
274    /// Without an appropriate hint, two read may be required to fetch the metadata.
275    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    /// Return a file reference from the given path
281    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    /// Return the path of this partitioned file
287    pub fn path(&self) -> &Path {
288        &self.object_meta.location
289    }
290
291    /// Update the file to only scan the specified range (in bytes)
292    pub fn with_range(mut self, start: i64, end: i64) -> Self {
293        self.range = Some(FileRange { start, end });
294        self
295    }
296
297    /// Attach a typed user-defined extension to this file. Multiple
298    /// independent extensions can be attached, each keyed by its concrete
299    /// Rust type. Inserting a value of a type that already has an extension
300    /// replaces the previous one.
301    ///
302    /// This can be used to pass reader-specific information (e.g. a
303    /// `ParquetAccessPlan`, or a custom index entry).
304    pub fn with_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
305        self.extensions.insert(value);
306        self
307    }
308
309    /// Borrow the extension of type `T`, if one is attached.
310    pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
311        self.extensions.get::<T>()
312    }
313
314    /// Attach a type-erased extension to this file.
315    ///
316    /// Kept as a backwards-compatible shim; prefer [`Self::with_extension`]
317    /// which keys the extension by its concrete Rust type at the call site.
318    #[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    /// Update the statistics for this file.
329    ///
330    /// The provided `statistics` should cover only the file schema columns.
331    /// This method will automatically append exact statistics for partition columns
332    /// based on `partition_values`:
333    /// - `min = max = partition_value` (all rows have the same value)
334    /// - `null_count = 0` (all rows have a non-null value)
335    /// - `distinct_count = 1` (all rows have the same partition value)
336    ///
337    /// A null partition value (e.g. a Hive default partition) instead gives
338    /// `null_count = num_rows`, `distinct_count = 0` and absent `min`/`max`.
339    pub fn with_statistics(mut self, file_statistics: Arc<Statistics>) -> Self {
340        if self.partition_values.is_empty() {
341            // No partition columns, use stats as-is
342            self.statistics = Some(file_statistics);
343        } else {
344            // Extend stats with exact partition column statistics
345            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    /// Check if this file has any statistics.
376    /// This returns `true` if the file has any Exact or Inexact statistics
377    /// and `false` if all statistics are `Precision::Absent`.
378    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    /// Set the known ordering of data in this file.
393    ///
394    /// The ordering represents the lexicographical sort order of the data,
395    /// typically inferred from file metadata (e.g., Parquet sorting_columns).
396    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/// Generates test files with min-max statistics in different overlap patterns.
419///
420/// # Overlap Factors
421///
422/// The `overlap_factor` parameter controls how much the value ranges in generated test files overlap:
423/// - `0.0`: No overlap between files (completely disjoint ranges)
424/// - `0.2`: Low overlap (20% of the range size overlaps with adjacent files)
425/// - `0.5`: Medium overlap (50% of ranges overlap)
426/// - `0.8`: High overlap (80% of ranges overlap between files)
427///
428/// # Examples
429///
430/// With 5 files and different overlap factors showing `[min, max]` ranges:
431///
432/// overlap_factor = 0.0 (no overlap):
433///
434/// File 0: [0, 20]
435/// File 1: [20, 40]
436/// File 2: [40, 60]
437/// File 3: [60, 80]
438/// File 4: [80, 100]
439///
440/// overlap_factor = 0.5 (50% overlap):
441///
442/// File 0: [0, 40]
443/// File 1: [20, 60]
444/// File 2: [40, 80]
445/// File 3: [60, 100]
446/// File 4: [80, 120]
447///
448/// overlap_factor = 0.8 (80% overlap):
449///
450/// File 0: [0, 100]
451/// File 1: [20, 120]
452/// File 2: [40, 140]
453/// File 3: [60, 160]
454/// File 4: [80, 180]
455///
456/// # Public Only for Internal Use:
457///
458/// This is not a public API and is for internal use only; see [API policy] for details.
459///
460/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
461#[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/// Verifies that files within each group maintain sort order.
513///
514/// # Public Only for Internal Use:
515///
516/// This is not a public API and is for internal use only; see [API policy] for details.
517///
518/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
519#[doc(hidden)]
520pub fn verify_sort_integrity(file_groups: &[FileGroup]) -> bool {
521    for group in file_groups {
522        // Known-empty files contribute no rows and may not have min/max
523        // statistics, so they cannot violate the ordering.
524        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            // Check if the min value of current file is greater than max value of previous file
533            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    /// Return a RecordBatch with a single Int32 array with values (0..sz) in a field named "i"
562    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    /// Get the schema for the aggregate_test_* csv files
573    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        // Create a PartitionedFile with partition values
645        let mut pf = PartitionedFile::new(
646            "test.parquet",
647            100, // file size
648        );
649        pf.partition_values = vec![
650            ScalarValue::Date32(Some(20148)), // 2025-03-01
651        ];
652
653        // Create file-only statistics (1 column for 'id')
654        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        // Call with_statistics - should append partition column stats
668        let pf = pf.with_statistics(file_stats);
669
670        // Verify the statistics now have 2 columns
671        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        // Verify partition column statistics
679        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        // standard case with default config
730        assert!(url.contains(
731            &Path::parse("/var/data/mytable/data.parquet").unwrap(),
732            true
733        ));
734
735        // standard case with `ignore_subdirectory` set to false
736        assert!(url.contains(
737            &Path::parse("/var/data/mytable/data.parquet").unwrap(),
738            false
739        ));
740
741        // as per documentation, when `ignore_subdirectory` is true, we should ignore files that aren't
742        // a direct child of the `url`
743        assert!(
744            url.contains(
745                &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
746                true
747            )
748            .not()
749        );
750
751        // when we set `ignore_subdirectory` to false, we should not ignore the file
752        assert!(url.contains(
753            &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
754            false
755        ));
756
757        // as above, `ignore_subdirectory` is false, so we include the file
758        assert!(url.contains(
759            &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
760            false
761        ));
762
763        // in this case, we include the file even when `ignore_subdirectory` is true because the
764        // path segment is a hive partition which doesn't count as a subdirectory for the purposes
765        // of `Url::contains`
766        assert!(url.contains(
767            &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
768            true
769        ));
770
771        // testing an empty path with default config
772        assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), true));
773
774        // testing an empty path with `ignore_subdirectory` set to false
775        assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), false));
776    }
777}