Skip to main content

datafusion_catalog/
streaming.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//! A simplified [`TableProvider`] for streaming partitioned datasets
6
7use std::future::ready;
8use std::sync::Arc;
9
10use arrow::datatypes::SchemaRef;
11use async_trait::async_trait;
12use datafusion_common::{DFSchema, Result, plan_err};
13use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
14use datafusion_expr::{Expr, SortExpr, TableType};
15use datafusion_physical_expr::equivalence::project_ordering;
16use datafusion_physical_expr::projection::ProjectionMapping;
17use datafusion_physical_expr::{
18    EquivalenceProperties, LexOrdering, Partitioning, create_physical_sort_exprs,
19};
20use datafusion_physical_plan::ExecutionPlan;
21use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec};
22use futures::future::BoxFuture;
23use log::debug;
24
25use crate::{Session, TableProvider};
26
27/// A [`TableProvider`] that streams a set of [`PartitionStream`]
28#[derive(Debug)]
29pub struct StreamingTable {
30    schema: SchemaRef,
31    partitions: Vec<Arc<dyn PartitionStream>>,
32    infinite: bool,
33    sort_order: Vec<SortExpr>,
34    output_partitioning: Option<Partitioning>,
35}
36
37impl StreamingTable {
38    /// Try to create a new [`StreamingTable`] returning an error if the schema is incorrect
39    pub fn try_new(
40        schema: SchemaRef,
41        partitions: Vec<Arc<dyn PartitionStream>>,
42    ) -> Result<Self> {
43        for x in partitions.iter() {
44            let partition_schema = x.schema();
45            if !schema.contains(partition_schema) {
46                debug!(
47                    "target schema does not contain partition schema. \
48                        Target_schema: {schema:?}. Partition Schema: {partition_schema:?}"
49                );
50                return plan_err!("Mismatch between schema and batches");
51            }
52        }
53
54        Ok(Self {
55            schema,
56            partitions,
57            infinite: false,
58            sort_order: vec![],
59            output_partitioning: None,
60        })
61    }
62
63    /// Sets streaming table can be infinite.
64    pub fn with_infinite_table(mut self, infinite: bool) -> Self {
65        self.infinite = infinite;
66        self
67    }
68
69    /// Sets the existing ordering of streaming table.
70    pub fn with_sort_order(mut self, sort_order: Vec<SortExpr>) -> Self {
71        self.sort_order = sort_order;
72        self
73    }
74
75    /// Declares the output partitioning of this streaming table.
76    ///
77    /// The partitioning expressions refer to the table schema before scan
78    /// projection. If a scan projection removes a partitioning expression, the
79    /// physical plan reports unknown partitioning.
80    pub fn with_output_partitioning(mut self, output_partitioning: Partitioning) -> Self {
81        self.output_partitioning = Some(output_partitioning);
82        self
83    }
84
85    fn output_partitioning(&self, projection: Option<&[usize]>) -> Result<Partitioning> {
86        let Some(output_partitioning) = &self.output_partitioning else {
87            return Ok(Partitioning::UnknownPartitioning(self.partitions.len()));
88        };
89        let Some(projection) = projection else {
90            return Ok(output_partitioning.clone());
91        };
92
93        let projection_mapping =
94            ProjectionMapping::from_indices(projection, &self.schema)?;
95        let eq_properties = EquivalenceProperties::new(Arc::clone(&self.schema));
96        Ok(output_partitioning.project(&projection_mapping, &eq_properties))
97    }
98}
99
100#[async_trait]
101impl TableProvider for StreamingTable {
102    fn schema(&self) -> SchemaRef {
103        Arc::clone(&self.schema)
104    }
105
106    fn table_type(&self) -> TableType {
107        TableType::View
108    }
109
110    // Hand-written `#[async_trait]` expansion to reduce compile time. See
111    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
112    fn scan<'life0, 'life1, 'life2, 'life3, 'async_trait>(
113        &'life0 self,
114        state: &'life1 dyn Session,
115        projection: Option<&'life2 [usize]>,
116        filters: &'life3 [Expr],
117        limit: Option<usize>,
118    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
119    where
120        'life0: 'async_trait,
121        'life1: 'async_trait,
122        'life2: 'async_trait,
123        'life3: 'async_trait,
124        Self: 'async_trait,
125    {
126        self.scan_boxed(state, projection, filters, limit)
127    }
128}
129
130impl StreamingTable {
131    fn scan_boxed<'a>(
132        &'a self,
133        state: &'a dyn Session,
134        projection: Option<&'a [usize]>,
135        filters: &'a [Expr],
136        limit: Option<usize>,
137    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
138        Box::pin(ready(self.scan_inner(state, projection, filters, limit)))
139    }
140
141    fn scan_inner(
142        &self,
143        state: &dyn Session,
144        projection: Option<&[usize]>,
145        _filters: &[Expr],
146        limit: Option<usize>,
147    ) -> Result<Arc<dyn ExecutionPlan>> {
148        let physical_sort = if !self.sort_order.is_empty() {
149            let df_schema = DFSchema::try_from(Arc::clone(&self.schema))?;
150            let eqp = state.execution_props();
151
152            let original_sort_exprs = create_physical_sort_exprs(
153                &self.sort_order,
154                &df_schema,
155                eqp,
156                &PhysicalPlanningContext::default(),
157            )?;
158
159            if let Some(p) = projection {
160                // When performing a projection, the output columns will not match
161                // the original physical sort expression indices. Also the sort columns
162                // may not be in the output projection. To correct for these issues
163                // we need to project the ordering based on the output schema.
164                let schema = Arc::new(self.schema.project(p)?);
165                LexOrdering::new(original_sort_exprs)
166                    .and_then(|lex_ordering| project_ordering(&lex_ordering, &schema))
167                    .map(|lex_ordering| lex_ordering.to_vec())
168                    .unwrap_or_default()
169            } else {
170                original_sort_exprs
171            }
172        } else {
173            vec![]
174        };
175
176        let exec = StreamingTableExec::try_new(
177            Arc::clone(&self.schema),
178            self.partitions.clone(),
179            projection,
180            LexOrdering::new(physical_sort),
181            self.infinite,
182            limit,
183        )?
184        .with_output_partitioning(self.output_partitioning(projection)?)?;
185
186        Ok(Arc::new(exec))
187    }
188}