Skip to main content

datafusion_datasource/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#![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// Make sure fast / cheap clones on Arc are explicit:
24// https://github.com/apache/datafusion/issues/11143
25#![cfg_attr(not(test), deny(clippy::clone_on_ref_ptr))]
26#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
27
28//! A table that uses the `ObjectStore` listing capability
29//! to get the list of files to process.
30
31pub 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/// Protobuf conversions for [`FileRange`], [`PartitionedFile`] and
45/// [`FileGroup`](crate::file_groups::FileGroup), gated on the `proto` feature.
46#[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
76/// User-defined per-file extension data, keyed by concrete Rust type.
77///
78/// Re-exported from [`datafusion_common::extensions::Extensions`]; the same
79/// type backs `SessionConfig::extensions`, `ExtendedStatistics::extensions`,
80/// and other extension fields throughout DataFusion.
81pub type FileExtensions = datafusion_common::extensions::Extensions;
82
83/// Stream of files get listed from object store
84#[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/// Only scan a subset of Row Groups from the Parquet file whose data "midpoint"
92/// lies within the [start, end) byte offsets. This option can be used to scan non-overlapping
93/// sections of a Parquet file in parallel.
94#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
95pub struct FileRange {
96    /// Range start
97    pub start: i64,
98    /// Range end
99    pub end: i64,
100}
101
102impl FileRange {
103    /// returns true if this file range contains the specified offset
104    pub fn contains(&self, offset: i64) -> bool {
105        offset >= self.start && offset < self.end
106    }
107}
108
109#[derive(Debug, Clone)]
110/// A single file or part of a file that should be read, along with its schema, statistics
111/// and partition column values that need to be appended to each row.
112///
113/// # Statistics
114///
115/// The [`Self::statistics`] field contains statistics for the **full table schema**,
116/// which includes both file columns and partition columns. When statistics are set via
117/// [`Self::with_statistics`], exact statistics for partition columns are automatically
118/// computed from [`Self::partition_values`]:
119///
120/// - `min = max = partition_value` (all rows in a file share the same partition value)
121/// - `null_count = 0` (every row has the file's partition value)
122/// - `distinct_count = 1` (single distinct value per file for each partition column)
123///
124/// A null partition value instead gives `null_count = num_rows`, `distinct_count = 0`
125/// and absent `min`/`max`.
126///
127/// This enables query optimizers to use partition column bounds for pruning and planning.
128pub struct PartitionedFile {
129    /// Path for the file (e.g. URL, filesystem path, etc)
130    pub object_meta: ObjectMeta,
131    /// Values of partition columns to be appended to each row.
132    ///
133    /// These MUST have the same count, order, and type than the [`table_partition_cols`].
134    ///
135    /// 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.
136    ///
137    ///
138    /// [`wrap_partition_type_in_dict`]: crate::file_scan_config::wrap_partition_type_in_dict
139    /// [`wrap_partition_value_in_dict`]: crate::file_scan_config::wrap_partition_value_in_dict
140    /// [`table_partition_cols`]: https://github.com/apache/datafusion/blob/main/datafusion/core/src/datasource/file_format/options.rs#L87
141    pub partition_values: Vec<ScalarValue>,
142    /// An optional file range for a more fine-grained parallel execution
143    pub range: Option<FileRange>,
144    /// Optional statistics that describe the data in this file if known.
145    ///
146    /// DataFusion relies on these statistics for planning (in particular to sort file groups),
147    /// so if they are incorrect, incorrect answers may result.
148    ///
149    /// These statistics cover the full table schema: file columns plus partition columns.
150    /// When set via [`Self::with_statistics`], partition column statistics are automatically
151    /// computed from [`Self::partition_values`] with exact min/max/null_count/distinct_count.
152    pub statistics: Option<Arc<Statistics>>,
153    /// The known lexicographical ordering of the rows in this file, if any.
154    ///
155    /// This describes how the data within the file is sorted with respect to one or more
156    /// columns, and is used by the optimizer for planning operations that depend on input
157    /// ordering (e.g. merges, sorts, and certain aggregations).
158    ///
159    /// When available, this is typically inferred from file-level metadata exposed by the
160    /// underlying format (for example, Parquet `sorting_columns`), but it may also be set
161    /// explicitly via [`Self::with_ordering`].
162    pub ordering: Option<LexOrdering>,
163    /// User-defined per-file metadata, keyed by Rust type. Multiple
164    /// independent components can each attach their own data here without
165    /// conflict — see [`FileExtensions`].
166    pub extensions: FileExtensions,
167    /// The estimated size of the parquet metadata, in bytes
168    pub metadata_size_hint: Option<usize>,
169    pub table_reference: Option<TableReference>,
170    /// A user-provided physical Arrow schema for this file.
171    ///
172    /// This schema describes only the columns stored in the file. It must not
173    /// include partition columns; those are represented separately by
174    /// [`Self::partition_values`] and the scan's table partition columns.
175    ///
176    /// When provided, this field will be used by the Parquet reader to avoid
177    /// parsing the Arrow schema from the `ARROW:schema` metadata key. Other
178    /// built-in file sources ignore it for now.
179    pub arrow_schema: Option<SchemaRef>,
180}
181
182impl PartitionedFile {
183    /// Create a simple file without metadata or partition
184    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    /// Create a file from a known ObjectMeta without partition
205    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    /// Create a file range without metadata or partition
220    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    /// Provide a physical Arrow schema for this file.
242    ///
243    /// The schema must describe only columns stored in the file and must not
244    /// include partition columns. See [`Self::arrow_schema`] for details.
245    pub fn with_arrow_schema(mut self, schema: SchemaRef) -> Self {
246        self.arrow_schema = Some(schema);
247        self
248    }
249
250    /// Attach partition values to this file.
251    /// This replaces any existing partition values.
252    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    /// Size of the file to be scanned (taking into account the range, if present).
266    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    /// Effective range of the file to be scanned.
275    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    /// Provide a hint to the size of the file metadata. If a hint is provided
284    /// the reader will try and fetch the last `size_hint` bytes of the parquet file optimistically.
285    /// Without an appropriate hint, two read may be required to fetch the metadata.
286    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    /// Return a file reference from the given path
292    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    /// Return the path of this partitioned file
298    pub fn path(&self) -> &Path {
299        &self.object_meta.location
300    }
301
302    /// Update the file to only scan the specified range (in bytes)
303    pub fn with_range(mut self, start: i64, end: i64) -> Self {
304        self.range = Some(FileRange { start, end });
305        self
306    }
307
308    /// Attach a typed user-defined extension to this file. Multiple
309    /// independent extensions can be attached, each keyed by its concrete
310    /// Rust type. Inserting a value of a type that already has an extension
311    /// replaces the previous one.
312    ///
313    /// This can be used to pass reader-specific information (e.g. a
314    /// `ParquetAccessPlan`, or a custom index entry).
315    pub fn with_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
316        self.extensions.insert(value);
317        self
318    }
319
320    /// Borrow the extension of type `T`, if one is attached.
321    pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
322        self.extensions.get::<T>()
323    }
324
325    /// Attach a type-erased extension to this file.
326    ///
327    /// Kept as a backwards-compatible shim; prefer [`Self::with_extension`]
328    /// which keys the extension by its concrete Rust type at the call site.
329    #[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    /// Update the statistics for this file.
340    ///
341    /// The provided `statistics` should cover only the file schema columns.
342    /// This method will automatically append exact statistics for partition columns
343    /// based on `partition_values`:
344    /// - `min = max = partition_value` (all rows have the same value)
345    /// - `null_count = 0` (all rows have a non-null value)
346    /// - `distinct_count = 1` (all rows have the same partition value)
347    ///
348    /// A null partition value (e.g. a Hive default partition) instead gives
349    /// `null_count = num_rows`, `distinct_count = 0` and absent `min`/`max`.
350    pub fn with_statistics(mut self, file_statistics: Arc<Statistics>) -> Self {
351        if self.partition_values.is_empty() {
352            // No partition columns, use stats as-is
353            self.statistics = Some(file_statistics);
354        } else {
355            // Extend stats with exact partition column statistics
356            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    /// Check if this file has any statistics.
387    /// This returns `true` if the file has any Exact or Inexact statistics
388    /// and `false` if all statistics are `Precision::Absent`.
389    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    /// Set the known ordering of data in this file.
404    ///
405    /// The ordering represents the lexicographical sort order of the data,
406    /// typically inferred from file metadata (e.g., Parquet sorting_columns).
407    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
429/// Generates test files with min-max statistics in different overlap patterns.
430///
431/// Used by tests and benchmarks.
432///
433/// # Overlap Factors
434///
435/// The `overlap_factor` parameter controls how much the value ranges in generated test files overlap:
436/// - `0.0`: No overlap between files (completely disjoint ranges)
437/// - `0.2`: Low overlap (20% of the range size overlaps with adjacent files)
438/// - `0.5`: Medium overlap (50% of ranges overlap)
439/// - `0.8`: High overlap (80% of ranges overlap between files)
440///
441/// # Examples
442///
443/// With 5 files and different overlap factors showing `[min, max]` ranges:
444///
445/// overlap_factor = 0.0 (no overlap):
446///
447/// File 0: [0, 20]
448/// File 1: [20, 40]
449/// File 2: [40, 60]
450/// File 3: [60, 80]
451/// File 4: [80, 100]
452///
453/// overlap_factor = 0.5 (50% overlap):
454///
455/// File 0: [0, 40]
456/// File 1: [20, 60]
457/// File 2: [40, 80]
458/// File 3: [60, 100]
459/// File 4: [80, 120]
460///
461/// overlap_factor = 0.8 (80% overlap):
462///
463/// File 0: [0, 100]
464/// File 1: [20, 120]
465/// File 2: [40, 140]
466/// File 3: [60, 160]
467/// File 4: [80, 180]
468pub 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
518// Helper function to verify that files within each group maintain sort order
519/// Used by tests and benchmarks
520pub 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            // Check if the min value of current file is greater than max value of previous file
528            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    /// Return a RecordBatch with a single Int32 array with values (0..sz) in a field named "i"
557    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    /// Get the schema for the aggregate_test_* csv files
568    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        // Create a PartitionedFile with partition values
640        let mut pf = PartitionedFile::new(
641            "test.parquet",
642            100, // file size
643        );
644        pf.partition_values = vec![
645            ScalarValue::Date32(Some(20148)), // 2025-03-01
646        ];
647
648        // Create file-only statistics (1 column for 'id')
649        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        // Call with_statistics - should append partition column stats
663        let pf = pf.with_statistics(file_stats);
664
665        // Verify the statistics now have 2 columns
666        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        // Verify partition column statistics
674        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        // standard case with default config
725        assert!(url.contains(
726            &Path::parse("/var/data/mytable/data.parquet").unwrap(),
727            true
728        ));
729
730        // standard case with `ignore_subdirectory` set to false
731        assert!(url.contains(
732            &Path::parse("/var/data/mytable/data.parquet").unwrap(),
733            false
734        ));
735
736        // as per documentation, when `ignore_subdirectory` is true, we should ignore files that aren't
737        // a direct child of the `url`
738        assert!(
739            url.contains(
740                &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
741                true
742            )
743            .not()
744        );
745
746        // when we set `ignore_subdirectory` to false, we should not ignore the file
747        assert!(url.contains(
748            &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
749            false
750        ));
751
752        // as above, `ignore_subdirectory` is false, so we include the file
753        assert!(url.contains(
754            &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
755            false
756        ));
757
758        // in this case, we include the file even when `ignore_subdirectory` is true because the
759        // path segment is a hive partition which doesn't count as a subdirectory for the purposes
760        // of `Url::contains`
761        assert!(url.contains(
762            &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
763            true
764        ));
765
766        // testing an empty path with default config
767        assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), true));
768
769        // testing an empty path with `ignore_subdirectory` set to false
770        assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), false));
771    }
772}