datafusion_datasource/file.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//! Common behaviors that every file format needs to implement
6
7use std::any::Any;
8use std::fmt;
9use std::fmt::Formatter;
10use std::sync::Arc;
11
12use crate::file_groups::FileGroupPartitioner;
13use crate::file_scan_config::FileScanConfig;
14use crate::file_stream::FileOpener;
15use crate::morsel::{FileOpenerMorselizer, Morselizer};
16#[expect(deprecated)]
17use crate::schema_adapter::SchemaAdapterFactory;
18use datafusion_common::config::ConfigOptions;
19use datafusion_common::tree_node::TreeNodeRecursion;
20use datafusion_common::{Result, not_impl_err};
21use datafusion_physical_expr::projection::ProjectionExprs;
22use datafusion_physical_expr::{EquivalenceProperties, LexOrdering, PhysicalExpr};
23use datafusion_physical_plan::DisplayFormatType;
24use datafusion_physical_plan::SortOrderPushdownResult;
25use datafusion_physical_plan::filter_pushdown::{FilterPushdownPropagation, PushedDown};
26use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
27
28use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
29use object_store::ObjectStore;
30
31/// Helper function to convert any type implementing [`FileSource`] to `Arc<dyn FileSource>`
32pub fn as_file_source<T: FileSource + 'static>(source: T) -> Arc<dyn FileSource> {
33 Arc::new(source)
34}
35
36/// File format specific behaviors for [`DataSource`]
37///
38/// # Schema information
39/// There are two important schemas for a [`FileSource`]:
40/// 1. [`Self::table_schema`] -- the schema for the overall table
41/// (file data plus partition columns)
42/// 2. The logical output schema, comprised of [`Self::table_schema`] with
43/// [`Self::projection`] applied
44///
45/// See more details on specific implementations:
46/// * [`ArrowSource`](https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.ArrowSource.html)
47/// * [`AvroSource`](https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.AvroSource.html)
48/// * [`CsvSource`](https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.CsvSource.html)
49/// * [`JsonSource`](https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.JsonSource.html)
50/// * [`ParquetSource`](https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.ParquetSource.html)
51///
52/// [`DataSource`]: crate::source::DataSource
53pub trait FileSource: Any + Send + Sync {
54 /// Creates a `dyn FileOpener` based on given parameters.
55 ///
56 /// Note: File sources with a native morsel implementation should return an
57 /// error from this method and implementing [`Self::create_morselizer`] instead.
58 fn create_file_opener(
59 &self,
60 object_store: Arc<dyn ObjectStore>,
61 base_config: &FileScanConfig,
62 partition: usize,
63 ) -> Result<Arc<dyn FileOpener>>;
64
65 /// Creates a `dyn Morselizer` based on given parameters.
66 ///
67 /// The default implementation preserves existing behavior by adapting the
68 /// legacy [`FileOpener`] API into a [`Morselizer`].
69 ///
70 /// It is preferred to implement the [`Morselizer`] API directly by
71 /// implementing this method.
72 fn create_morselizer(
73 &self,
74 object_store: Arc<dyn ObjectStore>,
75 base_config: &FileScanConfig,
76 partition: usize,
77 ) -> Result<Box<dyn Morselizer>> {
78 let opener = self.create_file_opener(object_store, base_config, partition)?;
79 Ok(Box::new(FileOpenerMorselizer::new(opener)))
80 }
81
82 /// Returns the table schema for the overall table (including partition columns, if any)
83 ///
84 /// This method returns the unprojected schema: the full schema of the data
85 /// without [`Self::projection`] applied.
86 ///
87 /// The output schema of this `FileSource` is this TableSchema
88 /// with [`Self::projection`] applied.
89 ///
90 /// Use [`ProjectionExprs::project_schema`] to get the projected schema
91 /// after applying the projection.
92 fn table_schema(&self) -> &crate::table_schema::TableSchema;
93
94 /// Initialize new type with batch size configuration
95 fn with_batch_size(&self, batch_size: usize) -> Arc<dyn FileSource>;
96
97 /// Returns the filter expression that will be applied *during* the file scan.
98 ///
99 /// These expressions are in terms of the unprojected [`Self::table_schema`].
100 fn filter(&self) -> Option<Arc<dyn PhysicalExpr>> {
101 None
102 }
103
104 /// Returns the part of [`Self::filter`] that every output row is
105 /// guaranteed to satisfy.
106 ///
107 /// [`FileScanConfig`] derives equivalence properties (constants and equal
108 /// columns) from this filter. A filter that the source uses only to skip
109 /// data (for example, row group or page pruning with statistics) does not
110 /// remove every non-matching row, so it must not be returned here.
111 ///
112 /// Returns `None` by default.
113 ///
114 /// [`FileScanConfig`]: crate::file_scan_config::FileScanConfig
115 fn exact_filter(&self) -> Option<Arc<dyn PhysicalExpr>> {
116 None
117 }
118
119 /// Return the projection that will be applied to the output stream on top
120 /// of [`Self::table_schema`].
121 ///
122 /// Note you can use [`ProjectionExprs::project_schema`] on the table
123 /// schema to get the effective output schema of this source.
124 fn projection(&self) -> Option<&ProjectionExprs> {
125 None
126 }
127
128 /// Return execution plan metrics
129 fn metrics(&self) -> &ExecutionPlanMetricsSet;
130
131 /// String representation of file source such as "csv", "json", "parquet"
132 fn file_type(&self) -> &str;
133
134 /// Format FileType specific information
135 fn fmt_extra(&self, _t: DisplayFormatType, _f: &mut Formatter) -> fmt::Result {
136 Ok(())
137 }
138
139 /// Returns whether this file source supports repartitioning files by byte ranges.
140 ///
141 /// When this returns `true`, files can be split into multiple partitions
142 /// based on byte offsets for parallel reading.
143 ///
144 /// When this returns `false`, files cannot be repartitioned (e.g., CSV files
145 /// with `newlines_in_values` enabled cannot be split because record boundaries
146 /// cannot be determined by byte offset alone).
147 ///
148 /// The default implementation returns `true`. File sources that cannot support
149 /// repartitioning should override this method.
150 fn supports_repartitioning(&self) -> bool {
151 true
152 }
153
154 /// If supported by the [`FileSource`], redistribute files across partitions
155 /// according to their size. Allows custom file formats to implement their
156 /// own repartitioning logic.
157 ///
158 /// The default implementation uses [`FileGroupPartitioner`]. See that
159 /// struct for more details.
160 fn repartitioned(
161 &self,
162 target_partitions: usize,
163 repartition_file_min_size: usize,
164 output_ordering: Option<LexOrdering>,
165 config: &FileScanConfig,
166 ) -> Result<Option<FileScanConfig>> {
167 if config.file_compression_type.is_compressed() || !self.supports_repartitioning()
168 {
169 return Ok(None);
170 }
171
172 let repartitioned_file_groups_option = FileGroupPartitioner::new()
173 .with_target_partitions(target_partitions)
174 .with_repartition_file_min_size(repartition_file_min_size)
175 .with_preserve_order_within_groups(output_ordering.is_some())
176 .repartition_file_groups(&config.file_groups);
177
178 if let Some(repartitioned_file_groups) = repartitioned_file_groups_option {
179 let mut source = config.clone();
180 source.file_groups = repartitioned_file_groups;
181 return Ok(Some(source));
182 }
183 Ok(None)
184 }
185
186 /// Try to push down filters into this FileSource.
187 ///
188 /// `filters` must be in terms of the unprojected table schema (file schema
189 /// plus partition columns), before any projection is applied.
190 ///
191 /// Any filters that this FileSource chooses to evaluate itself should be
192 /// returned as `PushedDown::Yes` in the result, along with a FileSource
193 /// instance that incorporates those filters. Such filters are logically
194 /// applied "during" the file scan, meaning they may refer to columns not
195 /// included in the final output projection.
196 ///
197 /// Filters that cannot be pushed down should be marked as `PushedDown::No`,
198 /// and will be evaluated by an execution plan after the file source.
199 ///
200 /// See [`ExecutionPlan::handle_child_pushdown_result`] for more details.
201 ///
202 /// [`ExecutionPlan::handle_child_pushdown_result`]: datafusion_physical_plan::ExecutionPlan::handle_child_pushdown_result
203 fn try_pushdown_filters(
204 &self,
205 filters: Vec<Arc<dyn PhysicalExpr>>,
206 _config: &ConfigOptions,
207 ) -> Result<FilterPushdownPropagation<Arc<dyn FileSource>>> {
208 Ok(FilterPushdownPropagation::with_parent_pushdown_result(
209 vec![PushedDown::No; filters.len()],
210 ))
211 }
212
213 /// Try to create a new FileSource that can produce data in the specified sort order.
214 ///
215 /// This method attempts to optimize data retrieval to match the requested ordering.
216 /// It receives both the requested ordering and equivalence properties that describe
217 /// the output data from this file source.
218 ///
219 /// # Parameters
220 /// * `order` - The requested sort ordering from the query
221 /// * `eq_properties` - Equivalence properties of the data that will be produced by this
222 /// file source. These properties describe the ordering, constant columns, and other
223 /// relationships in the output data, allowing the implementation to determine if
224 /// optimizations like reversed scanning can help satisfy the requested ordering.
225 /// This includes information about:
226 /// - The file's natural ordering (from output_ordering in FileScanConfig)
227 /// - Constant columns (e.g., from filters like `ticker = 'AAPL'`)
228 /// - Monotonic functions (e.g., `extract_year_month(timestamp)`)
229 /// - Other equivalence relationships
230 ///
231 /// # Examples
232 ///
233 /// ## Example 1: Simple reverse
234 /// ```text
235 /// File ordering: [a ASC, b DESC]
236 /// Requested: [a DESC]
237 /// Reversed file: [a DESC, b ASC]
238 /// Result: Satisfies request (prefix match) → Inexact
239 /// ```
240 ///
241 /// ## Example 2: Monotonic function
242 /// ```text
243 /// File ordering: [extract_year_month(ts) ASC, ts ASC]
244 /// Requested: [ts DESC]
245 /// Reversed file: [extract_year_month(ts) DESC, ts DESC]
246 /// Result: Through monotonicity, satisfies [ts DESC] → Inexact
247 /// ```
248 ///
249 /// # Returns
250 /// * `Exact` - Created a source that guarantees perfect ordering
251 /// * `Inexact` - Created a source optimized for ordering (e.g., reversed row groups) but not perfectly sorted
252 /// * `Unsupported` - Cannot optimize for this ordering
253 ///
254 /// # Deprecation / migration notes
255 /// - [`Self::try_reverse_output`] was renamed to this method and deprecated since `53.0.0`.
256 /// Per DataFusion's deprecation guidelines, it will be removed in `59.0.0` or later
257 /// (6 major versions or 6 months, whichever is longer).
258 /// - New implementations should override [`Self::try_pushdown_sort`] directly.
259 /// - For backwards compatibility, the default implementation of
260 /// [`Self::try_pushdown_sort`] delegates to the deprecated
261 /// [`Self::try_reverse_output`] until it is removed. After that point, the
262 /// default implementation will return [`SortOrderPushdownResult::Unsupported`].
263 fn try_pushdown_sort(
264 &self,
265 order: &[PhysicalSortExpr],
266 eq_properties: &EquivalenceProperties,
267 ) -> Result<SortOrderPushdownResult<Arc<dyn FileSource>>> {
268 #[expect(deprecated)]
269 self.try_reverse_output(order, eq_properties)
270 }
271
272 /// Deprecated: Renamed to [`Self::try_pushdown_sort`].
273 #[deprecated(
274 since = "53.0.0",
275 note = "Renamed to try_pushdown_sort. This method was never limited to reversing output. It will be removed in 59.0.0 or later."
276 )]
277 fn try_reverse_output(
278 &self,
279 _order: &[PhysicalSortExpr],
280 _eq_properties: &EquivalenceProperties,
281 ) -> Result<SortOrderPushdownResult<Arc<dyn FileSource>>> {
282 Ok(SortOrderPushdownResult::Unsupported)
283 }
284
285 /// Reorder files in the shared work queue to optimize query performance.
286 ///
287 /// For example, TopK queries benefit from reading files with the best
288 /// statistics first, so the dynamic filter threshold tightens quickly.
289 ///
290 /// The default implementation returns files unchanged (no reordering).
291 fn reorder_files(
292 &self,
293 files: Vec<crate::PartitionedFile>,
294 ) -> Vec<crate::PartitionedFile> {
295 files
296 }
297
298 /// Try to push down a projection into this FileSource.
299 ///
300 /// `FileSource` implementations that support projection pushdown should
301 /// override this method and return a new `FileSource` instance with the
302 /// projection incorporated.
303 ///
304 /// If a `FileSource` does accept a projection it is expected to handle
305 /// the projection in it's entirety, including partition columns.
306 /// For example, the `FileSource` may translate that projection into a
307 /// file format specific projection (e.g. Parquet can push down struct field access,
308 /// some other file formats like Vortex can push down computed expressions into un-decoded data)
309 /// and also need to handle partition column projection (generally done by replacing partition column
310 /// references with literal values derived from each files partition values).
311 ///
312 /// Not all FileSource's can handle complex expression pushdowns. For example,
313 /// a CSV file source may only support simple column selections. In such cases,
314 /// the `FileSource` can use [`SplitProjection`] and [`ProjectionOpener`]
315 /// to split the projection into a pushdownable part and a non-pushdownable part.
316 /// These helpers also handle partition column projection.
317 ///
318 /// [`SplitProjection`]: crate::projection::SplitProjection
319 /// [`ProjectionOpener`]: crate::projection::ProjectionOpener
320 fn try_pushdown_projection(
321 &self,
322 _projection: &ProjectionExprs,
323 ) -> Result<Option<Arc<dyn FileSource>>> {
324 Ok(None)
325 }
326
327 /// Deprecated: Set optional schema adapter factory.
328 ///
329 /// `SchemaAdapterFactory` has been removed. Use `PhysicalExprAdapterFactory` instead.
330 /// See `upgrading.md` for more details.
331 #[deprecated(
332 since = "53.0.0",
333 note = "SchemaAdapterFactory has been removed. Use PhysicalExprAdapterFactory instead. See upgrading.md for more details."
334 )]
335 #[expect(deprecated)]
336 fn with_schema_adapter_factory(
337 &self,
338 _factory: Arc<dyn SchemaAdapterFactory>,
339 ) -> Result<Arc<dyn FileSource>> {
340 not_impl_err!(
341 "SchemaAdapterFactory has been removed. Use PhysicalExprAdapterFactory instead. See upgrading.md for more details."
342 )
343 }
344
345 /// Deprecated: Returns the current schema adapter factory if set.
346 ///
347 /// `SchemaAdapterFactory` has been removed. Use `PhysicalExprAdapterFactory` instead.
348 /// See `upgrading.md` for more details.
349 #[deprecated(
350 since = "53.0.0",
351 note = "SchemaAdapterFactory has been removed. Use PhysicalExprAdapterFactory instead. See upgrading.md for more details."
352 )]
353 #[expect(deprecated)]
354 fn schema_adapter_factory(&self) -> Option<Arc<dyn SchemaAdapterFactory>> {
355 None
356 }
357
358 /// Apply a function to all physical expressions used by this file source.
359 ///
360 /// This includes:
361 /// - Filter predicates (which may contain dynamic filters)
362 /// - Projection expressions
363 ///
364 /// The function `f` should be called once per expression unless the function returns
365 /// [`TreeNodeRecursion::Stop`] to stop iteration.
366 ///
367 /// See [`ExecutionPlan::apply_expressions`] for more details and implementation examples.
368 ///
369 /// [`ExecutionPlan::apply_expressions`]: datafusion_physical_plan::ExecutionPlan::apply_expressions
370 fn apply_expressions(
371 &self,
372 f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
373 ) -> Result<TreeNodeRecursion>;
374
375 /// Serialize this file source into a full [`PhysicalPlanNode`] (a
376 /// `DataSourceExec` wrapping the `FileScanConfig`), if it knows how.
377 ///
378 /// `base` is the shared [`FileScanConfig`] this source is wrapped in; the
379 /// format-agnostic parts (file groups, schema, statistics, ordering,
380 /// projection, …) are encoded via
381 /// [`FileScanConfig::try_to_proto`](crate::file_scan_config::FileScanConfig::try_to_proto),
382 /// and the concrete source appends its format-specific fields (e.g. CSV
383 /// delimiter/quote) around it.
384 ///
385 /// * `Ok(None)` (the default) — this source has no proto hook yet; the
386 /// caller falls back to the central downcast chain in `datafusion-proto`.
387 /// * `Ok(Some(node))` — fully serialized; the caller must not fall back.
388 ///
389 /// [`PhysicalPlanNode`]: datafusion_proto_models::protobuf::PhysicalPlanNode
390 /// [`FileScanConfig`]: crate::file_scan_config::FileScanConfig
391 #[cfg(feature = "proto")]
392 fn try_to_proto(
393 &self,
394 _base: &FileScanConfig,
395 _ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
396 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
397 Ok(None)
398 }
399}
400
401impl dyn FileSource {
402 /// Returns `true` if this source is of type `T`.
403 pub fn is<T: FileSource>(&self) -> bool {
404 (self as &dyn Any).is::<T>()
405 }
406
407 /// Attempts to downcast this source to a concrete type `T`.
408 pub fn downcast_ref<T: FileSource>(&self) -> Option<&T> {
409 (self as &dyn Any).downcast_ref()
410 }
411}