Skip to main content

datafusion_datasource/
file_format.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//! Module containing helper methods for the various file formats
6//! See write.rs for write related helper methods
7
8use std::any::Any;
9use std::collections::{HashMap, HashSet};
10use std::fmt;
11use std::sync::Arc;
12
13use crate::file::FileSource;
14use crate::file_compression_type::FileCompressionType;
15use crate::file_scan_config::FileScanConfig;
16use crate::file_sink_config::FileSinkConfig;
17
18use arrow::datatypes::{Schema, SchemaRef};
19use datafusion_common::file_options::file_type::FileType;
20use datafusion_common::{
21    GetExt, Result, SchemaError, Statistics, internal_err, not_impl_err, schema_err,
22};
23use datafusion_physical_expr::LexRequirement;
24use datafusion_physical_expr_common::sort_expr::LexOrdering;
25use datafusion_physical_plan::ExecutionPlan;
26use datafusion_session::Session;
27
28use async_trait::async_trait;
29use object_store::{ObjectMeta, ObjectStore};
30
31/// Default max records to scan to infer the schema
32pub const DEFAULT_SCHEMA_INFER_MAX_RECORD: usize = 1000;
33
34/// Rejects an inferred schema that names the same field more than once.
35///
36/// [`Schema::try_merge`] coalesces fields by name, so callers validate each
37/// inferred file schema before merging. `seen` is cleared before use so callers
38/// can reuse its allocation across schemas.
39pub fn ensure_unique_field_names<'a>(
40    schema: &'a Schema,
41    seen: &mut HashSet<&'a str>,
42) -> Result<()> {
43    seen.clear();
44    seen.reserve(schema.fields().len());
45    for field in schema.fields() {
46        if !seen.insert(field.name()) {
47            return schema_err!(SchemaError::DuplicateUnqualifiedField {
48                name: field.name().clone(),
49            });
50        }
51    }
52    Ok(())
53}
54
55/// Metadata fetched from a file, including statistics and ordering.
56///
57/// This struct is returned by [`FileFormat::infer_stats_and_ordering`] to
58/// provide all metadata in a single read, avoiding duplicate I/O operations.
59#[derive(Debug, Clone)]
60#[non_exhaustive]
61pub struct FileMeta {
62    /// Statistics for the file (row counts, byte sizes, column statistics).
63    pub statistics: Statistics,
64    /// The ordering (sort order) of the file, if known.
65    pub ordering: Option<LexOrdering>,
66}
67
68impl FileMeta {
69    /// Creates a new `FileMeta` with the given statistics and no ordering.
70    pub fn new(statistics: Statistics) -> Self {
71        Self {
72            statistics,
73            ordering: None,
74        }
75    }
76
77    /// Sets the ordering for this file metadata.
78    pub fn with_ordering(mut self, ordering: Option<LexOrdering>) -> Self {
79        self.ordering = ordering;
80        self
81    }
82}
83
84/// This trait abstracts all the file format specific implementations
85/// from the [`TableProvider`]. This helps code re-utilization across
86/// providers that support the same file formats.
87///
88/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/catalog/trait.TableProvider.html
89#[async_trait]
90pub trait FileFormat: Any + Send + Sync + fmt::Debug {
91    /// Returns the extension for this FileFormat, e.g. "file.csv" -> csv
92    fn get_ext(&self) -> String;
93
94    /// Returns the extension for this FileFormat when compressed, e.g. "file.csv.gz" -> csv
95    fn get_ext_with_compression(
96        &self,
97        _file_compression_type: &FileCompressionType,
98    ) -> Result<String>;
99
100    /// Returns whether this instance uses compression if applicable
101    fn compression_type(&self) -> Option<FileCompressionType>;
102
103    /// Infer the common schema of the provided objects. The objects will usually
104    /// be analysed up to a given number of records or files (as specified in the
105    /// format config) then give the estimated common schema. This might fail if
106    /// the files have schemas that cannot be merged.
107    async fn infer_schema(
108        &self,
109        state: &dyn Session,
110        store: &Arc<dyn ObjectStore>,
111        objects: &[ObjectMeta],
112    ) -> Result<SchemaRef>;
113
114    /// Infer the statistics for the provided object. The cost and accuracy of the
115    /// estimated statistics might vary greatly between file formats.
116    ///
117    /// `table_schema` is the (combined) schema of the overall table
118    /// and may be a superset of the schema contained in this file.
119    ///
120    /// TODO: should the file source return statistics for only columns referred to in the table schema?
121    async fn infer_stats(
122        &self,
123        state: &dyn Session,
124        store: &Arc<dyn ObjectStore>,
125        table_schema: SchemaRef,
126        object: &ObjectMeta,
127    ) -> Result<Statistics>;
128
129    /// Infer the ordering (sort order) for the provided object from file metadata.
130    ///
131    /// Returns `Ok(None)` if the file format does not support ordering inference
132    /// or if the file does not have ordering information.
133    ///
134    /// `table_schema` is the (combined) schema of the overall table
135    /// and may be a superset of the schema contained in this file.
136    ///
137    /// The default implementation returns `Ok(None)`.
138    async fn infer_ordering(
139        &self,
140        _state: &dyn Session,
141        _store: &Arc<dyn ObjectStore>,
142        _table_schema: SchemaRef,
143        _object: &ObjectMeta,
144    ) -> Result<Option<LexOrdering>> {
145        Ok(None)
146    }
147
148    /// Infer both statistics and ordering from a single metadata read.
149    ///
150    /// This is more efficient than calling [`Self::infer_stats`] and
151    /// [`Self::infer_ordering`] separately when both are needed, as it avoids
152    /// reading file metadata twice.
153    ///
154    /// The default implementation calls both methods separately. File formats
155    /// that can extract both from a single read should override this method.
156    async fn infer_stats_and_ordering(
157        &self,
158        state: &dyn Session,
159        store: &Arc<dyn ObjectStore>,
160        table_schema: SchemaRef,
161        object: &ObjectMeta,
162    ) -> Result<FileMeta> {
163        let statistics = self
164            .infer_stats(state, store, Arc::clone(&table_schema), object)
165            .await?;
166        let ordering = self
167            .infer_ordering(state, store, table_schema, object)
168            .await?;
169        Ok(FileMeta {
170            statistics,
171            ordering,
172        })
173    }
174
175    /// Take a list of files and convert it to the appropriate executor
176    /// according to this file format.
177    async fn create_physical_plan(
178        &self,
179        state: &dyn Session,
180        conf: FileScanConfig,
181    ) -> Result<Arc<dyn ExecutionPlan>>;
182
183    /// Take a list of files and the configuration to convert it to the
184    /// appropriate writer executor according to this file format.
185    async fn create_writer_physical_plan(
186        &self,
187        _input: Arc<dyn ExecutionPlan>,
188        _state: &dyn Session,
189        _conf: FileSinkConfig,
190        _order_requirements: Option<LexRequirement>,
191    ) -> Result<Arc<dyn ExecutionPlan>> {
192        not_impl_err!("Writer not implemented for this format")
193    }
194
195    /// Return the related FileSource such as `CsvSource`, `JsonSource`, etc.
196    ///
197    /// # Arguments
198    /// * `table_schema` - The table schema to use for the FileSource (includes partition columns)
199    fn file_source(&self, table_schema: crate::TableSchema) -> Arc<dyn FileSource>;
200}
201
202impl dyn FileFormat {
203    pub fn is<T: FileFormat>(&self) -> bool {
204        (self as &dyn Any).is::<T>()
205    }
206
207    pub fn downcast_ref<T: FileFormat>(&self) -> Option<&T> {
208        (self as &dyn Any).downcast_ref()
209    }
210}
211
212/// Factory for creating [`FileFormat`] instances based on session and command level options
213///
214/// Users can provide their own `FileFormatFactory` to support arbitrary file formats
215pub trait FileFormatFactory: Any + Sync + Send + GetExt + fmt::Debug {
216    /// Initialize a [FileFormat] and configure based on session and command level options
217    fn create(
218        &self,
219        state: &dyn Session,
220        format_options: &HashMap<String, String>,
221    ) -> Result<Arc<dyn FileFormat>>;
222
223    /// Initialize a [FileFormat] with all options set to default values
224    fn default(&self) -> Arc<dyn FileFormat>;
225}
226
227impl dyn FileFormatFactory {
228    pub fn is<T: FileFormatFactory>(&self) -> bool {
229        (self as &dyn Any).is::<T>()
230    }
231
232    pub fn downcast_ref<T: FileFormatFactory>(&self) -> Option<&T> {
233        (self as &dyn Any).downcast_ref()
234    }
235}
236
237/// A container of [FileFormatFactory] which also implements [FileType].
238/// This enables converting a dyn FileFormat to a dyn FileType.
239/// The former trait is a superset of the latter trait, which includes execution time
240/// relevant methods. [FileType] is only used in logical planning and only implements
241/// the subset of methods required during logical planning.
242#[derive(Debug)]
243pub struct DefaultFileType {
244    file_format_factory: Arc<dyn FileFormatFactory>,
245}
246
247impl DefaultFileType {
248    /// Constructs a [DefaultFileType] wrapper from a [FileFormatFactory]
249    pub fn new(file_format_factory: Arc<dyn FileFormatFactory>) -> Self {
250        Self {
251            file_format_factory,
252        }
253    }
254
255    /// get a reference to the inner [FileFormatFactory] struct
256    pub fn as_format_factory(&self) -> &Arc<dyn FileFormatFactory> {
257        &self.file_format_factory
258    }
259}
260
261impl FileType for DefaultFileType {
262    fn as_any(&self) -> &dyn Any {
263        self
264    }
265}
266
267impl fmt::Display for DefaultFileType {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        write!(f, "{:?}", self.file_format_factory)
270    }
271}
272
273impl GetExt for DefaultFileType {
274    fn get_ext(&self) -> String {
275        self.file_format_factory.get_ext()
276    }
277}
278
279/// Converts a [FileFormatFactory] to a [FileType]
280pub fn format_as_file_type(
281    file_format_factory: Arc<dyn FileFormatFactory>,
282) -> Arc<dyn FileType> {
283    Arc::new(DefaultFileType {
284        file_format_factory,
285    })
286}
287
288/// Converts a [FileType] to a [FileFormatFactory].
289/// Returns an error if the [FileType] cannot be
290/// downcasted to a [DefaultFileType].
291pub fn file_type_to_format(
292    file_type: &Arc<dyn FileType>,
293) -> Result<Arc<dyn FileFormatFactory>> {
294    match file_type
295        .as_ref()
296        .as_any()
297        .downcast_ref::<DefaultFileType>()
298    {
299        Some(source) => Ok(Arc::clone(&source.file_format_factory)),
300        _ => internal_err!("FileType was not DefaultFileType"),
301    }
302}