datafusion_catalog/
streaming.rs1use std::sync::Arc;
21
22use arrow::datatypes::SchemaRef;
23use async_trait::async_trait;
24use datafusion_common::{DFSchema, Result, plan_err};
25use datafusion_expr::{Expr, SortExpr, TableType};
26use datafusion_physical_expr::equivalence::project_ordering;
27use datafusion_physical_expr::{LexOrdering, create_physical_sort_exprs};
28use datafusion_physical_plan::ExecutionPlan;
29use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec};
30use log::debug;
31
32use crate::{Session, TableProvider};
33
34#[derive(Debug)]
36pub struct StreamingTable {
37 schema: SchemaRef,
38 partitions: Vec<Arc<dyn PartitionStream>>,
39 infinite: bool,
40 sort_order: Vec<SortExpr>,
41}
42
43impl StreamingTable {
44 pub fn try_new(
46 schema: SchemaRef,
47 partitions: Vec<Arc<dyn PartitionStream>>,
48 ) -> Result<Self> {
49 for x in partitions.iter() {
50 let partition_schema = x.schema();
51 if !schema.contains(partition_schema) {
52 debug!(
53 "target schema does not contain partition schema. \
54 Target_schema: {schema:?}. Partition Schema: {partition_schema:?}"
55 );
56 return plan_err!("Mismatch between schema and batches");
57 }
58 }
59
60 Ok(Self {
61 schema,
62 partitions,
63 infinite: false,
64 sort_order: vec![],
65 })
66 }
67
68 pub fn with_infinite_table(mut self, infinite: bool) -> Self {
70 self.infinite = infinite;
71 self
72 }
73
74 pub fn with_sort_order(mut self, sort_order: Vec<SortExpr>) -> Self {
76 self.sort_order = sort_order;
77 self
78 }
79}
80
81#[async_trait]
82impl TableProvider for StreamingTable {
83 fn schema(&self) -> SchemaRef {
84 Arc::clone(&self.schema)
85 }
86
87 fn table_type(&self) -> TableType {
88 TableType::View
89 }
90
91 async fn scan(
92 &self,
93 state: &dyn Session,
94 projection: Option<&Vec<usize>>,
95 _filters: &[Expr],
96 limit: Option<usize>,
97 ) -> Result<Arc<dyn ExecutionPlan>> {
98 let physical_sort = if !self.sort_order.is_empty() {
99 let df_schema = DFSchema::try_from(Arc::clone(&self.schema))?;
100 let eqp = state.execution_props();
101
102 let original_sort_exprs =
103 create_physical_sort_exprs(&self.sort_order, &df_schema, eqp)?;
104
105 if let Some(p) = projection {
106 let schema = Arc::new(self.schema.project(p)?);
111 LexOrdering::new(original_sort_exprs)
112 .and_then(|lex_ordering| project_ordering(&lex_ordering, &schema))
113 .map(|lex_ordering| lex_ordering.to_vec())
114 .unwrap_or_default()
115 } else {
116 original_sort_exprs
117 }
118 } else {
119 vec![]
120 };
121
122 Ok(Arc::new(StreamingTableExec::try_new(
123 Arc::clone(&self.schema),
124 self.partitions.clone(),
125 projection,
126 LexOrdering::new(physical_sort),
127 self.infinite,
128 limit,
129 )?))
130 }
131}