datafusion_datasource/source.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//! [`DataSource`] and [`DataSourceExec`]
6
7use std::any::Any;
8use std::fmt;
9use std::fmt::{Debug, Formatter};
10use std::sync::{Arc, OnceLock};
11
12use datafusion_physical_expr::projection::ProjectionExprs;
13use datafusion_physical_plan::execution_plan::{
14 Boundedness, EmissionType, SchedulingType,
15};
16use datafusion_physical_plan::metrics::SplitMetrics;
17use datafusion_physical_plan::metrics::{
18 BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet,
19};
20use datafusion_physical_plan::projection::ProjectionExec;
21use datafusion_physical_plan::stream::BatchSplitStream;
22use datafusion_physical_plan::{
23 ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
24 ReplaceChildrenOptions,
25};
26use itertools::Itertools;
27
28use crate::file::FileSource;
29use crate::file_scan_config::FileScanConfig;
30use datafusion_common::config::ConfigOptions;
31use datafusion_common::tree_node::TreeNodeRecursion;
32use datafusion_common::{Constraints, Result, Statistics};
33use datafusion_execution::{SendableRecordBatchStream, TaskContext};
34use datafusion_physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr};
35use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
36use datafusion_physical_plan::SortOrderPushdownResult;
37use datafusion_physical_plan::StatisticsArgs;
38use datafusion_physical_plan::filter_pushdown::{
39 ChildPushdownResult, FilterPushdownPhase, FilterPushdownPropagation, PushedDown,
40};
41
42/// A source of data, typically a list of files or memory
43///
44/// This trait provides common behaviors for abstract sources of data. It has
45/// two common implementations:
46///
47/// 1. [`FileScanConfig`]: lists of files
48/// 2. [`MemorySourceConfig`]: in memory list of `RecordBatch`
49///
50/// File format specific behaviors are defined by [`FileSource`]
51///
52/// # See Also
53/// * [`FileSource`] for file format specific implementations (Parquet, Json, etc)
54/// * [`DataSourceExec`]: The [`ExecutionPlan`] that reads from a `DataSource`
55///
56/// # Notes
57///
58/// Requires `Debug` to assist debugging
59///
60/// [`FileScanConfig`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.FileScanConfig.html
61/// [`MemorySourceConfig`]: https://docs.rs/datafusion/latest/datafusion/datasource/memory/struct.MemorySourceConfig.html
62/// [`FileSource`]: crate::file::FileSource
63/// [`FileFormat``]: https://docs.rs/datafusion/latest/datafusion/datasource/file_format/index.html
64/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/catalog/trait.TableProvider.html
65///
66/// The following diagram shows how DataSource, FileSource, and DataSourceExec are related
67/// ```text
68/// ┌─────────────────────┐ -----► execute path
69/// │ │ ┄┄┄┄┄► init path
70/// │ DataSourceExec │
71/// │ │
72/// └───────▲─────────────┘
73/// ┊ │
74/// ┊ │
75/// ┌──────────▼──────────┐ ┌──────────-──────────┐
76/// │ │ | |
77/// │ DataSource(trait) │ | TableProvider(trait)|
78/// │ │ | |
79/// └───────▲─────────────┘ └─────────────────────┘
80/// ┊ │ ┊
81/// ┌───────────────┿──┴────────────────┐ ┊
82/// | ┌┄┄┄┄┄┄┄┄┄┄┄┘ | ┊
83/// | ┊ | ┊
84/// ┌──────────▼──────────┐ ┌──────────▼──────────┐ ┊
85/// │ │ │ │ ┌──────────▼──────────┐
86/// │ FileScanConfig │ │ MemorySourceConfig │ | |
87/// │ │ │ │ | FileFormat(trait) |
88/// └──────────────▲──────┘ └─────────────────────┘ | |
89/// │ ┊ └─────────────────────┘
90/// │ ┊ ┊
91/// │ ┊ ┊
92/// ┌──────────▼──────────┐ ┌──────────▼──────────┐
93/// │ │ │ ArrowSource │
94/// │ FileSource(trait) ◄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄│ ... │
95/// │ │ │ ParquetSource │
96/// └─────────────────────┘ └─────────────────────┘
97/// │
98/// │
99/// │
100/// │
101/// ┌──────────▼──────────┐
102/// │ ArrowSource │
103/// │ ... │
104/// │ ParquetSource │
105/// └─────────────────────┘
106/// |
107/// FileOpener (called by FileStream)
108/// │
109/// ┌──────────▼──────────┐
110/// │ │
111/// │ RecordBatch │
112/// │ │
113/// └─────────────────────┘
114/// ```
115pub trait DataSource: Any + Send + Sync + Debug {
116 /// Open the specified output partition and return its stream of
117 /// [`RecordBatch`]es.
118 ///
119 /// This should be used by data sources that do not need any sibling
120 /// coordination. Data sources that want to use per-execution shared state
121 /// (for example, to reorder work across partitions at runtime) should
122 /// implement [`Self::open_with_args`] instead.
123 ///
124 /// [`RecordBatch`]: arrow::record_batch::RecordBatch
125 fn open(
126 &self,
127 partition: usize,
128 context: Arc<TaskContext>,
129 ) -> Result<SendableRecordBatchStream>;
130
131 /// Format this source for display in explain plans
132 fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> fmt::Result;
133
134 /// Return a copy of this DataSource with a new partitioning scheme.
135 ///
136 /// Returns `Ok(None)` (the default) if the partitioning cannot be changed.
137 /// Refer to [`ExecutionPlan::repartitioned`] for details on when None should be returned.
138 ///
139 /// Repartitioning should not change the output ordering, if this ordering exists.
140 /// Refer to [`MemorySourceConfig::repartition_preserving_order`](crate::memory::MemorySourceConfig)
141 /// and the FileSource's
142 /// [`FileGroupPartitioner::repartition_file_groups`](crate::file_groups::FileGroupPartitioner::repartition_file_groups)
143 /// for examples.
144 fn repartitioned(
145 &self,
146 _target_partitions: usize,
147 _repartition_file_min_size: usize,
148 _output_ordering: Option<LexOrdering>,
149 ) -> Result<Option<Arc<dyn DataSource>>> {
150 Ok(None)
151 }
152
153 fn output_partitioning(&self) -> Partitioning;
154 fn eq_properties(&self) -> EquivalenceProperties;
155 fn scheduling_type(&self) -> SchedulingType {
156 SchedulingType::NonCooperative
157 }
158
159 /// Returns statistics for a specific partition, or aggregate statistics
160 /// across all partitions if `partition` is `None`.
161 fn partition_statistics(&self, partition: Option<usize>) -> Result<Arc<Statistics>>;
162
163 /// Return a copy of this DataSource with a new fetch limit
164 fn with_fetch(&self, _limit: Option<usize>) -> Option<Arc<dyn DataSource>>;
165 fn fetch(&self) -> Option<usize>;
166 fn metrics(&self) -> ExecutionPlanMetricsSet {
167 ExecutionPlanMetricsSet::new()
168 }
169 fn try_swapping_with_projection(
170 &self,
171 _projection: &ProjectionExprs,
172 ) -> Result<Option<Arc<dyn DataSource>>>;
173
174 /// Try to push down filters into this DataSource.
175 ///
176 /// These filters are in terms of the output schema of this DataSource (e.g.
177 /// [`Self::eq_properties`] and output of any projections pushed into the
178 /// source), not the original table schema.
179 ///
180 /// See [`ExecutionPlan::handle_child_pushdown_result`] for more details.
181 ///
182 /// [`ExecutionPlan::handle_child_pushdown_result`]: datafusion_physical_plan::ExecutionPlan::handle_child_pushdown_result
183 fn try_pushdown_filters(
184 &self,
185 filters: Vec<Arc<dyn PhysicalExpr>>,
186 _config: &ConfigOptions,
187 ) -> Result<FilterPushdownPropagation<Arc<dyn DataSource>>> {
188 Ok(FilterPushdownPropagation::with_parent_pushdown_result(
189 vec![PushedDown::No; filters.len()],
190 ))
191 }
192
193 /// Try to create a new DataSource that produces data in the specified sort order.
194 ///
195 /// # Arguments
196 /// * `order` - The desired output ordering
197 ///
198 /// # Returns
199 /// * `Ok(SortOrderPushdownResult::Exact { .. })` - Created a source that guarantees exact ordering
200 /// * `Ok(SortOrderPushdownResult::Inexact { .. })` - Created a source optimized for the ordering
201 /// * `Ok(SortOrderPushdownResult::Unsupported)` - Cannot optimize for this ordering
202 /// * `Err(e)` - Error occurred
203 ///
204 /// Default implementation returns `Unsupported`.
205 fn try_pushdown_sort(
206 &self,
207 _order: &[PhysicalSortExpr],
208 ) -> Result<SortOrderPushdownResult<Arc<dyn DataSource>>> {
209 Ok(SortOrderPushdownResult::Unsupported)
210 }
211
212 /// Returns a variant of this `DataSource` that is aware of order-sensitivity.
213 #[deprecated(
214 since = "56.0.0",
215 note = "no longer called: a scan that advertises an output ordering always preserves it"
216 )]
217 fn with_preserve_order(&self, _preserve_order: bool) -> Option<Arc<dyn DataSource>> {
218 None
219 }
220
221 /// Apply a closure to each expression used by this data source.
222 ///
223 /// This includes filter predicates (which may contain dynamic filters) and any
224 /// other expressions used during data scanning.
225 ///
226 /// The function `f` should be called once per expression unless the function returns
227 /// [`TreeNodeRecursion::Stop`] to stop iteration.
228 ///
229 /// See [`ExecutionPlan::apply_expressions`] for more details and implementation examples.
230 ///
231 /// [`ExecutionPlan::apply_expressions`]: datafusion_physical_plan::ExecutionPlan::apply_expressions
232 fn apply_expressions(
233 &self,
234 f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
235 ) -> Result<TreeNodeRecursion>;
236
237 /// Injects arbitrary run-time state into this DataSource, returning a new instance
238 /// that incorporates that state *if* it is relevant to the concrete DataSource implementation.
239 ///
240 /// This is a generic entry point: the `state` can be any type wrapped in
241 /// `Arc<dyn Any + Send + Sync>`. A data source that cares about the state should
242 /// down-cast it to the concrete type it expects and, if successful, return a
243 /// modified copy of itself that captures the provided value. If the state is
244 /// not applicable, the default behaviour is to return `None` so that parent
245 /// nodes can continue propagating the attempt further down the plan tree.
246 fn with_new_state(
247 &self,
248 _state: Arc<dyn Any + Send + Sync>,
249 ) -> Option<Arc<dyn DataSource>> {
250 None
251 }
252
253 /// Create per execution state to share across sibling instances of this
254 /// data source during one execution.
255 ///
256 /// `config` is the session configuration, so implementations can honor
257 /// options that disable sibling sharing (returning `None`) for consumers
258 /// that cannot poll all partitions in one process.
259 ///
260 /// Returns `None` (the default) if this data source has
261 /// no sibling-shared execution state.
262 fn create_sibling_state(
263 &self,
264 _config: &ConfigOptions,
265 ) -> Option<Arc<dyn Any + Send + Sync>> {
266 None
267 }
268
269 /// Open a partition using optional sibling-shared execution state.
270 ///
271 /// The default implementation ignores the additional state and delegates to
272 /// [`Self::open`].
273 fn open_with_args(&self, args: OpenArgs) -> Result<SendableRecordBatchStream> {
274 self.open(args.partition, args.context)
275 }
276
277 /// Serialize this data source to a full [`PhysicalPlanNode`] (a
278 /// `DataSourceExec` wrapping this source), if it knows how.
279 ///
280 /// This is the `DataSource` analog of
281 /// [`ExecutionPlan::try_to_proto`].
282 /// [`DataSourceExec::try_to_proto`](crate::source::DataSourceExec) delegates
283 /// to this hook, which for file scans forwards to
284 /// [`FileSource::try_to_proto`]
285 /// through the shared [`FileScanConfig`]
286 /// spine.
287 ///
288 /// * `Ok(None)` (the default) — "I don't serialize myself"; the caller falls
289 /// back to the central downcast chain in `datafusion-proto`.
290 /// * `Ok(Some(node))` — fully serialized; the caller must not fall back.
291 ///
292 /// [`PhysicalPlanNode`]: datafusion_proto_models::protobuf::PhysicalPlanNode
293 #[cfg(feature = "proto")]
294 fn try_to_proto(
295 &self,
296 _ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
297 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
298 Ok(None)
299 }
300}
301
302/// Arguments for [`DataSource::open_with_args`]
303#[derive(Debug, Clone)]
304pub struct OpenArgs {
305 /// Which partition to open
306 pub partition: usize,
307 /// The task context for execution
308 pub context: Arc<TaskContext>,
309 /// Optional sibling-shared execution state, see
310 /// [`DataSource::create_sibling_state`] for details.
311 pub sibling_state: Option<Arc<dyn Any + Send + Sync>>,
312}
313
314impl OpenArgs {
315 /// Create a new OpenArgs with required arguments
316 pub fn new(partition: usize, context: Arc<TaskContext>) -> Self {
317 Self {
318 partition,
319 context,
320 sibling_state: None,
321 }
322 }
323
324 /// Set sibling shared state
325 pub fn with_shared_state(
326 mut self,
327 sibling_state: Option<Arc<dyn Any + Send + Sync>>,
328 ) -> Self {
329 self.sibling_state = sibling_state;
330 self
331 }
332}
333
334impl dyn DataSource {
335 pub fn is<T: DataSource>(&self) -> bool {
336 (self as &dyn Any).is::<T>()
337 }
338
339 pub fn downcast_ref<T: DataSource>(&self) -> Option<&T> {
340 (self as &dyn Any).downcast_ref()
341 }
342}
343
344/// [`ExecutionPlan`] that reads one or more files
345///
346/// `DataSourceExec` implements common functionality such as applying
347/// projections, and caching plan properties.
348///
349/// The [`DataSource`] describes where to find the data for this data source
350/// (for example in files or what in memory partitions).
351///
352/// For file based [`DataSource`]s, format specific behavior is implemented in
353/// the [`FileSource`] trait.
354///
355/// [`FileSource`]: crate::file::FileSource
356#[derive(Clone, Debug)]
357pub struct DataSourceExec {
358 /// The source of the data -- for example, `FileScanConfig` or `MemorySourceConfig`
359 data_source: Arc<dyn DataSource>,
360 /// Cached plan properties such as sort order
361 cache: Arc<PlanProperties>,
362 /// Per execution state shared across partitions of this plan.
363 ///
364 /// Created by [`DataSource::create_sibling_state`]
365 /// and then passed to
366 /// [`DataSource::open_with_args`].
367 execution_state: Arc<OnceLock<Option<Arc<dyn Any + Send + Sync>>>>,
368}
369
370impl DisplayAs for DataSourceExec {
371 fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
372 match t {
373 DisplayFormatType::Default | DisplayFormatType::Verbose => {
374 write!(f, "DataSourceExec: ")?;
375 }
376 DisplayFormatType::TreeRender => {}
377 }
378 self.data_source.fmt_as(t, f)
379 }
380}
381
382impl ExecutionPlan for DataSourceExec {
383 fn name(&self) -> &'static str {
384 "DataSourceExec"
385 }
386
387 fn properties(&self) -> &Arc<PlanProperties> {
388 &self.cache
389 }
390
391 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
392 Vec::new()
393 }
394
395 fn replace_children(
396 self: Arc<Self>,
397 _: Vec<Arc<dyn ExecutionPlan>>,
398 _: ReplaceChildrenOptions,
399 ) -> Result<Arc<dyn ExecutionPlan>> {
400 Ok(self)
401 }
402
403 fn with_new_children(
404 self: Arc<Self>,
405 children: Vec<Arc<dyn ExecutionPlan>>,
406 ) -> Result<Arc<dyn ExecutionPlan>> {
407 self.replace_children(
408 children,
409 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
410 )
411 }
412
413 fn apply_expressions(
414 &self,
415 f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
416 ) -> Result<TreeNodeRecursion> {
417 // Delegate to the underlying data source
418 self.data_source.apply_expressions(f)
419 }
420
421 /// Implementation of [`ExecutionPlan::repartitioned`] which relies upon the inner [`DataSource::repartitioned`].
422 ///
423 /// If the data source does not support changing its partitioning, returns `Ok(None)` (the default). Refer
424 /// to [`ExecutionPlan::repartitioned`] for more details.
425 fn repartitioned(
426 &self,
427 target_partitions: usize,
428 config: &ConfigOptions,
429 ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
430 let data_source = self.data_source.repartitioned(
431 target_partitions,
432 config.optimizer.repartition_file_min_size,
433 self.properties().eq_properties.output_ordering(),
434 )?;
435
436 Ok(data_source.map(|source| {
437 let output_partitioning = source.output_partitioning();
438 let plan = self
439 .clone()
440 .with_data_source(source)
441 // Changing source partitioning may invalidate output partitioning. Update it also
442 .with_partitioning(output_partitioning);
443 Arc::new(plan) as _
444 }))
445 }
446
447 fn execute(
448 &self,
449 partition: usize,
450 context: Arc<TaskContext>,
451 ) -> Result<SendableRecordBatchStream> {
452 let shared_state = self
453 .execution_state
454 .get_or_init(|| {
455 self.data_source
456 .create_sibling_state(context.session_config().options())
457 })
458 .clone();
459 let args = OpenArgs::new(partition, Arc::clone(&context))
460 .with_shared_state(shared_state);
461 let stream = self.data_source.open_with_args(args)?;
462 let batch_size = context.session_config().batch_size();
463
464 log::debug!(
465 "Batch splitting enabled for partition {partition}: batch_size={batch_size}"
466 );
467 let metrics = self.data_source.metrics();
468 let split_metrics = SplitMetrics::new(&metrics, partition);
469 Ok(Box::pin(BatchSplitStream::new(
470 stream,
471 batch_size,
472 split_metrics,
473 )))
474 }
475
476 fn metrics(&self) -> Option<MetricsSet> {
477 let mut metrics = self.data_source.metrics().clone_inner();
478
479 // Add `output_rows_skew` metric to the metrics set.
480 // Done here because it's a derived metric from output_rows metric.
481 if let Some(file_scan_config) = self.data_source.downcast_ref::<FileScanConfig>()
482 && file_scan_config.file_source().file_type() == "parquet"
483 && let Some(output_rows_skew) =
484 BaselineMetrics::output_rows_skew_metric(&metrics)
485 {
486 metrics.push(output_rows_skew);
487 }
488
489 Some(metrics)
490 }
491
492 fn statistics_from_inputs(
493 &self,
494 _input_stats: &[Arc<Statistics>],
495 args: &StatisticsArgs,
496 ) -> Result<Arc<Statistics>> {
497 self.data_source.partition_statistics(args.partition())
498 }
499
500 fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
501 let data_source = self.data_source.with_fetch(limit)?;
502 let cache = Arc::clone(&self.cache);
503 let execution_state = Arc::new(OnceLock::new());
504
505 Some(Arc::new(Self {
506 data_source,
507 cache,
508 execution_state,
509 }))
510 }
511
512 fn fetch(&self) -> Option<usize> {
513 self.data_source.fetch()
514 }
515
516 fn try_swapping_with_projection(
517 &self,
518 projection: &ProjectionExec,
519 ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
520 match self
521 .data_source
522 .try_swapping_with_projection(projection.projection_expr())?
523 {
524 Some(new_data_source) => {
525 Ok(Some(Arc::new(DataSourceExec::new(new_data_source))))
526 }
527 None => Ok(None),
528 }
529 }
530
531 fn handle_child_pushdown_result(
532 &self,
533 _phase: FilterPushdownPhase,
534 child_pushdown_result: ChildPushdownResult,
535 config: &ConfigOptions,
536 ) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
537 // Push any remaining filters into our data source
538 let parent_filters = child_pushdown_result
539 .parent_filters
540 .into_iter()
541 .map(|f| f.filter)
542 .collect_vec();
543 let res = self
544 .data_source
545 .try_pushdown_filters(parent_filters, config)?;
546 match res.updated_node {
547 Some(data_source) => {
548 let mut new_node = self.clone();
549 new_node.data_source = data_source;
550 // Re-compute properties since we have new filters which will impact equivalence info
551 new_node.cache =
552 Arc::new(Self::compute_properties(&new_node.data_source));
553
554 Ok(FilterPushdownPropagation {
555 filters: res.filters,
556 updated_node: Some(Arc::new(new_node)),
557 })
558 }
559 None => Ok(FilterPushdownPropagation {
560 filters: res.filters,
561 updated_node: None,
562 }),
563 }
564 }
565
566 fn try_pushdown_sort(
567 &self,
568 order: &[PhysicalSortExpr],
569 ) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
570 // Delegate to the data source and wrap result with DataSourceExec
571 self.data_source
572 .try_pushdown_sort(order)?
573 .try_map(|new_data_source| {
574 let new_exec = self.clone().with_data_source(new_data_source);
575 Ok(Arc::new(new_exec) as Arc<dyn ExecutionPlan>)
576 })
577 }
578
579 fn with_new_state(
580 &self,
581 state: Arc<dyn Any + Send + Sync>,
582 ) -> Option<Arc<dyn ExecutionPlan>> {
583 self.data_source
584 .with_new_state(state)
585 .map(|new_data_source| {
586 Arc::new(self.clone().with_data_source(new_data_source))
587 as Arc<dyn ExecutionPlan>
588 })
589 }
590
591 fn reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
592 let mut new_exec = Arc::unwrap_or_clone(self);
593 new_exec.execution_state = Arc::new(OnceLock::new());
594 Ok(Arc::new(new_exec))
595 }
596
597 /// Delegates serialization to the wrapped [`DataSource`]. For file scans the
598 /// concrete [`FileSource`] emits the node via its
599 /// own `try_to_proto` hook, keeping the format-specific wire logic in the
600 /// format crate.
601 #[cfg(feature = "proto")]
602 fn try_to_proto(
603 &self,
604 ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
605 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
606 self.data_source().try_to_proto(ctx)
607 }
608}
609
610impl DataSourceExec {
611 pub fn from_data_source(data_source: impl DataSource + 'static) -> Arc<Self> {
612 Arc::new(Self::new(Arc::new(data_source)))
613 }
614
615 // Default constructor for `DataSourceExec`, setting the `cooperative` flag to `true`.
616 pub fn new(data_source: Arc<dyn DataSource>) -> Self {
617 let cache = Self::compute_properties(&data_source);
618 Self {
619 data_source,
620 cache: Arc::new(cache),
621 execution_state: Arc::new(OnceLock::new()),
622 }
623 }
624
625 /// Return the source object
626 pub fn data_source(&self) -> &Arc<dyn DataSource> {
627 &self.data_source
628 }
629
630 pub fn with_data_source(mut self, data_source: Arc<dyn DataSource>) -> Self {
631 self.cache = Arc::new(Self::compute_properties(&data_source));
632 self.data_source = data_source;
633 self.execution_state = Arc::new(OnceLock::new());
634 self
635 }
636
637 /// Assign constraints
638 pub fn with_constraints(mut self, constraints: Constraints) -> Self {
639 Arc::make_mut(&mut self.cache).set_constraints(constraints);
640 self
641 }
642
643 /// Assign output partitioning
644 pub fn with_partitioning(mut self, partitioning: Partitioning) -> Self {
645 Arc::make_mut(&mut self.cache).partitioning = partitioning;
646 self
647 }
648
649 fn compute_properties(data_source: &Arc<dyn DataSource>) -> PlanProperties {
650 PlanProperties::new(
651 data_source.eq_properties(),
652 data_source.output_partitioning(),
653 EmissionType::Incremental,
654 Boundedness::Bounded,
655 )
656 .with_scheduling_type(data_source.scheduling_type())
657 }
658
659 /// Downcast the `DataSourceExec`'s `data_source` to a specific file source
660 ///
661 /// Returns `None` if
662 /// 1. the datasource is not scanning files (`FileScanConfig`)
663 /// 2. The [`FileScanConfig::file_source`] is not of type `T`
664 pub fn downcast_to_file_source<T: FileSource>(
665 &self,
666 ) -> Option<(&FileScanConfig, &T)> {
667 self.data_source()
668 .downcast_ref::<FileScanConfig>()
669 .and_then(|file_scan_conf| {
670 file_scan_conf
671 .file_source()
672 .downcast_ref::<T>()
673 .map(|source| (file_scan_conf, source))
674 })
675 }
676}
677
678/// Create a new `DataSourceExec` from a `DataSource`
679impl<S> From<S> for DataSourceExec
680where
681 S: DataSource + 'static,
682{
683 fn from(source: S) -> Self {
684 Self::new(Arc::new(source))
685 }
686}