Skip to content

Apache DataFusion SQL Query Engine

ARROW-10844: [Rust] [DataFusion] Allow joins after a table registration

Jorge C. Leitao669b7c2a1288
diff --git a/rust/datafusion/benches/sort_limit_query_sql.rs b/rust/datafusion/benches/sort_limit_query_sql.rs
index f67c1f729f..ad9f29f828 100644
--- a/rust/datafusion/benches/sort_limit_query_sql.rs
+++ b/rust/datafusion/benches/sort_limit_query_sql.rs
@@ -76,7 +76,7 @@ fn create_context() -> Arc<Mutex<ExecutionContext>> {
// create local execution context
let mut ctx = ExecutionContext::new();
- ctx.state.config.concurrency = 1;
+ ctx.state.lock().unwrap().config.concurrency = 1;
ctx.register_table("aggregate_test_100", Box::new(mem_table));
ctx_holder.lock().unwrap().push(Arc::new(Mutex::new(ctx)))
});
diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rs
index 68884217eb..6cab9299f4 100644
--- a/rust/datafusion/src/dataframe.rs
+++ b/rust/datafusion/src/dataframe.rs
@@ -233,5 +233,5 @@ pub trait DataFrame {
/// # Ok(())
/// # }
/// ```
- fn registry(&self) -> &dyn FunctionRegistry;
+ fn registry(&self) -> Arc<dyn FunctionRegistry>;
}
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 4d00ced9ea..f06d6e5ea0 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -17,11 +17,14 @@
//! ExecutionContext contains methods for registering data sources and executing queries
-use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;
use std::string::String;
use std::sync::Arc;
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Mutex,
+};
use futures::{StreamExt, TryStreamExt};
@@ -91,7 +94,7 @@ use parquet::arrow::ArrowWriter;
/// ```
pub struct ExecutionContext {
/// Internal state for the context
- pub state: ExecutionContextState,
+ pub state: Arc<Mutex<ExecutionContextState>>,
}
impl ExecutionContext {
@@ -103,22 +106,16 @@ impl ExecutionContext {
/// Create a new execution context using the provided configuration
pub fn with_config(config: ExecutionConfig) -> Self {
Self {
- state: ExecutionContextState {
+ state: Arc::new(Mutex::new(ExecutionContextState {
datasources: HashMap::new(),
scalar_functions: HashMap::new(),
var_provider: HashMap::new(),
aggregate_functions: HashMap::new(),
config,
- },
+ })),
}
}
- /// Get the configuration of this execution context
- pub fn config(&self) -> &ExecutionConfig {
- &self.state.config
- }
-
- /// Execute a SQL query and produce a Relation (a schema-aware iterator over a series
/// of RecordBatch instances)
pub fn sql(&mut self, sql: &str) -> Result<Arc<dyn DataFrame>> {
let plan = self.create_logical_plan(sql)?;
@@ -168,7 +165,8 @@ impl ExecutionContext {
}
// create a query planner
- let query_planner = SqlToRel::new(&self.state);
+ let state = self.state.lock().unwrap().clone();
+ let query_planner = SqlToRel::new(&state);
Ok(query_planner.statement_to_plan(&statements[0])?)
}
@@ -178,12 +176,18 @@ impl ExecutionContext {
variable_type: VarType,
provider: Arc<dyn VarProvider + Send + Sync>,
) {
- self.state.var_provider.insert(variable_type, provider);
+ self.state
+ .lock()
+ .unwrap()
+ .var_provider
+ .insert(variable_type, provider);
}
/// Register a scalar UDF
pub fn register_udf(&mut self, f: ScalarUDF) {
self.state
+ .lock()
+ .unwrap()
.scalar_functions
.insert(f.name.clone(), Arc::new(f));
}
@@ -191,6 +195,8 @@ impl ExecutionContext {
/// Register a aggregate UDF
pub fn register_udaf(&mut self, f: AggregateUDF) {
self.state
+ .lock()
+ .unwrap()
.aggregate_functions
.insert(f.name.clone(), Arc::new(f));
}
@@ -261,6 +267,8 @@ impl ExecutionContext {
provider: Box<dyn TableProvider + Send + Sync>,
) {
self.state
+ .lock()
+ .unwrap()
.datasources
.insert(name.to_string(), provider.into());
}
@@ -269,7 +277,7 @@ impl ExecutionContext {
/// register_table function. An Err result will be returned if no table has been
/// registered with the provided name.
pub fn table(&mut self, table_name: &str) -> Result<Arc<dyn DataFrame>> {
- match self.state.datasources.get(table_name) {
+ match self.state.lock().unwrap().datasources.get(table_name) {
Some(provider) => {
let schema = provider.schema();
let table_scan = LogicalPlan::TableScan {
@@ -292,7 +300,13 @@ impl ExecutionContext {
/// The set of available tables. Use `table` to get a specific table.
pub fn tables(&self) -> HashSet<String> {
- self.state.datasources.keys().cloned().collect()
+ self.state
+ .lock()
+ .unwrap()
+ .datasources
+ .keys()
+ .cloned()
+ .collect()
}
/// Optimize the logical plan by applying optimizer rules
@@ -301,7 +315,12 @@ impl ExecutionContext {
let mut plan = ProjectionPushDown::new().optimize(&plan)?;
plan = FilterPushDown::new().optimize(&plan)?;
- self.state.config.query_planner.rewrite_logical_plan(plan)
+ self.state
+ .lock()
+ .unwrap()
+ .config
+ .query_planner
+ .rewrite_logical_plan(plan)
}
/// Create a physical plan from a logical plan
@@ -309,10 +328,11 @@ impl ExecutionContext {
&self,
logical_plan: &LogicalPlan,
) -> Result<Arc<dyn ExecutionPlan>> {
- self.state
+ let state = self.state.lock().unwrap();
+ state
.config
.query_planner
- .create_physical_plan(logical_plan, &self.state)
+ .create_physical_plan(logical_plan, &state)
}
/// Execute a query and write the results to a partitioned CSV file
@@ -373,16 +393,25 @@ impl ExecutionContext {
}
Ok(())
}
+}
- /// get the registry, that allows to construct logical expressions of UDFs
- pub fn registry(&self) -> &dyn FunctionRegistry {
- &self.state
+impl From<Arc<Mutex<ExecutionContextState>>> for ExecutionContext {
+ fn from(state: Arc<Mutex<ExecutionContextState>>) -> Self {
+ ExecutionContext { state }
}
}
-impl From<ExecutionContextState> for ExecutionContext {
- fn from(state: ExecutionContextState) -> Self {
- ExecutionContext { state }
+impl FunctionRegistry for ExecutionContext {
+ fn udfs(&self) -> HashSet<String> {
+ self.state.lock().unwrap().udfs()
+ }
+
+ fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {
+ self.state.lock().unwrap().udf(name)
+ }
+
+ fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {
+ self.state.lock().unwrap().udaf(name)
}
}
@@ -502,10 +531,10 @@ impl FunctionRegistry for ExecutionContextState {
self.scalar_functions.keys().cloned().collect()
}
- fn udf(&self, name: &str) -> Result<&ScalarUDF> {
+ fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {
let result = self.scalar_functions.get(name);
- result.map(|x| x.as_ref()).ok_or_else(|| {
+ result.cloned().ok_or_else(|| {
DataFusionError::Plan(format!(
"There is no UDF named \"{}\" in the registry",
name
@@ -513,10 +542,10 @@ impl FunctionRegistry for ExecutionContextState {
})
}
- fn udaf(&self, name: &str) -> Result<&AggregateUDF> {
+ fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {
let result = self.aggregate_functions.get(name);
- result.map(|x| x.as_ref()).ok_or_else(|| {
+ result.cloned().ok_or_else(|| {
DataFusionError::Plan(format!(
"There is no UDAF named \"{}\" in the registry",
name
@@ -678,7 +707,14 @@ mod tests {
let tmp_dir = TempDir::new()?;
let ctx = create_ctx(&tmp_dir, 1)?;
- let schema = ctx.state.datasources.get("test").unwrap().schema();
+ let schema = ctx
+ .state
+ .lock()
+ .unwrap()
+ .datasources
+ .get("test")
+ .unwrap()
+ .schema();
assert_eq!(schema.field_with_name("c1")?.is_nullable(), false);
let plan = LogicalPlanBuilder::scan_empty("", schema.as_ref(), None)?
@@ -1319,7 +1355,7 @@ mod tests {
.project(vec![
col("a"),
col("b"),
- ctx.registry().udf("my_add")?.call(vec![col("a"), col("b")]),
+ ctx.udf("my_add")?.call(vec![col("a"), col("b")]),
])?
.build()?;
diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rs
index 395b923b15..3badb4fc38 100644
--- a/rust/datafusion/src/execution/dataframe_impl.rs
+++ b/rust/datafusion/src/execution/dataframe_impl.rs
@@ -17,7 +17,7 @@
//! Implementation of DataFrame API
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use crate::dataframe::*;
use crate::error::Result;
@@ -31,13 +31,13 @@ use async_trait::async_trait;
/// Implementation of DataFrame API
pub struct DataFrameImpl {
- ctx_state: ExecutionContextState,
+ ctx_state: Arc<Mutex<ExecutionContextState>>,
plan: LogicalPlan,
}
impl DataFrameImpl {
/// Create a new Table based on an existing logical plan
- pub fn new(ctx_state: ExecutionContextState, plan: &LogicalPlan) -> Self {
+ pub fn new(ctx_state: Arc<Mutex<ExecutionContextState>>, plan: &LogicalPlan) -> Self {
Self {
ctx_state,
plan: plan.clone(),
@@ -119,7 +119,8 @@ impl DataFrame for DataFrameImpl {
// Convert the logical plan represented by this DataFrame into a physical plan and
// execute it
async fn collect(&self) -> Result<Vec<RecordBatch>> {
- let ctx = ExecutionContext::from(self.ctx_state.clone());
+ let state = self.ctx_state.lock().unwrap().clone();
+ let ctx = ExecutionContext::from(Arc::new(Mutex::new(state)));
let plan = ctx.optimize(&self.plan)?;
let plan = ctx.create_physical_plan(&plan)?;
Ok(collect(plan).await?)
@@ -137,8 +138,9 @@ impl DataFrame for DataFrameImpl {
Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))
}
- fn registry(&self) -> &dyn FunctionRegistry {
- &self.ctx_state
+ fn registry(&self) -> Arc<dyn FunctionRegistry> {
+ let registry = self.ctx_state.lock().unwrap().clone();
+ Arc::new(registry)
}
}
diff --git a/rust/datafusion/src/logical_plan/registry.rs b/rust/datafusion/src/logical_plan/registry.rs
index c115048782..d9b1839881 100644
--- a/rust/datafusion/src/logical_plan/registry.rs
+++ b/rust/datafusion/src/logical_plan/registry.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use std::collections::HashSet;
+use std::{collections::HashSet, sync::Arc};
use crate::error::Result;
use crate::physical_plan::udaf::AggregateUDF;
@@ -27,8 +27,8 @@ pub trait FunctionRegistry {
fn udfs(&self) -> HashSet<String>;
/// Returns a reference to the udf named `name`.
- fn udf(&self, name: &str) -> Result<&ScalarUDF>;
+ fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>>;
/// Returns a reference to the udaf named `name`.
- fn udaf(&self, name: &str) -> Result<&AggregateUDF>;
+ fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>>;
}
diff --git a/rust/datafusion/tests/custom_sources.rs b/rust/datafusion/tests/custom_sources.rs
new file mode 100644
index 0000000000..fd041782fd
--- /dev/null
+++ b/rust/datafusion/tests/custom_sources.rs
@@ -0,0 +1,198 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow::array::Int32Array;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use datafusion::error::{DataFusionError, Result};
+use datafusion::{
+ datasource::{datasource::Statistics, TableProvider},
+ physical_plan::collect,
+};
+
+use datafusion::execution::context::ExecutionContext;
+use datafusion::logical_plan::{col, LogicalPlan, LogicalPlanBuilder};
+use datafusion::physical_plan::{
+ ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream,
+};
+
+use futures::stream::Stream;
+use std::any::Any;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use async_trait::async_trait;
+
+//// Custom source dataframe tests ////
+
+struct CustomTableProvider;
+#[derive(Debug, Clone)]
+struct CustomExecutionPlan {
+ projection: Option<Vec<usize>>,
+}
+struct TestCustomRecordBatchStream {
+ /// the nb of batches of TEST_CUSTOM_RECORD_BATCH generated
+ nb_batch: i32,
+}
+macro_rules! TEST_CUSTOM_SCHEMA_REF {
+ () => {
+ Arc::new(Schema::new(vec![
+ Field::new("c1", DataType::Int32, false),
+ Field::new("c2", DataType::Int32, false),
+ ]))
+ };
+}
+macro_rules! TEST_CUSTOM_RECORD_BATCH {
+ () => {
+ RecordBatch::try_new(
+ TEST_CUSTOM_SCHEMA_REF!(),
+ vec![
+ Arc::new(Int32Array::from(vec![1, 10, 10, 100])),
+ Arc::new(Int32Array::from(vec![2, 12, 12, 120])),
+ ],
+ )
+ };
+}
+
+impl RecordBatchStream for TestCustomRecordBatchStream {
+ fn schema(&self) -> SchemaRef {
+ TEST_CUSTOM_SCHEMA_REF!()
+ }
+}
+
+impl Stream for TestCustomRecordBatchStream {
+ type Item = ArrowResult<RecordBatch>;
+
+ fn poll_next(
+ self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Self::Item>> {
+ if self.nb_batch > 0 {
+ self.get_mut().nb_batch -= 1;
+ Poll::Ready(Some(TEST_CUSTOM_RECORD_BATCH!()))
+ } else {
+ Poll::Ready(None)
+ }
+ }
+}
+
+#[async_trait]
+impl ExecutionPlan for CustomExecutionPlan {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn schema(&self) -> SchemaRef {
+ let schema = TEST_CUSTOM_SCHEMA_REF!();
+ match &self.projection {
+ None => schema,
+ Some(p) => Arc::new(Schema::new(
+ p.iter().map(|i| schema.field(*i).clone()).collect(),
+ )),
+ }
+ }
+ fn output_partitioning(&self) -> Partitioning {
+ Partitioning::UnknownPartitioning(1)
+ }
+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+ vec![]
+ }
+ fn with_new_children(
+ &self,
+ children: Vec<Arc<dyn ExecutionPlan>>,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ if children.is_empty() {
+ Ok(Arc::new(self.clone()))
+ } else {
+ Err(DataFusionError::Internal(
+ "Children cannot be replaced in CustomExecutionPlan".to_owned(),
+ ))
+ }
+ }
+ async fn execute(&self, _partition: usize) -> Result<SendableRecordBatchStream> {
+ Ok(Box::pin(TestCustomRecordBatchStream { nb_batch: 1 }))
+ }
+}
+
+impl TableProvider for CustomTableProvider {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn schema(&self) -> SchemaRef {
+ TEST_CUSTOM_SCHEMA_REF!()
+ }
+
+ fn scan(
+ &self,
+ projection: &Option<Vec<usize>>,
+ _batch_size: usize,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ Ok(Arc::new(CustomExecutionPlan {
+ projection: projection.clone(),
+ }))
+ }
+
+ fn statistics(&self) -> Statistics {
+ Statistics::default()
+ }
+}
+
+#[tokio::test]
+async fn custom_source_dataframe() -> Result<()> {
+ let mut ctx = ExecutionContext::new();
+
+ let table = ctx.read_table(Arc::new(CustomTableProvider))?;
+ let logical_plan = LogicalPlanBuilder::from(&table.to_logical_plan())
+ .project(vec![col("c2")])?
+ .build()?;
+
+ let optimized_plan = ctx.optimize(&logical_plan)?;
+ match &optimized_plan {
+ LogicalPlan::Projection { input, .. } => match &**input {
+ LogicalPlan::TableScan {
+ source,
+ projected_schema,
+ ..
+ } => {
+ assert_eq!(source.schema().fields().len(), 2);
+ assert_eq!(projected_schema.fields().len(), 1);
+ }
+ _ => panic!("input to projection should be TableScan"),
+ },
+ _ => panic!("expect optimized_plan to be projection"),
+ }
+
+ let expected = "Projection: #c2\
+ \n TableScan: projection=Some([1])";
+ assert_eq!(format!("{:?}", optimized_plan), expected);
+
+ let physical_plan = ctx.create_physical_plan(&optimized_plan)?;
+
+ assert_eq!(1, physical_plan.schema().fields().len());
+ assert_eq!("c2", physical_plan.schema().field(0).name().as_str());
+
+ let batches = collect(physical_plan).await?;
+ let origin_rec_batch = TEST_CUSTOM_RECORD_BATCH!()?;
+ assert_eq!(1, batches.len());
+ assert_eq!(1, batches[0].num_columns());
+ assert_eq!(origin_rec_batch.num_rows(), batches[0].num_rows());
+
+ Ok(())
+}
diff --git a/rust/datafusion/tests/dataframe.rs b/rust/datafusion/tests/dataframe.rs
index 45ba517503..0f3996803a 100644
--- a/rust/datafusion/tests/dataframe.rs
+++ b/rust/datafusion/tests/dataframe.rs
@@ -15,182 +15,64 @@
// specific language governing permissions and limitations
// under the License.
-use arrow::array::Int32Array;
-use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
-use arrow::error::Result as ArrowResult;
-use arrow::record_batch::RecordBatch;
-
-use datafusion::datasource::datasource::Statistics;
-use datafusion::error::{DataFusionError, Result};
-use datafusion::{datasource::TableProvider, physical_plan::collect};
-
-use datafusion::execution::context::ExecutionContext;
-use datafusion::logical_plan::{col, LogicalPlan, LogicalPlanBuilder};
-use datafusion::physical_plan::{
- ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream,
-};
-
-use futures::stream::Stream;
-use std::any::Any;
-use std::pin::Pin;
use std::sync::Arc;
-use std::task::{Context, Poll};
-
-use async_trait::async_trait;
-
-//// Custom source dataframe tests ////
-struct CustomTableProvider;
-#[derive(Debug, Clone)]
-struct CustomExecutionPlan {
- projection: Option<Vec<usize>>,
-}
-struct TestCustomRecordBatchStream {
- /// the nb of batches of TEST_CUSTOM_RECORD_BATCH generated
- nb_batch: i32,
-}
-macro_rules! TEST_CUSTOM_SCHEMA_REF {
- () => {
- Arc::new(Schema::new(vec![
- Field::new("c1", DataType::Int32, false),
- Field::new("c2", DataType::Int32, false),
- ]))
- };
-}
-macro_rules! TEST_CUSTOM_RECORD_BATCH {
- () => {
- RecordBatch::try_new(
- TEST_CUSTOM_SCHEMA_REF!(),
- vec![
- Arc::new(Int32Array::from(vec![1, 10, 10, 100])),
- Arc::new(Int32Array::from(vec![2, 12, 12, 120])),
- ],
- )
- };
-}
-
-impl RecordBatchStream for TestCustomRecordBatchStream {
- fn schema(&self) -> SchemaRef {
- TEST_CUSTOM_SCHEMA_REF!()
- }
-}
-
-impl Stream for TestCustomRecordBatchStream {
- type Item = ArrowResult<RecordBatch>;
-
- fn poll_next(
- self: Pin<&mut Self>,
- _cx: &mut Context<'_>,
- ) -> Poll<Option<Self::Item>> {
- if self.nb_batch > 0 {
- self.get_mut().nb_batch -= 1;
- Poll::Ready(Some(TEST_CUSTOM_RECORD_BATCH!()))
- } else {
- Poll::Ready(None)
- }
- }
-}
-
-#[async_trait]
-impl ExecutionPlan for CustomExecutionPlan {
- fn as_any(&self) -> &dyn Any {
- self
- }
- fn schema(&self) -> SchemaRef {
- let schema = TEST_CUSTOM_SCHEMA_REF!();
- match &self.projection {
- None => schema,
- Some(p) => Arc::new(Schema::new(
- p.iter().map(|i| schema.field(*i).clone()).collect(),
- )),
- }
- }
- fn output_partitioning(&self) -> Partitioning {
- Partitioning::UnknownPartitioning(1)
- }
- fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
- vec![]
- }
- fn with_new_children(
- &self,
- children: Vec<Arc<dyn ExecutionPlan>>,
- ) -> Result<Arc<dyn ExecutionPlan>> {
- if children.is_empty() {
- Ok(Arc::new(self.clone()))
- } else {
- Err(DataFusionError::Internal(
- "Children cannot be replaced in CustomExecutionPlan".to_owned(),
- ))
- }
- }
- async fn execute(&self, _partition: usize) -> Result<SendableRecordBatchStream> {
- Ok(Box::pin(TestCustomRecordBatchStream { nb_batch: 1 }))
- }
-}
-
-impl TableProvider for CustomTableProvider {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
- fn schema(&self) -> SchemaRef {
- TEST_CUSTOM_SCHEMA_REF!()
- }
+use arrow::datatypes::{DataType, Field, Schema};
+use arrow::{
+ array::{Int32Array, StringArray},
+ record_batch::RecordBatch,
+};
- fn scan(
- &self,
- projection: &Option<Vec<usize>>,
- _batch_size: usize,
- ) -> Result<Arc<dyn ExecutionPlan>> {
- Ok(Arc::new(CustomExecutionPlan {
- projection: projection.clone(),
- }))
- }
+use datafusion::error::Result;
+use datafusion::{datasource::MemTable, prelude::JoinType};
- fn statistics(&self) -> Statistics {
- Statistics::default()
- }
-}
+use datafusion::execution::context::ExecutionContext;
#[tokio::test]
-async fn custom_source_dataframe() -> Result<()> {
+async fn join() -> Result<()> {
+ let schema1 = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Utf8, false),
+ Field::new("b", DataType::Int32, false),
+ ]));
+ let schema2 = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Utf8, false),
+ Field::new("c", DataType::Int32, false),
+ ]));
+
+ // define data.
+ let batch1 = RecordBatch::try_new(
+ schema1.clone(),
+ vec![
+ Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
+ Arc::new(Int32Array::from(vec![1, 10, 10, 100])),
+ ],
+ )?;
+ // define data.
+ let batch2 = RecordBatch::try_new(
+ schema2.clone(),
+ vec![
+ Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
+ Arc::new(Int32Array::from(vec![1, 10, 10, 100])),
+ ],
+ )?;
+
let mut ctx = ExecutionContext::new();
- let table = ctx.read_table(Arc::new(CustomTableProvider))?;
- let logical_plan = LogicalPlanBuilder::from(&table.to_logical_plan())
- .project(vec![col("c2")])?
- .build()?;
+ let table1 = MemTable::try_new(schema1, vec![vec![batch1]])?;
+ let table2 = MemTable::try_new(schema2, vec![vec![batch2]])?;
+
+ ctx.register_table("aa", Box::new(table1));
- let optimized_plan = ctx.optimize(&logical_plan)?;
- match &optimized_plan {
- LogicalPlan::Projection { input, .. } => match &**input {
- LogicalPlan::TableScan {
- source,
- projected_schema,
- ..
- } => {
- assert_eq!(source.schema().fields().len(), 2);
- assert_eq!(projected_schema.fields().len(), 1);
- }
- _ => panic!("input to projection should be TableScan"),
- },
- _ => panic!("expect optimized_plan to be projection"),
- }
+ let df1 = ctx.table("aa")?;
- let expected = "Projection: #c2\
- \n TableScan: projection=Some([1])";
- assert_eq!(format!("{:?}", optimized_plan), expected);
+ ctx.register_table("aaa", Box::new(table2));
- let physical_plan = ctx.create_physical_plan(&optimized_plan)?;
+ let df2 = ctx.table("aaa")?;
- assert_eq!(1, physical_plan.schema().fields().len());
- assert_eq!("c2", physical_plan.schema().field(0).name().as_str());
+ let a = df1.join(df2, JoinType::Inner, &["a"], &["a"])?;
- let batches = collect(physical_plan).await?;
- let origin_rec_batch = TEST_CUSTOM_RECORD_BATCH!()?;
- assert_eq!(1, batches.len());
- assert_eq!(1, batches[0].num_columns());
- assert_eq!(origin_rec_batch.num_rows(), batches[0].num_rows());
+ let batches = a.collect().await?;
+ assert_eq!(batches.len(), 1);
Ok(())
}