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 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// Remove when add_row_stats is remove
67#[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
75/// User-defined per-file extension data, keyed by concrete Rust type.
76///
77/// Re-exported from [`datafusion_common::extensions::Extensions`]; the same
78/// type backs `SessionConfig::extensions`, `ExtendedStatistics::extensions`,
79/// and other extension fields throughout DataFusion.
80pub type FileExtensions = datafusion_common::extensions::Extensions;
81
82/// Stream of files get listed from object store
83#[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/// Only scan a subset of Row Groups from the Parquet file whose data "midpoint"
91/// lies within the [start, end) byte offsets. This option can be used to scan non-overlapping
92/// sections of a Parquet file in parallel.
93#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
94pub struct FileRange {
95    /// Range start
96    pub start: i64,
97    /// Range end
98    pub end: i64,
99}
100
101impl FileRange {
102    /// returns true if this file range contains the specified offset
103    pub fn contains(&self, offset: i64) -> bool {
104        offset >= self.start && offset < self.end
105    }
106}
107
108#[derive(Debug, Clone)]
109/// A single file or part of a file that should be read, along with its schema, statistics
110/// and partition column values that need to be appended to each row.
111///
112/// # Statistics
113///
114/// The [`Self::statistics`] field contains statistics for the **full table schema**,
115/// which includes both file columns and partition columns. When statistics are set via
116/// [`Self::with_statistics`], exact statistics for partition columns are automatically
117/// computed from [`Self::partition_values`]:
118///
119/// - `min = max = partition_value` (all rows in a file share the same partition value)
120/// - `null_count = 0` (every row has the file's partition value)
121/// - `distinct_count = 1` (single distinct value per file for each partition column)
122///
123/// A null partition value instead gives `null_count = num_rows`, `distinct_count = 0`
124/// and absent `min`/`max`.
125///
126/// This enables query optimizers to use partition column bounds for pruning and planning.
127pub struct PartitionedFile {
128    /// Path for the file (e.g. URL, filesystem path, etc)
129    pub object_meta: ObjectMeta,
130    /// Values of partition columns to be appended to each row.
131    ///
132    /// These MUST have the same count, order, and type than the [`table_partition_cols`].
133    ///
134    /// 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.
135    ///
136    ///
137    /// [`wrap_partition_type_in_dict`]: crate::file_scan_config::wrap_partition_type_in_dict
138    /// [`wrap_partition_value_in_dict`]: crate::file_scan_config::wrap_partition_value_in_dict
139    /// [`table_partition_cols`]: https://github.com/apache/datafusion/blob/main/datafusion/core/src/datasource/file_format/options.rs#L87
140    pub partition_values: Vec<ScalarValue>,
141    /// An optional file range for a more fine-grained parallel execution
142    pub range: Option<FileRange>,
143    /// Optional statistics that describe the data in this file if known.
144    ///
145    /// DataFusion relies on these statistics for planning (in particular to sort file groups),
146    /// so if they are incorrect, incorrect answers may result.
147    ///
148    /// These statistics cover the full table schema: file columns plus partition columns.
149    /// When set via [`Self::with_statistics`], partition column statistics are automatically
150    /// computed from [`Self::partition_values`] with exact min/max/null_count/distinct_count.
151    pub statistics: Option<Arc<Statistics>>,
152    /// The known lexicographical ordering of the rows in this file, if any.
153    ///
154    /// This describes how the data within the file is sorted with respect to one or more
155    /// columns, and is used by the optimizer for planning operations that depend on input
156    /// ordering (e.g. merges, sorts, and certain aggregations).
157    ///
158    /// When available, this is typically inferred from file-level metadata exposed by the
159    /// underlying format (for example, Parquet `sorting_columns`), but it may also be set
160    /// explicitly via [`Self::with_ordering`].
161    pub ordering: Option<LexOrdering>,
162    /// User-defined per-file metadata, keyed by Rust type. Multiple
163    /// independent components can each attach their own data here without
164    /// conflict — see [`FileExtensions`].
165    pub extensions: FileExtensions,
166    /// The estimated size of the parquet metadata, in bytes
167    pub metadata_size_hint: Option<usize>,
168    pub table_reference: Option<TableReference>,
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            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    /// Create a file from a known ObjectMeta without partition
193    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    /// Create a file range without metadata or partition
207    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    /// Attach partition values to this file.
228    /// This replaces any existing partition values.
229    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    /// Size of the file to be scanned (taking into account the range, if present).
243    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    /// Effective range of the file to be scanned.
252    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    /// Provide a hint to the size of the file metadata. If a hint is provided
261    /// the reader will try and fetch the last `size_hint` bytes of the parquet file optimistically.
262    /// Without an appropriate hint, two read may be required to fetch the metadata.
263    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    /// Return a file reference from the given path
269    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    /// Return the path of this partitioned file
275    pub fn path(&self) -> &Path {
276        &self.object_meta.location
277    }
278
279    /// Update the file to only scan the specified range (in bytes)
280    pub fn with_range(mut self, start: i64, end: i64) -> Self {
281        self.range = Some(FileRange { start, end });
282        self
283    }
284
285    /// Attach a typed user-defined extension to this file. Multiple
286    /// independent extensions can be attached, each keyed by its concrete
287    /// Rust type. Inserting a value of a type that already has an extension
288    /// replaces the previous one.
289    ///
290    /// This can be used to pass reader-specific information (e.g. a
291    /// `ParquetAccessPlan`, or a custom index entry).
292    pub fn with_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
293        self.extensions.insert(value);
294        self
295    }
296
297    /// Borrow the extension of type `T`, if one is attached.
298    pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
299        self.extensions.get::<T>()
300    }
301
302    /// Attach a type-erased extension to this file.
303    ///
304    /// Kept as a backwards-compatible shim; prefer [`Self::with_extension`]
305    /// which keys the extension by its concrete Rust type at the call site.
306    #[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    /// Update the statistics for this file.
317    ///
318    /// The provided `statistics` should cover only the file schema columns.
319    /// This method will automatically append exact statistics for partition columns
320    /// based on `partition_values`:
321    /// - `min = max = partition_value` (all rows have the same value)
322    /// - `null_count = 0` (all rows have a non-null value)
323    /// - `distinct_count = 1` (all rows have the same partition value)
324    ///
325    /// A null partition value (e.g. a Hive default partition) instead gives
326    /// `null_count = num_rows`, `distinct_count = 0` and absent `min`/`max`.
327    pub fn with_statistics(mut self, file_statistics: Arc<Statistics>) -> Self {
328        if self.partition_values.is_empty() {
329            // No partition columns, use stats as-is
330            self.statistics = Some(file_statistics);
331        } else {
332            // Extend stats with exact partition column statistics
333            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    /// Check if this file has any statistics.
364    /// This returns `true` if the file has any Exact or Inexact statistics
365    /// and `false` if all statistics are `Precision::Absent`.
366    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    /// Set the known ordering of data in this file.
381    ///
382    /// The ordering represents the lexicographical sort order of the data,
383    /// typically inferred from file metadata (e.g., Parquet sorting_columns).
384    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
405/// Represents the possible outcomes of a range calculation.
406///
407/// This enum is used to encapsulate the result of calculating the range of
408/// bytes to read from an object (like a file) in an object store.
409///
410/// Variants:
411/// - `Range(Option<Range<usize>>)`:
412///   Represents a range of bytes to be read. It contains an `Option` wrapping a
413///   `Range<usize>`. `None` signifies that the entire object should be read,
414///   while `Some(range)` specifies the exact byte range to read.
415/// - `TerminateEarly`:
416///   Indicates that the range calculation determined no further action is
417///   necessary, possibly because the calculated range is empty or invalid.
418pub enum RangeCalculation {
419    Range(Option<Range<u64>>),
420    TerminateEarly,
421}
422
423/// Calculates an appropriate byte range for reading from an object based on the
424/// provided metadata.
425///
426/// This asynchronous function examines the [`PartitionedFile`] of an object in an object store
427/// and determines the range of bytes to be read. The range calculation may adjust
428/// the start and end points to align with meaningful data boundaries (like newlines).
429///
430/// Returns a `Result` wrapping a [`RangeCalculation`], which is either a calculated byte range or an indication to terminate early.
431///
432/// Returns an `Error` if any part of the range calculation fails, such as issues in reading from the object store or invalid range boundaries.
433pub 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
479/// Asynchronously finds the position of the first newline character in a specified byte range
480/// within an object, such as a file, in an object store.
481///
482/// This function scans the contents of the object starting from the specified `start` position
483/// up to the `end` position, looking for the first occurrence of a newline character.
484/// It returns the position of the first newline relative to the start of the range.
485///
486/// Returns a `Result` wrapping a `usize` that represents the position of the first newline character found within the specified range. If no newline is found, it returns the length of the scanned data, effectively indicating the end of the range.
487///
488/// The function returns an `Error` if any issues arise while reading from the object store or processing the data stream.
489async 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
518/// Generates test files with min-max statistics in different overlap patterns.
519///
520/// Used by tests and benchmarks.
521///
522/// # Overlap Factors
523///
524/// The `overlap_factor` parameter controls how much the value ranges in generated test files overlap:
525/// - `0.0`: No overlap between files (completely disjoint ranges)
526/// - `0.2`: Low overlap (20% of the range size overlaps with adjacent files)
527/// - `0.5`: Medium overlap (50% of ranges overlap)
528/// - `0.8`: High overlap (80% of ranges overlap between files)
529///
530/// # Examples
531///
532/// With 5 files and different overlap factors showing `[min, max]` ranges:
533///
534/// overlap_factor = 0.0 (no overlap):
535///
536/// File 0: [0, 20]
537/// File 1: [20, 40]
538/// File 2: [40, 60]
539/// File 3: [60, 80]
540/// File 4: [80, 100]
541///
542/// overlap_factor = 0.5 (50% overlap):
543///
544/// File 0: [0, 40]
545/// File 1: [20, 60]
546/// File 2: [40, 80]
547/// File 3: [60, 100]
548/// File 4: [80, 120]
549///
550/// overlap_factor = 0.8 (80% overlap):
551///
552/// File 0: [0, 100]
553/// File 1: [20, 120]
554/// File 2: [40, 140]
555/// File 3: [60, 160]
556/// File 4: [80, 180]
557pub 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
606// Helper function to verify that files within each group maintain sort order
607/// Used by tests and benchmarks
608pub 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            // Check if the min value of current file is greater than max value of previous file
616            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    /// Return a RecordBatch with a single Int32 array with values (0..sz) in a field named "i"
645    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    /// Get the schema for the aggregate_test_* csv files
656    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        // Create a PartitionedFile with partition values
728        let mut pf = PartitionedFile::new(
729            "test.parquet",
730            100, // file size
731        );
732        pf.partition_values = vec![
733            ScalarValue::Date32(Some(20148)), // 2025-03-01
734        ];
735
736        // Create file-only statistics (1 column for 'id')
737        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        // Call with_statistics - should append partition column stats
751        let pf = pf.with_statistics(file_stats);
752
753        // Verify the statistics now have 2 columns
754        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        // Verify partition column statistics
762        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        // standard case with default config
813        assert!(url.contains(
814            &Path::parse("/var/data/mytable/data.parquet").unwrap(),
815            true
816        ));
817
818        // standard case with `ignore_subdirectory` set to false
819        assert!(url.contains(
820            &Path::parse("/var/data/mytable/data.parquet").unwrap(),
821            false
822        ));
823
824        // as per documentation, when `ignore_subdirectory` is true, we should ignore files that aren't
825        // a direct child of the `url`
826        assert!(
827            url.contains(
828                &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
829                true
830            )
831            .not()
832        );
833
834        // when we set `ignore_subdirectory` to false, we should not ignore the file
835        assert!(url.contains(
836            &Path::parse("/var/data/mytable/mysubfolder/data.parquet").unwrap(),
837            false
838        ));
839
840        // as above, `ignore_subdirectory` is false, so we include the file
841        assert!(url.contains(
842            &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
843            false
844        ));
845
846        // in this case, we include the file even when `ignore_subdirectory` is true because the
847        // path segment is a hive partition which doesn't count as a subdirectory for the purposes
848        // of `Url::contains`
849        assert!(url.contains(
850            &Path::parse("/var/data/mytable/year=2024/data.parquet").unwrap(),
851            true
852        ));
853
854        // testing an empty path with default config
855        assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), true));
856
857        // testing an empty path with `ignore_subdirectory` set to false
858        assert!(url.contains(&Path::parse("/var/data/mytable/").unwrap(), false));
859    }
860
861    /// Regression test for <https://github.com/apache/datafusion/issues/19605>
862    #[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}