datafusion_session/table.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
5use std::any::Any;
6use std::borrow::Cow;
7use std::fmt::Debug;
8use std::future::ready;
9use std::sync::Arc;
10
11use crate::session::Session;
12use arrow_schema::SchemaRef;
13use async_trait::async_trait;
14use datafusion_common::{Constraints, Statistics, not_impl_err};
15use datafusion_common::{DFSchemaRef, Result, internal_err};
16use datafusion_expr::Expr;
17use datafusion_expr::statistics::StatisticsRequest;
18use futures::future::BoxFuture;
19
20use datafusion_expr::dml::{InsertOp, MergeIntoClause};
21use datafusion_expr::{
22 CreateExternalTable, LogicalPlan, TableProviderFilterPushDown, TableType,
23};
24use datafusion_physical_plan::ExecutionPlan;
25
26/// A table which can be queried and modified.
27///
28/// Please see [`CatalogProvider`] for details of implementing a custom catalog.
29///
30/// [`TableProvider`] represents a source of data which can provide data as
31/// Apache Arrow [`RecordBatch`]es. Implementations of this trait provide
32/// important information for planning such as:
33///
34/// 1. [`Self::schema`]: The schema (columns and their types) of the table
35/// 2. [`Self::supports_filters_pushdown`]: Should filters be pushed into this scan
36/// 3. [`Self::supports_skip_pushdown`]: Should `skip` (offset) be pushed into this scan
37/// 4. [`Self::scan`]: An [`ExecutionPlan`] that can read data
38///
39/// [`RecordBatch`]: https://docs.rs/arrow/latest/arrow/record_batch/struct.RecordBatch.html
40/// [`CatalogProvider`]: super::CatalogProvider
41#[async_trait]
42pub trait TableProvider: Any + Debug + Sync + Send {
43 /// Get a reference to the schema for this table
44 fn schema(&self) -> SchemaRef;
45
46 /// Get a reference to the constraints of the table.
47 /// Returns:
48 /// - `None` for tables that do not support constraints.
49 /// - `Some(&Constraints)` for tables supporting constraints.
50 /// Therefore, a `Some(&Constraints::empty())` return value indicates that
51 /// this table supports constraints, but there are no constraints.
52 fn constraints(&self) -> Option<&Constraints> {
53 None
54 }
55
56 /// Get the type of this table for metadata/catalog purposes.
57 fn table_type(&self) -> TableType;
58
59 /// Get the create statement used to create this table, if available.
60 fn get_table_definition(&self) -> Option<&str> {
61 None
62 }
63
64 /// Get the [`LogicalPlan`] of this table, if available.
65 fn get_logical_plan(&'_ self) -> Option<Cow<'_, LogicalPlan>> {
66 None
67 }
68
69 /// Get the default value for a column, if available.
70 fn get_column_default(&self, _column: &str) -> Option<&Expr> {
71 None
72 }
73
74 /// Create an [`ExecutionPlan`] for scanning the table with optional
75 /// `projection`, `filter`, and `limit`, described below.
76 ///
77 /// The returned `ExecutionPlan` is responsible for scanning the datasource's
78 /// partitions in a streaming, parallelized fashion.
79 ///
80 /// # Projection
81 ///
82 /// If specified, only a subset of columns should be returned, in the order
83 /// specified. The projection is a set of indexes of the fields in
84 /// [`Self::schema`].
85 ///
86 /// DataFusion provides the projection so the scan reads only the columns
87 /// actually used in the query, an optimization called "Projection
88 /// Pushdown". Some datasources, such as Parquet, can use this information
89 /// to go significantly faster when only a subset of columns is required.
90 ///
91 /// # Filters
92 ///
93 /// A list of boolean filter [`Expr`]s to evaluate *during* the scan, in the
94 /// manner specified by [`Self::supports_filters_pushdown`]. Only rows for
95 /// which *all* of the `Expr`s evaluate to `true` must be returned (that is,
96 /// the expressions are `AND`ed together).
97 ///
98 /// To enable filter pushdown, override
99 /// [`Self::supports_filters_pushdown`]. The default implementation does not
100 /// push down filters, and `filters` will be empty.
101 ///
102 /// DataFusion pushes filters into scans whenever possible ("Filter
103 /// Pushdown"). Depending on the data format and implementation, evaluating
104 /// predicates during the scan can significantly improve performance.
105 ///
106 /// ## Note: Some columns may appear *only* in Filters
107 ///
108 /// In some cases, a query may use a column only in a filter and the
109 /// projection will not contain all columns referenced by the filter
110 /// expressions.
111 ///
112 /// For example, given the query `SELECT t.a FROM t WHERE t.b > 5`,
113 ///
114 /// ```text
115 /// ┌────────────────────┐
116 /// │ Projection(t.a) │
117 /// └────────────────────┘
118 /// ▲
119 /// │
120 /// │
121 /// ┌────────────────────┐ Filter ┌────────────────────┐ Projection ┌────────────────────┐
122 /// │ Filter(t.b > 5) │────Pushdown──▶ │ Projection(t.a) │ ───Pushdown───▶ │ Projection(t.a) │
123 /// └────────────────────┘ └────────────────────┘ └────────────────────┘
124 /// ▲ ▲ ▲
125 /// │ │ │
126 /// │ │ ┌────────────────────┐
127 /// ┌────────────────────┐ ┌────────────────────┐ │ Scan │
128 /// │ Scan │ │ Scan │ │ filter=(t.b > 5) │
129 /// └────────────────────┘ │ filter=(t.b > 5) │ │ projection=(t.a) │
130 /// └────────────────────┘ └────────────────────┘
131 ///
132 /// Initial Plan If `TableProviderFilterPushDown` Projection pushdown notes that
133 /// returns true, filter pushdown the scan only needs t.a
134 /// pushes the filter into the scan
135 /// BUT internally evaluating the
136 /// predicate still requires t.b
137 /// ```
138 ///
139 /// # Limit
140 ///
141 /// If `limit` is specified, the scan must produce *at most* this many
142 /// rows, though it may return less. Like Projection Pushdown and Filter
143 /// Pushdown, DataFusion pushes `LIMIT`s as far down in the plan as
144 /// possible. This is called "Limit Pushdown", and some sources can use the
145 /// information to improve performance.
146 ///
147 /// Note: If any pushed-down filters are `Inexact`, the `LIMIT` cannot be
148 /// pushed down. Inexact filters do not guarantee that every filtered row is
149 /// removed, so applying the limit could leave too few rows to return in the
150 /// final result.
151 ///
152 /// # Evaluation Order
153 ///
154 /// The logical evaluation order is `filters`, then `limit`, then
155 /// `projection`.
156 ///
157 /// Note that `limit` applies to the filtered result, not to the unfiltered
158 /// input, and `projection` affects only which columns are returned, not
159 /// which rows qualify.
160 ///
161 /// For example, if a scan receives:
162 ///
163 /// - `projection = [a]`
164 /// - `filters = [b > 5]`
165 /// - `limit = Some(3)`
166 ///
167 /// It must logically produce results equivalent to:
168 ///
169 /// ```text
170 /// PROJECTION a (LIMIT 3 (SCAN WHERE b > 5))
171 /// ```
172 ///
173 /// As noted above, columns referenced only by pushed-down filters may be
174 /// absent from `projection`.
175 ///
176 /// # Note
177 ///
178 /// Overriding [`TableProvider::scan_with_args`] will give you access to more arguments,
179 /// e.g. [`ScanArgs::skip`]
180 async fn scan(
181 &self,
182 state: &dyn Session,
183 projection: Option<&[usize]>,
184 filters: &[Expr],
185 limit: Option<usize>,
186 ) -> Result<Arc<dyn ExecutionPlan>>;
187
188 /// Create an [`ExecutionPlan`] for scanning the table using structured arguments.
189 ///
190 /// This method uses [`ScanArgs`] to pass scan parameters in a structured way
191 /// and returns a [`ScanResult`] containing the execution plan.
192 ///
193 /// Table providers can override this method to take advantage of additional
194 /// parameters like the upcoming `preferred_ordering` that may not be available through
195 /// other scan methods.
196 ///
197 /// # Arguments
198 /// * `state` - The session state containing configuration and context
199 /// * `args` - Structured scan arguments including projection, filters, limit, and ordering preferences
200 ///
201 /// # Returns
202 /// A [`ScanResult`] containing the [`ExecutionPlan`] for scanning the table
203 ///
204 /// See [`Self::scan`] for detailed documentation about projection, filters, and limits.
205 ///
206 /// # Evaluation Order
207 ///
208 /// The logical evaluation order is [`ScanArgs::filters`], then [`ScanArgs::skip`]
209 /// and [`ScanArgs::limit`], and finally `projection`.
210 ///
211 /// Note that `limit` and `skip` apply to the filtered result, not to the unfiltered
212 /// input, and `projection` affects only which columns are returned, not which rows qualify.
213 ///
214 /// For example, if a scan receives:
215 ///
216 /// - `projection = [a]`
217 /// - `filters = [b > 5]`
218 /// - `limit = Some(3)`
219 /// - `skip = Some(5)`
220 ///
221 /// It must logically produce results equivalent to:
222 ///
223 /// ```text
224 /// PROJECTION a (OFFSET 5 LIMIT 3 (SCAN WHERE b > 5))
225 /// ```
226 ///
227 /// As noted above, columns referenced only by pushed-down filters may be
228 /// absent from `projection`.
229 // Hand-written `#[async_trait]` expansion to reduce compile time. See
230 // <https://github.com/apache/datafusion/issues/13814>.
231 fn scan_with_args<'a, 'life0, 'life1, 'async_trait>(
232 &'life0 self,
233 state: &'life1 dyn Session,
234 args: ScanArgs<'a>,
235 ) -> BoxFuture<'async_trait, Result<ScanResult>>
236 where
237 'a: 'async_trait,
238 'life0: 'async_trait,
239 'life1: 'async_trait,
240 Self: 'async_trait,
241 {
242 let plan = self.scan(
243 state,
244 args.projection(),
245 args.filters().unwrap_or(&[]),
246 args.limit(),
247 );
248 Box::pin(async move { Ok(plan.await?.into()) })
249 }
250
251 /// Specify if DataFusion should provide the offset/skip to the
252 /// TableProvider to apply *during* the scan.
253 ///
254 /// # Note
255 ///
256 /// Make sure [`TableProvider::scan_with_args`] is overridden too
257 /// and [`ScanArgs::skip`] is used!
258 fn supports_skip_pushdown(&self) -> bool {
259 false
260 }
261
262 /// Specify if DataFusion should provide filter expressions to the
263 /// TableProvider to apply *during* the scan.
264 ///
265 /// Some TableProviders can evaluate filters more efficiently than the
266 /// `Filter` operator in DataFusion, for example by using an index.
267 ///
268 /// # Parameters and Return Value
269 ///
270 /// The return `Vec` must have one element for each element of the `filters`
271 /// argument. The value of each element indicates if the TableProvider can
272 /// apply the corresponding filter during the scan. The position in the return
273 /// value corresponds to the expression in the `filters` parameter.
274 ///
275 /// If the length of the resulting `Vec` does not match the `filters` input
276 /// an error will be thrown.
277 ///
278 /// Each element in the resulting `Vec` is one of the following:
279 /// * [`Exact`] or [`Inexact`]: The TableProvider can apply the filter
280 /// during scan
281 /// * [`Unsupported`]: The TableProvider cannot apply the filter during scan
282 ///
283 /// By default, this function returns [`Unsupported`] for all filters,
284 /// meaning no filters will be provided to [`Self::scan`].
285 ///
286 /// [`Unsupported`]: TableProviderFilterPushDown::Unsupported
287 /// [`Exact`]: TableProviderFilterPushDown::Exact
288 /// [`Inexact`]: TableProviderFilterPushDown::Inexact
289 /// # Example
290 ///
291 /// ```rust
292 /// # use std::any::Any;
293 /// # use std::sync::Arc;
294 /// # use arrow_schema::SchemaRef;
295 /// # use async_trait::async_trait;
296 /// # use datafusion_session::{TableProvider, Session};
297 /// # use datafusion_common::Result;
298 /// # use datafusion_expr::{Expr, TableProviderFilterPushDown, TableType};
299 /// # use datafusion_physical_plan::ExecutionPlan;
300 /// // Define a struct that implements the TableProvider trait
301 /// #[derive(Debug)]
302 /// struct TestDataSource {}
303 ///
304 /// #[async_trait]
305 /// impl TableProvider for TestDataSource {
306 /// # fn schema(&self) -> SchemaRef { todo!() }
307 /// # fn table_type(&self) -> TableType { todo!() }
308 /// # async fn scan(&self, s: &dyn Session, p: Option<&[usize]>, f: &[Expr], l: Option<usize>) -> Result<Arc<dyn ExecutionPlan>> {
309 /// todo!()
310 /// # }
311 /// // Override the supports_filters_pushdown to evaluate which expressions
312 /// // to accept as pushdown predicates.
313 /// fn supports_filters_pushdown(&self, filters: &[&Expr]) -> Result<Vec<TableProviderFilterPushDown>> {
314 /// // Process each filter
315 /// let support: Vec<_> = filters.iter().map(|expr| {
316 /// match expr {
317 /// // This example only supports a between expr with a single column named "c1".
318 /// Expr::Between(between_expr) => {
319 /// between_expr.expr
320 /// .try_as_col()
321 /// .map(|column| {
322 /// if column.name == "c1" {
323 /// TableProviderFilterPushDown::Exact
324 /// } else {
325 /// TableProviderFilterPushDown::Unsupported
326 /// }
327 /// })
328 /// // If there is no column in the expr set the filter to unsupported.
329 /// .unwrap_or(TableProviderFilterPushDown::Unsupported)
330 /// }
331 /// _ => {
332 /// // For all other cases return Unsupported.
333 /// TableProviderFilterPushDown::Unsupported
334 /// }
335 /// }
336 /// }).collect();
337 /// Ok(support)
338 /// }
339 /// }
340 /// ```
341 fn supports_filters_pushdown(
342 &self,
343 filters: &[&Expr],
344 ) -> Result<Vec<TableProviderFilterPushDown>> {
345 Ok(vec![
346 TableProviderFilterPushDown::Unsupported;
347 filters.len()
348 ])
349 }
350
351 /// Get statistics for this table, if available
352 /// Although not presently used in mainline DataFusion, this allows implementation specific
353 /// behavior for downstream repositories, in conjunction with specialized optimizer rules to
354 /// perform operations such as re-ordering of joins.
355 fn statistics(&self) -> Option<Statistics> {
356 None
357 }
358
359 /// Return an [`ExecutionPlan`] to insert data into this table, if
360 /// supported.
361 ///
362 /// The returned plan should return a single row in a UInt64
363 /// column called "count" such as the following
364 ///
365 /// ```text
366 /// +-------+
367 /// | count |
368 /// +-------+
369 /// | 6 |
370 /// +-------+
371 /// ```
372 ///
373 /// # See Also
374 ///
375 /// See [`DataSinkExec`] for the common pattern of inserting a
376 /// streams of `RecordBatch`es as files to an ObjectStore.
377 ///
378 /// [`DataSinkExec`]: https://docs.rs/datafusion-datasource/latest/datafusion_datasource/sink/struct.DataSinkExec.html
379 async fn insert_into(
380 &self,
381 _state: &dyn Session,
382 _input: Arc<dyn ExecutionPlan>,
383 _insert_op: InsertOp,
384 ) -> Result<Arc<dyn ExecutionPlan>> {
385 not_impl_err!("Insert into not implemented for this table")
386 }
387
388 /// Delete rows matching the filter predicates.
389 ///
390 /// Returns an [`ExecutionPlan`] producing one row in a single non-null
391 /// `UInt64` column named `count`, containing the number of deleted rows.
392 /// The default implementation returns a "not implemented" error.
393 ///
394 /// # Filters
395 ///
396 /// `filters` contains logical [`Expr`] predicates on the target table.
397 /// The planner collects them from filters and pushed-down table scan
398 /// predicates, splits `AND` conjunctions, removes table qualifiers, and
399 /// deduplicates them. For example, `t.id = 1 AND t.value > 15` becomes
400 /// separate `id = 1` and `value > 15` expressions.
401 ///
402 /// Delete a row only when every predicate evaluates to true. SQL
403 /// three-valued logic applies: a false or `NULL` predicate leaves the row
404 /// unchanged. Empty `filters` deletes all rows, as for `DELETE FROM t`
405 /// without a `WHERE` clause.
406 ///
407 /// # Execution
408 ///
409 /// This method is called during physical planning, including for `EXPLAIN`.
410 /// Perform mutations when the returned plan executes, rather than while
411 /// constructing it, so planning does not change the table.
412 ///
413 /// # Limitations
414 ///
415 /// The method receives no row limit ([#24998]). Subqueries in DML
416 /// expressions are not fully supported ([#24654]); in particular, a
417 /// subquery rewritten into a join can cause predicates to be lost before
418 /// this method is called.
419 ///
420 /// [#24998]: https://github.com/apache/datafusion/issues/24998
421 /// [#24654]: https://github.com/apache/datafusion/issues/24654
422 // Hand-written `#[async_trait]` expansion to reduce compile time. See
423 // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
424 fn delete_from<'life0, 'life1, 'async_trait>(
425 &'life0 self,
426 _state: &'life1 dyn Session,
427 _filters: Vec<Expr>,
428 ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
429 where
430 'life0: 'async_trait,
431 'life1: 'async_trait,
432 Self: 'async_trait,
433 {
434 Box::pin(ready(not_impl_err!(
435 "DELETE not supported for {} table",
436 self.table_type()
437 )))
438 }
439
440 /// Update rows matching the filter predicates.
441 ///
442 /// Returns an [`ExecutionPlan`] producing one row in a single non-null
443 /// `UInt64` column named `count`, containing the number of affected rows.
444 /// The default implementation returns a "not implemented" error.
445 ///
446 /// # Filters
447 ///
448 /// `filters` follows the same conventions as [`Self::delete_from`]:
449 /// predicates are combined with `AND`, table qualifiers are removed, and
450 /// only rows for which every predicate is true are updated. A false or
451 /// `NULL` predicate leaves the row unchanged. Empty `filters` updates all
452 /// rows.
453 ///
454 /// # Assignments
455 ///
456 /// `assignments` contains `(column_name, Expr)` pairs from the `SET`
457 /// clause. The planner removes identity assignments and strips table
458 /// qualifiers from the expressions. Leave columns without an assignment
459 /// unchanged.
460 ///
461 /// Evaluate every assignment against the row values from before the
462 /// statement, and only for matching rows. For example, `SET a = b, b = a`
463 /// exchanges the two values; an expression such as `100 / divisor` must
464 /// not be evaluated on rows excluded by the filters.
465 ///
466 /// # Execution
467 ///
468 /// Like [`Self::delete_from`], this method is called during physical
469 /// planning, including for `EXPLAIN`. Perform mutations when the returned
470 /// plan executes so planning does not change the table.
471 ///
472 /// # Limitations
473 ///
474 /// Subqueries have the same limitations as in [`Self::delete_from`]
475 /// ([#24654]). `UPDATE ... FROM` is not supported ([#19950]).
476 ///
477 /// [#24654]: https://github.com/apache/datafusion/issues/24654
478 /// [#19950]: https://github.com/apache/datafusion/issues/19950
479 // Hand-written `#[async_trait]` expansion to reduce compile time. See
480 // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
481 fn update<'life0, 'life1, 'async_trait>(
482 &'life0 self,
483 _state: &'life1 dyn Session,
484 _assignments: Vec<(String, Expr)>,
485 _filters: Vec<Expr>,
486 ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
487 where
488 'life0: 'async_trait,
489 'life1: 'async_trait,
490 Self: 'async_trait,
491 {
492 Box::pin(ready(not_impl_err!(
493 "UPDATE not supported for {} table",
494 self.table_type()
495 )))
496 }
497
498 /// Remove all rows from the table.
499 ///
500 /// Should return an [ExecutionPlan] producing a single row with count (UInt64),
501 /// representing the number of rows removed.
502 async fn truncate(&self, _state: &dyn Session) -> Result<Arc<dyn ExecutionPlan>> {
503 not_impl_err!("TRUNCATE not supported for {} table", self.table_type())
504 }
505
506 /// Merge rows from a source into this table.
507 ///
508 /// The `source` is an [`ExecutionPlan`] representing the USING clause.
509 /// The `merge_schema` contains the target columns followed by the source
510 /// columns, preserving their logical qualifiers. Providers can use this
511 /// schema to resolve the logical expressions against the combined rows
512 /// they construct while executing the merge. Providers should identify
513 /// target fields by this leading field range rather than comparing their
514 /// qualifiers with the provider's catalog name.
515 /// The `on` condition is the join predicate from the ON clause.
516 /// The `clauses` describe the WHEN MATCHED / WHEN NOT MATCHED actions.
517 /// These logical expressions may contain residual subqueries. Providers
518 /// must either support those subqueries or return an explicit error.
519 ///
520 /// Returns an [`ExecutionPlan`] producing a single row with `count` (UInt64).
521 // Hand-written `#[async_trait]` expansion to reduce compile time. See
522 // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
523 fn merge_into<'life0, 'life1, 'async_trait>(
524 &'life0 self,
525 _state: &'life1 dyn Session,
526 _source: Arc<dyn ExecutionPlan>,
527 _merge_schema: DFSchemaRef,
528 _on: Expr,
529 _clauses: Vec<MergeIntoClause>,
530 ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
531 where
532 'life0: 'async_trait,
533 'life1: 'async_trait,
534 Self: 'async_trait,
535 {
536 Box::pin(ready(not_impl_err!(
537 "MERGE INTO not supported for {} table",
538 self.table_type()
539 )))
540 }
541}
542
543impl dyn TableProvider {
544 /// Returns `true` if the table provider is of type `T`.
545 ///
546 /// Prefer this over `downcast_ref::<T>().is_some()`. Works correctly when
547 /// called on `Arc<dyn TableProvider>` via auto-deref.
548 pub fn is<T: TableProvider>(&self) -> bool {
549 (self as &dyn Any).is::<T>()
550 }
551
552 /// Attempts to downcast this table provider to a concrete type `T`,
553 /// returning `None` if the provider is not of that type.
554 ///
555 /// Works correctly when called on `Arc<dyn TableProvider>` via auto-deref,
556 /// unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would attempt to
557 /// downcast the `Arc` itself.
558 pub fn downcast_ref<T: TableProvider>(&self) -> Option<&T> {
559 (self as &dyn Any).downcast_ref()
560 }
561}
562
563/// Arguments for scanning a table with [`TableProvider::scan_with_args`].
564#[derive(Debug, Clone, Default)]
565pub struct ScanArgs<'a> {
566 filters: Option<&'a [Expr]>,
567 projection: Option<&'a [usize]>,
568 limit: Option<usize>,
569 skip: Option<usize>,
570 statistics_requests: &'a [StatisticsRequest],
571}
572
573impl<'a> ScanArgs<'a> {
574 /// Set the column projection for the scan.
575 ///
576 /// The projection is a list of column indices from [`TableProvider::schema`]
577 /// that should be included in the scan results. If `None`, all columns are included.
578 ///
579 /// # Arguments
580 /// * `projection` - Optional slice of column indices to project
581 pub fn with_projection(mut self, projection: Option<&'a [usize]>) -> Self {
582 self.projection = projection;
583 self
584 }
585
586 /// Get the column projection for the scan.
587 ///
588 /// Returns a reference to the projection column indices, or `None` if
589 /// no projection was specified (meaning all columns should be included).
590 pub fn projection(&self) -> Option<&'a [usize]> {
591 self.projection
592 }
593
594 /// Set the filter expressions for the scan.
595 ///
596 /// Filters are boolean expressions that should be evaluated during the scan
597 /// to reduce the number of rows returned. All expressions are combined with AND logic.
598 /// Whether filters are actually pushed down depends on [`TableProvider::supports_filters_pushdown`].
599 ///
600 /// # Arguments
601 /// * `filters` - Optional slice of filter expressions
602 pub fn with_filters(mut self, filters: Option<&'a [Expr]>) -> Self {
603 self.filters = filters;
604 self
605 }
606
607 /// Get the filter expressions for the scan.
608 ///
609 /// Returns a reference to the filter expressions, or `None` if no filters were specified.
610 pub fn filters(&self) -> Option<&'a [Expr]> {
611 self.filters
612 }
613
614 /// Set the maximum number of rows to return from the scan.
615 ///
616 /// If specified, the scan should return at most this many rows. This is typically
617 /// used to optimize queries with `LIMIT` clauses.
618 ///
619 /// # Arguments
620 /// * `limit` - Optional maximum number of rows to return
621 pub fn with_limit(mut self, limit: Option<usize>) -> Self {
622 self.limit = limit;
623 self
624 }
625
626 /// Get the maximum number of rows to return from the scan.
627 ///
628 /// Returns the row limit, or `None` if no limit was specified.
629 pub fn limit(&self) -> Option<usize> {
630 self.limit
631 }
632
633 /// Set the number of rows to skip from the scan.
634 ///
635 /// If specified, the scan should skip this many rows. This is typically
636 /// used to optimize queries with `OFFSET` clauses.
637 ///
638 /// # Arguments
639 /// * `skip` - Optional number of rows to skip
640 pub fn with_skip(mut self, skip: Option<usize>) -> Self {
641 self.skip = skip;
642 self
643 }
644
645 /// Get the number of rows to skip from the scan.
646 ///
647 /// Returns the row offsets/skip, or `None` if no such was specified.
648 pub fn skip(&self) -> Option<usize> {
649 self.skip
650 }
651
652 /// Specifies the statistics the caller may use when optimizing the query.
653 ///
654 /// This is intended to allow the `TableProvider` to cheaply provide
655 /// statistics that may help, such as those it has in an in-memory catalog
656 /// or from some other metadata source.
657 ///
658 /// `TableProvider`s read these via [`Self::statistics_requests()`]; anything
659 /// a `TableProvider` cannot answer cheaply it simply ignores. DataFusion's
660 /// own `TableProvider`s ignore this field — it exists so a request can be
661 /// threaded from a custom optimizer rule (which annotates
662 /// `TableScan::statistics_requests`) through to a custom `TableProvider`.
663 pub fn with_statistics_requests(
664 mut self,
665 statistics_requests: &'a [StatisticsRequest],
666 ) -> Self {
667 self.statistics_requests = statistics_requests;
668 self
669 }
670
671 /// Get the statistics requests for the scan. Empty if none were set.
672 ///
673 /// See [`Self::with_statistics_requests`] for more details
674 pub fn statistics_requests(&self) -> &'a [StatisticsRequest] {
675 self.statistics_requests
676 }
677}
678
679/// Result of a table scan operation from [`TableProvider::scan_with_args`].
680#[derive(Debug, Clone)]
681pub struct ScanResult {
682 /// The ExecutionPlan to run.
683 plan: Arc<dyn ExecutionPlan>,
684}
685
686impl ScanResult {
687 /// Create a new `ScanResult` with the given execution plan.
688 ///
689 /// # Arguments
690 /// * `plan` - The execution plan that will perform the table scan
691 pub fn new(plan: Arc<dyn ExecutionPlan>) -> Self {
692 Self { plan }
693 }
694
695 /// Get a reference to the execution plan for this scan result.
696 ///
697 /// Returns a reference to the [`ExecutionPlan`] that will perform
698 /// the actual table scanning and data retrieval.
699 pub fn plan(&self) -> &Arc<dyn ExecutionPlan> {
700 &self.plan
701 }
702
703 /// Consume this ScanResult and return the execution plan.
704 ///
705 /// Returns the owned [`ExecutionPlan`] that will perform
706 /// the actual table scanning and data retrieval.
707 pub fn into_inner(self) -> Arc<dyn ExecutionPlan> {
708 self.plan
709 }
710}
711
712impl From<Arc<dyn ExecutionPlan>> for ScanResult {
713 fn from(plan: Arc<dyn ExecutionPlan>) -> Self {
714 Self::new(plan)
715 }
716}
717
718/// A factory which creates [`TableProvider`]s at runtime given a URL.
719///
720/// For example, this can be used to create a table "on the fly"
721/// from a directory of files only when that name is referenced.
722#[async_trait]
723pub trait TableProviderFactory: Debug + Sync + Send {
724 /// Create a TableProvider with the given url
725 async fn create(
726 &self,
727 state: &dyn Session,
728 cmd: &CreateExternalTable,
729 ) -> Result<Arc<dyn TableProvider>>;
730}
731
732/// Describes arguments provided to the table function call.
733pub struct TableFunctionArgs<'e, 's> {
734 /// Call arguments.
735 exprs: &'e [Expr],
736 /// Session within which the function is called.
737 session: &'s dyn Session,
738}
739
740impl<'e, 's> TableFunctionArgs<'e, 's> {
741 /// Make a new [`TableFunctionArgs`].
742 pub fn new(exprs: &'e [Expr], session: &'s dyn Session) -> Self {
743 Self { exprs, session }
744 }
745
746 /// Get expressions passed as the called function arguments.
747 pub fn exprs(&self) -> &'e [Expr] {
748 self.exprs
749 }
750
751 /// Get a session where the table function is called.
752 pub fn session(&self) -> &'s dyn Session {
753 self.session
754 }
755}
756
757/// A trait for table function implementations
758pub trait TableFunctionImpl: Debug + Sync + Send + Any {
759 /// Create a table provider
760 #[deprecated(
761 since = "53.0.0",
762 note = "Implement `TableFunctionImpl::call_with_args` instead"
763 )]
764 fn call(&self, _exprs: &[Expr]) -> Result<Arc<dyn TableProvider>> {
765 internal_err!(
766 "TableFunctionImpl::call is not implemented. Implement TableFunctionImpl::call_with_args instead."
767 )
768 }
769
770 /// Create a table provider
771 fn call_with_args(&self, args: TableFunctionArgs) -> Result<Arc<dyn TableProvider>> {
772 #[expect(deprecated)]
773 self.call(args.exprs)
774 }
775}
776
777/// A table that uses a function to generate data
778#[derive(Clone, Debug)]
779pub struct TableFunction {
780 /// Name of the table function
781 name: String,
782 /// Function implementation
783 fun: Arc<dyn TableFunctionImpl>,
784}
785
786impl TableFunction {
787 /// Create a new table function
788 pub fn new(name: String, fun: Arc<dyn TableFunctionImpl>) -> Self {
789 Self { name, fun }
790 }
791
792 /// Get the name of the table function
793 pub fn name(&self) -> &str {
794 &self.name
795 }
796
797 /// Get the implementation of the table function
798 pub fn function(&self) -> &Arc<dyn TableFunctionImpl> {
799 &self.fun
800 }
801
802 /// Get the function implementation and generate a table
803 #[deprecated(
804 since = "53.0.0",
805 note = "Use `TableFunction::create_table_provider_with_args` instead"
806 )]
807 pub fn create_table_provider(&self, args: &[Expr]) -> Result<Arc<dyn TableProvider>> {
808 #[expect(deprecated)]
809 self.fun.call(args)
810 }
811
812 /// Get the function implementation and generate a table
813 pub fn create_table_provider_with_args(
814 &self,
815 args: TableFunctionArgs,
816 ) -> Result<Arc<dyn TableProvider>> {
817 self.fun.call_with_args(args)
818 }
819}