datafusion_datasource/
file.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//! Common behaviors that every file format needs to implement
19
20use std::any::Any;
21use std::fmt;
22use std::fmt::Formatter;
23use std::sync::Arc;
24
25use crate::file_groups::FileGroupPartitioner;
26use crate::file_scan_config::FileScanConfig;
27use crate::file_stream::FileOpener;
28use arrow::datatypes::SchemaRef;
29use datafusion_common::Statistics;
30use datafusion_physical_expr::LexOrdering;
31use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
32use datafusion_physical_plan::DisplayFormatType;
33
34use object_store::ObjectStore;
35
36/// Common file format behaviors needs to implement.
37///
38/// See implementation examples such as `ParquetSource`, `CsvSource`
39pub trait FileSource: Send + Sync {
40    /// Creates a `dyn FileOpener` based on given parameters
41    fn create_file_opener(
42        &self,
43        object_store: Arc<dyn ObjectStore>,
44        base_config: &FileScanConfig,
45        partition: usize,
46    ) -> Arc<dyn FileOpener>;
47    /// Any
48    fn as_any(&self) -> &dyn Any;
49    /// Initialize new type with batch size configuration
50    fn with_batch_size(&self, batch_size: usize) -> Arc<dyn FileSource>;
51    /// Initialize new instance with a new schema
52    fn with_schema(&self, schema: SchemaRef) -> Arc<dyn FileSource>;
53    /// Initialize new instance with projection information
54    fn with_projection(&self, config: &FileScanConfig) -> Arc<dyn FileSource>;
55    /// Initialize new instance with projected statistics
56    fn with_statistics(&self, statistics: Statistics) -> Arc<dyn FileSource>;
57    /// Return execution plan metrics
58    fn metrics(&self) -> &ExecutionPlanMetricsSet;
59    /// Return projected statistics
60    fn statistics(&self) -> datafusion_common::Result<Statistics>;
61    /// String representation of file source such as "csv", "json", "parquet"
62    fn file_type(&self) -> &str;
63    /// Format FileType specific information
64    fn fmt_extra(&self, _t: DisplayFormatType, _f: &mut Formatter) -> fmt::Result {
65        Ok(())
66    }
67
68    /// If supported by the [`FileSource`], redistribute files across partitions according to their size.
69    /// Allows custom file formats to implement their own repartitioning logic.
70    ///
71    /// Provides a default repartitioning behavior, see comments on [`FileGroupPartitioner`] for more detail.
72    fn repartitioned(
73        &self,
74        target_partitions: usize,
75        repartition_file_min_size: usize,
76        output_ordering: Option<LexOrdering>,
77        config: &FileScanConfig,
78    ) -> datafusion_common::Result<Option<FileScanConfig>> {
79        if config.file_compression_type.is_compressed() || config.new_lines_in_values {
80            return Ok(None);
81        }
82
83        let repartitioned_file_groups_option = FileGroupPartitioner::new()
84            .with_target_partitions(target_partitions)
85            .with_repartition_file_min_size(repartition_file_min_size)
86            .with_preserve_order_within_groups(output_ordering.is_some())
87            .repartition_file_groups(&config.file_groups);
88
89        if let Some(repartitioned_file_groups) = repartitioned_file_groups_option {
90            let mut source = config.clone();
91            source.file_groups = repartitioned_file_groups;
92            return Ok(Some(source));
93        }
94        Ok(None)
95    }
96}