Skip to content

Apache DataFusion SQL Query Engine

ARROW-9754: [Rust] [DataFusion] Implement async in ExecutionPlan trait

Andy Groved6d043d93d49
diff --git a/rust/benchmarks/Cargo.toml b/rust/benchmarks/Cargo.toml
index ead493b96b..1937024a02 100644
--- a/rust/benchmarks/Cargo.toml
+++ b/rust/benchmarks/Cargo.toml
@@ -28,5 +28,5 @@ license = "Apache-2.0"
[dependencies]
arrow = { path = "../arrow" }
datafusion = { path = "../datafusion" }
-
structopt = { version = "0.3", default-features = false }
+tokio = { version = "0.2", features = ["macros", "rt-core", "rt-threaded"] }
diff --git a/rust/benchmarks/src/bin/nyctaxi.rs b/rust/benchmarks/src/bin/nyctaxi.rs
index 026d020347..02a790bdca 100644
--- a/rust/benchmarks/src/bin/nyctaxi.rs
+++ b/rust/benchmarks/src/bin/nyctaxi.rs
@@ -58,7 +58,8 @@ struct Opt {
file_format: String,
}
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
let opt = Opt::from_args();
println!("Running benchmarks with the following options: {:?}", opt);
@@ -82,10 +83,10 @@ fn main() -> Result<()> {
}
}
- datafusion_sql_benchmarks(&mut ctx, opt.iterations, opt.debug)
+ datafusion_sql_benchmarks(&mut ctx, opt.iterations, opt.debug).await
}
-fn datafusion_sql_benchmarks(
+async fn datafusion_sql_benchmarks(
ctx: &mut ExecutionContext,
iterations: usize,
debug: bool,
@@ -96,7 +97,7 @@ fn datafusion_sql_benchmarks(
println!("Executing '{}'", name);
for i in 0..iterations {
let start = Instant::now();
- execute_sql(ctx, sql, debug)?;
+ execute_sql(ctx, sql, debug).await?;
println!(
"Query '{}' iteration {} took {} ms",
name,
@@ -108,14 +109,14 @@ fn datafusion_sql_benchmarks(
Ok(())
}
-fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Result<()> {
+async fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Result<()> {
let plan = ctx.create_logical_plan(sql)?;
let plan = ctx.optimize(&plan)?;
if debug {
println!("Optimized logical plan:\n{:?}", plan);
}
let physical_plan = ctx.create_physical_plan(&plan)?;
- let result = ctx.collect(physical_plan)?;
+ let result = ctx.collect(physical_plan).await?;
if debug {
pretty::print_batches(&result)?;
}
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rs
index 56ac32c87b..0fe5a1a68c 100644
--- a/rust/benchmarks/src/bin/tpch.rs
+++ b/rust/benchmarks/src/bin/tpch.rs
@@ -61,7 +61,8 @@ struct TpchOpt {
file_format: String,
}
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
let opt = TpchOpt::from_args();
println!("Running benchmarks with the following options: {:?}", opt);
@@ -129,7 +130,7 @@ fn main() -> Result<()> {
for i in 0..opt.iterations {
let start = Instant::now();
- execute_sql(&mut ctx, sql, opt.debug)?;
+ execute_sql(&mut ctx, sql, opt.debug).await?;
println!(
"Query {} iteration {} took {} ms",
opt.query,
@@ -141,14 +142,14 @@ fn main() -> Result<()> {
Ok(())
}
-fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Result<()> {
+async fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Result<()> {
let plan = ctx.create_logical_plan(sql)?;
let plan = ctx.optimize(&plan)?;
if debug {
println!("Optimized logical plan:\n{:?}", plan);
}
let physical_plan = ctx.create_physical_plan(&plan)?;
- let result = ctx.collect(physical_plan)?;
+ let result = ctx.collect(physical_plan).await?;
if debug {
pretty::print_batches(&result)?;
}
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.toml
index 0ec891d76f..66330612d7 100644
--- a/rust/datafusion/Cargo.toml
+++ b/rust/datafusion/Cargo.toml
@@ -54,6 +54,8 @@ crossbeam = "0.7"
paste = "0.1"
num_cpus = "1.13.0"
chrono = "0.4"
+async-trait = "0.1.36"
+tokio = { version = "0.2", features = ["macros", "rt-core", "rt-threaded"] }
[dev-dependencies]
rand = "0.7"
@@ -61,7 +63,6 @@ criterion = "0.3"
tempfile = "3"
futures = "0.3"
prost = "0.6"
-tokio = { version = "0.2", features = ["macros"] }
arrow-flight = { path = "../arrow-flight", version = "2.0.0-SNAPSHOT" }
tonic = "0.2"
diff --git a/rust/datafusion/benches/aggregate_query_sql.rs b/rust/datafusion/benches/aggregate_query_sql.rs
index 2189f5807e..547bf9e5d3 100644
--- a/rust/datafusion/benches/aggregate_query_sql.rs
+++ b/rust/datafusion/benches/aggregate_query_sql.rs
@@ -21,7 +21,7 @@ use criterion::Criterion;
use rand::seq::SliceRandom;
use rand::Rng;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
extern crate arrow;
extern crate datafusion;
@@ -38,10 +38,10 @@ use datafusion::datasource::MemTable;
use datafusion::error::Result;
use datafusion::execution::context::ExecutionContext;
-fn query(ctx: &mut ExecutionContext, sql: &str) {
+async fn query(ctx: Arc<Mutex<ExecutionContext>>, sql: &str) {
// execute the query
- let df = ctx.sql(&sql).unwrap();
- let results = df.collect().unwrap();
+ let df = ctx.lock().unwrap().sql(&sql).unwrap();
+ let results = df.collect().await.unwrap();
// display the relation
for _batch in results {}
@@ -66,7 +66,7 @@ fn create_context(
partitions_len: usize,
array_len: usize,
batch_size: usize,
-) -> Result<ExecutionContext> {
+) -> Result<Arc<Mutex<ExecutionContext>>> {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("utf8", DataType::Utf8, false),
@@ -112,19 +112,19 @@ fn create_context(
let provider = MemTable::new(schema, partitions)?;
ctx.register_table("t", Box::new(provider));
- Ok(ctx)
+ Ok(Arc::new(Mutex::new(ctx)))
}
fn criterion_benchmark(c: &mut Criterion) {
let partitions_len = 4;
let array_len = 32768; // 2^15
let batch_size = 2048; // 2^11
- let mut ctx = create_context(partitions_len, array_len, batch_size).unwrap();
+ let ctx = create_context(partitions_len, array_len, batch_size).unwrap();
c.bench_function("aggregate_query_no_group_by 15 12", |b| {
b.iter(|| {
query(
- &mut ctx,
+ ctx.clone(),
"SELECT MIN(f64), AVG(f64), COUNT(f64) \
FROM t",
)
@@ -134,7 +134,7 @@ fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("aggregate_query_group_by 15 12", |b| {
b.iter(|| {
query(
- &mut ctx,
+ ctx.clone(),
"SELECT utf8, MIN(f64), AVG(f64), COUNT(f64) \
FROM t GROUP BY utf8",
)
@@ -144,7 +144,7 @@ fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("aggregate_query_group_by_with_filter 15 12", |b| {
b.iter(|| {
query(
- &mut ctx,
+ ctx.clone(),
"SELECT utf8, MIN(f64), AVG(f64), COUNT(f64) \
FROM t \
WHERE f32 > 10 AND f32 < 20 GROUP BY utf8",
diff --git a/rust/datafusion/benches/math_query_sql.rs b/rust/datafusion/benches/math_query_sql.rs
index 151a28e547..b7e08106ff 100644
--- a/rust/datafusion/benches/math_query_sql.rs
+++ b/rust/datafusion/benches/math_query_sql.rs
@@ -19,7 +19,7 @@
extern crate criterion;
use criterion::Criterion;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
extern crate arrow;
extern crate datafusion;
@@ -34,16 +34,19 @@ use datafusion::error::Result;
use datafusion::datasource::MemTable;
use datafusion::execution::context::ExecutionContext;
-fn query(ctx: &mut ExecutionContext, sql: &str) {
+async fn query(ctx: Arc<Mutex<ExecutionContext>>, sql: &str) {
// execute the query
- let df = ctx.sql(&sql).unwrap();
- let results = df.collect().unwrap();
+ let df = ctx.lock().unwrap().sql(&sql).unwrap();
+ let results = df.collect().await.unwrap();
// display the relation
for _batch in results {}
}
-fn create_context(array_len: usize, batch_size: usize) -> Result<ExecutionContext> {
+fn create_context(
+ array_len: usize,
+ batch_size: usize,
+) -> Result<Arc<Mutex<ExecutionContext>>> {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("f32", DataType::Float32, false),
@@ -70,29 +73,29 @@ fn create_context(array_len: usize, batch_size: usize) -> Result<ExecutionContex
let provider = MemTable::new(schema, vec![batches])?;
ctx.register_table("t", Box::new(provider));
- Ok(ctx)
+ Ok(Arc::new(Mutex::new(ctx)))
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("sqrt_20_12", |b| {
let array_len = 1048576; // 2^20
let batch_size = 4096; // 2^12
- let mut ctx = create_context(array_len, batch_size).unwrap();
- b.iter(|| query(&mut ctx, "SELECT sqrt(f32) FROM t"))
+ let ctx = create_context(array_len, batch_size).unwrap();
+ b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
c.bench_function("sqrt_22_12", |b| {
let array_len = 4194304; // 2^22
let batch_size = 4096; // 2^12
- let mut ctx = create_context(array_len, batch_size).unwrap();
- b.iter(|| query(&mut ctx, "SELECT sqrt(f32) FROM t"))
+ let ctx = create_context(array_len, batch_size).unwrap();
+ b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
c.bench_function("sqrt_22_14", |b| {
let array_len = 4194304; // 2^22
let batch_size = 16384; // 2^14
- let mut ctx = create_context(array_len, batch_size).unwrap();
- b.iter(|| query(&mut ctx, "SELECT sqrt(f32) FROM t"))
+ let ctx = create_context(array_len, batch_size).unwrap();
+ b.iter(|| query(ctx.clone(), "SELECT sqrt(f32) FROM t"))
});
}
diff --git a/rust/datafusion/benches/sort_limit_query_sql.rs b/rust/datafusion/benches/sort_limit_query_sql.rs
index 51eeec93d2..76e0caea55 100644
--- a/rust/datafusion/benches/sort_limit_query_sql.rs
+++ b/rust/datafusion/benches/sort_limit_query_sql.rs
@@ -20,7 +20,7 @@ extern crate criterion;
use criterion::Criterion;
use std::env;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
extern crate arrow;
extern crate datafusion;
@@ -30,16 +30,18 @@ use arrow::datatypes::{DataType, Field, Schema};
use datafusion::datasource::{CsvFile, CsvReadOptions, MemTable};
use datafusion::execution::context::ExecutionContext;
-fn run_query(ctx: &mut ExecutionContext, sql: &str) {
+use tokio::runtime::Runtime;
+
+async fn run_query(ctx: Arc<Mutex<ExecutionContext>>, sql: &str) {
// execute the query
- let df = ctx.sql(&sql).unwrap();
- let results = df.collect().unwrap();
+ let df = ctx.lock().unwrap().sql(&sql).unwrap();
+ let results = df.collect().await.unwrap();
// display the relation
for _batch in results {}
}
-fn create_context() -> ExecutionContext {
+fn create_context() -> Arc<Mutex<ExecutionContext>> {
// define schema for data source (csv file)
let schema = Arc::new(Schema::new(vec![
Field::new("c1", DataType::Utf8, false),
@@ -66,21 +68,30 @@ fn create_context() -> ExecutionContext {
)
.unwrap();
- let mem_table = MemTable::load(&csv).unwrap();
+ let mut rt = Runtime::new().unwrap();
+
+ let ctx_holder: Arc<Mutex<Vec<Arc<Mutex<ExecutionContext>>>>> =
+ Arc::new(Mutex::new(vec![]));
+ rt.block_on(async {
+ let mem_table = MemTable::load(&csv).await.unwrap();
+
+ // create local execution context
+ let mut ctx = ExecutionContext::new();
+ ctx.state.config.concurrency = 1;
+ ctx.register_table("aggregate_test_100", Box::new(mem_table));
+ ctx_holder.lock().unwrap().push(Arc::new(Mutex::new(ctx)))
+ });
- // create local execution context
- let mut ctx = ExecutionContext::new();
- ctx.state.config.concurrency = 1;
- ctx.register_table("aggregate_test_100", Box::new(mem_table));
+ let ctx = ctx_holder.lock().unwrap().get(0).unwrap().clone();
ctx
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("sort_and_limit_by_int", |b| {
- let mut ctx = create_context();
+ let ctx = create_context();
b.iter(|| {
run_query(
- &mut ctx,
+ ctx.clone(),
"SELECT c1, c13, c6, c10 \
FROM aggregate_test_100 \
ORDER BY 3
@@ -90,10 +101,10 @@ fn criterion_benchmark(c: &mut Criterion) {
});
c.bench_function("sort_and_limit_by_float", |b| {
- let mut ctx = create_context();
+ let ctx = create_context();
b.iter(|| {
run_query(
- &mut ctx,
+ ctx.clone(),
"SELECT c1, c13, c12 \
FROM aggregate_test_100 \
ORDER BY 2
@@ -103,10 +114,10 @@ fn criterion_benchmark(c: &mut Criterion) {
});
c.bench_function("sort_and_limit_lex_by_int", |b| {
- let mut ctx = create_context();
+ let ctx = create_context();
b.iter(|| {
run_query(
- &mut ctx,
+ ctx.clone(),
"SELECT c1, c13, c6, c10 \
FROM aggregate_test_100 \
ORDER BY 3 DESC, 4 DESC
@@ -116,10 +127,10 @@ fn criterion_benchmark(c: &mut Criterion) {
});
c.bench_function("sort_and_limit_lex_by_string", |b| {
- let mut ctx = create_context();
+ let ctx = create_context();
b.iter(|| {
run_query(
- &mut ctx,
+ ctx.clone(),
"SELECT c1, c13, c6, c10 \
FROM aggregate_test_100 \
ORDER BY 1, 2
diff --git a/rust/datafusion/examples/csv_sql.rs b/rust/datafusion/examples/csv_sql.rs
index 97085f8580..78f2416907 100644
--- a/rust/datafusion/examples/csv_sql.rs
+++ b/rust/datafusion/examples/csv_sql.rs
@@ -22,7 +22,8 @@ use datafusion::prelude::*;
/// This example demonstrates executing a simple query against an Arrow data source (CSV) and
/// fetching results
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
// create local execution context
let mut ctx = ExecutionContext::new();
@@ -42,7 +43,7 @@ fn main() -> Result<()> {
WHERE c11 > 0.1 AND c11 < 0.9 \
GROUP BY c1",
)?;
- let results = df.collect()?;
+ let results = df.collect().await?;
// print the results
pretty::print_batches(&results)?;
diff --git a/rust/datafusion/examples/dataframe.rs b/rust/datafusion/examples/dataframe.rs
index 5b45d11cef..979768abfd 100644
--- a/rust/datafusion/examples/dataframe.rs
+++ b/rust/datafusion/examples/dataframe.rs
@@ -22,7 +22,8 @@ use datafusion::prelude::*;
/// This example demonstrates executing a simple query against an Arrow data source (Parquet) and
/// fetching results, using the DataFrame trait
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
// create local execution context
let mut ctx = ExecutionContext::new();
@@ -38,7 +39,7 @@ fn main() -> Result<()> {
.filter(col("tinyint_col").lt(col("tinyint_col")))?;
// execute the query
- let results = df.collect()?;
+ let results = df.collect().await?;
// print the results
pretty::print_batches(&results)?;
diff --git a/rust/datafusion/examples/flight_server.rs b/rust/datafusion/examples/flight_server.rs
index f5d6410cbb..4cf32b7d88 100644
--- a/rust/datafusion/examples/flight_server.rs
+++ b/rust/datafusion/examples/flight_server.rs
@@ -103,7 +103,10 @@ impl FlightService for FlightServiceImpl {
.map_err(|e| to_tonic_err(&e))?;
// execute the query
- let results = ctx.collect(plan.clone()).map_err(|e| to_tonic_err(&e))?;
+ let results = ctx
+ .collect(plan.clone())
+ .await
+ .map_err(|e| to_tonic_err(&e))?;
if results.is_empty() {
return Err(Status::internal("There were no results from ticket"));
}
diff --git a/rust/datafusion/examples/memory_table_api.rs b/rust/datafusion/examples/memory_table_api.rs
index da947613eb..823ea019a9 100644
--- a/rust/datafusion/examples/memory_table_api.rs
+++ b/rust/datafusion/examples/memory_table_api.rs
@@ -28,7 +28,8 @@ use datafusion::error::Result;
use datafusion::prelude::*;
/// This example demonstrates basic uses of the Table API on an in-memory table
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Utf8, false),
@@ -58,7 +59,7 @@ fn main() -> Result<()> {
let df = df.select_columns(vec!["a", "b"])?.filter(filter)?;
// execute
- let results = df.collect()?;
+ let results = df.collect().await?;
// print the results
pretty::print_batches(&results)?;
diff --git a/rust/datafusion/examples/parquet_sql.rs b/rust/datafusion/examples/parquet_sql.rs
index cc9ab968b2..0429305862 100644
--- a/rust/datafusion/examples/parquet_sql.rs
+++ b/rust/datafusion/examples/parquet_sql.rs
@@ -22,7 +22,8 @@ use datafusion::prelude::*;
/// This example demonstrates executing a simple query against an Arrow data source (Parquet) and
/// fetching results
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
// create local execution context
let mut ctx = ExecutionContext::new();
@@ -41,7 +42,7 @@ fn main() -> Result<()> {
FROM alltypes_plain \
WHERE id > 1 AND tinyint_col < double_col",
)?;
- let results = df.collect()?;
+ let results = df.collect().await?;
// print the results
pretty::print_batches(&results)?;
diff --git a/rust/datafusion/examples/simple_udaf.rs b/rust/datafusion/examples/simple_udaf.rs
index deec9b2cc7..5227ba07f9 100644
--- a/rust/datafusion/examples/simple_udaf.rs
+++ b/rust/datafusion/examples/simple_udaf.rs
@@ -125,7 +125,8 @@ impl Accumulator for GeometricMean {
// By default, these methods call `update` and `merge` row by row
}
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
let mut ctx = create_context()?;
// here is where we define the UDAF. We also declare its signature:
@@ -152,7 +153,7 @@ fn main() -> Result<()> {
// note that "a" is f32, not f64. DataFusion coerces it to match the UDAF's signature.
// execute the query
- let results = df.collect()?;
+ let results = df.collect().await?;
// downcast the array to the expected type
let result = results[0]
diff --git a/rust/datafusion/examples/simple_udf.rs b/rust/datafusion/examples/simple_udf.rs
index 313d916ea7..24e8cf7bd8 100644
--- a/rust/datafusion/examples/simple_udf.rs
+++ b/rust/datafusion/examples/simple_udf.rs
@@ -57,7 +57,8 @@ fn create_context() -> Result<ExecutionContext> {
}
/// In this example we will declare a single-type, single return type UDF that exponentiates f64, a^b
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
let mut ctx = create_context()?;
// First, declare the actual implementation of the calculation
@@ -139,7 +140,7 @@ fn main() -> Result<()> {
// note that "b" is f32, not f64. DataFusion coerces the types to match the UDF's signature.
// execute the query
- let results = df.collect()?;
+ let results = df.collect().await?;
// print the results
pretty::print_batches(&results)?;
diff --git a/rust/datafusion/src/bin/repl.rs b/rust/datafusion/src/bin/repl.rs
index d93401b878..df27f98431 100644
--- a/rust/datafusion/src/bin/repl.rs
+++ b/rust/datafusion/src/bin/repl.rs
@@ -26,7 +26,8 @@ use std::env;
use std::path::Path;
use std::time::Instant;
-pub fn main() {
+#[tokio::main]
+pub async fn main() {
let matches = App::new("DataFusion")
.version(crate_version!())
.about(
@@ -76,7 +77,7 @@ pub fn main() {
Ok(ref line) if line.trim_end().ends_with(';') => {
query.push_str(line.trim_end());
rl.add_history_entry(query.clone());
- match exec_and_print(&mut ctx, query) {
+ match exec_and_print(&mut ctx, query).await {
Ok(_) => {}
Err(err) => println!("{:?}", err),
}
@@ -100,11 +101,11 @@ fn is_exit_command(line: &str) -> bool {
line == "quit" || line == "exit"
}
-fn exec_and_print(ctx: &mut ExecutionContext, sql: String) -> Result<()> {
+async fn exec_and_print(ctx: &mut ExecutionContext, sql: String) -> Result<()> {
let now = Instant::now();
let df = ctx.sql(&sql)?;
- let results = df.collect()?;
+ let results = df.collect().await?;
if results.is_empty() {
println!(
diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rs
index ae3bf3a1bb..d2ad7e6917 100644
--- a/rust/datafusion/src/dataframe.rs
+++ b/rust/datafusion/src/dataframe.rs
@@ -23,6 +23,8 @@ use crate::logical_plan::{Expr, FunctionRegistry, LogicalPlan};
use arrow::datatypes::Schema;
use std::sync::Arc;
+use async_trait::async_trait;
+
/// DataFrame represents a logical set of rows with the same named columns.
/// Similar to a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) or
/// [Spark DataFrame](https://spark.apache.org/docs/latest/sql-programming-guide.html)
@@ -47,6 +49,7 @@ use std::sync::Arc;
/// # Ok(())
/// # }
/// ```
+#[async_trait]
pub trait DataFrame {
/// Filter the DataFrame by column. Returns a new DataFrame only containing the
/// specified columns.
@@ -148,14 +151,15 @@ pub trait DataFrame {
/// ```
/// # use datafusion::prelude::*;
/// # use datafusion::error::Result;
- /// # fn main() -> Result<()> {
+ /// # #[tokio::main]
+ /// # async fn main() -> Result<()> {
/// let mut ctx = ExecutionContext::new();
/// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;
- /// let batches = df.collect()?;
+ /// let batches = df.collect().await?;
/// # Ok(())
/// # }
/// ```
- fn collect(&self) -> Result<Vec<RecordBatch>>;
+ async fn collect(&self) -> Result<Vec<RecordBatch>>;
/// Returns the schema describing the output of this DataFrame in terms of columns returned,
/// where each column has a name, data type, and nullability attribute.
@@ -180,10 +184,11 @@ pub trait DataFrame {
/// ```
/// # use datafusion::prelude::*;
/// # use datafusion::error::Result;
- /// # fn main() -> Result<()> {
+ /// # #[tokio::main]
+ /// # async fn main() -> Result<()> {
/// let mut ctx = ExecutionContext::new();
/// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;
- /// let batches = df.limit(100)?.explain(false)?.collect()?;
+ /// let batches = df.limit(100)?.explain(false)?.collect().await?;
/// # Ok(())
/// # }
/// ```
diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rs
index c00528a3d3..4f0f846828 100644
--- a/rust/datafusion/src/datasource/memory.rs
+++ b/rust/datafusion/src/datasource/memory.rs
@@ -55,14 +55,14 @@ impl MemTable {
}
/// Create a mem table by reading from another data source
- pub fn load(t: &dyn TableProvider) -> Result<Self> {
+ pub async fn load(t: &dyn TableProvider) -> Result<Self> {
let schema = t.schema();
let exec = t.scan(&None, 1024 * 1024)?;
let mut data: Vec<Vec<RecordBatch>> =
Vec::with_capacity(exec.output_partitioning().partition_count());
for partition in 0..exec.output_partitioning().partition_count() {
- let it = exec.execute(partition)?;
+ let it = exec.execute(partition).await?;
let mut it = it.lock().unwrap();
let mut partition_batches = vec![];
while let Ok(Some(batch)) = it.next_batch() {
@@ -126,8 +126,8 @@ mod tests {
use arrow::array::Int32Array;
use arrow::datatypes::{DataType, Field, Schema};
- #[test]
- fn test_with_projection() -> Result<()> {
+ #[tokio::test]
+ async fn test_with_projection() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, false),
@@ -147,7 +147,7 @@ mod tests {
// scan with projection
let exec = provider.scan(&Some(vec![2, 1]), 1024)?;
- let it = exec.execute(0)?;
+ let it = exec.execute(0).await?;
let batch2 = it.lock().expect("mutex lock").next_batch()?.unwrap();
assert_eq!(2, batch2.schema().fields().len());
assert_eq!("c", batch2.schema().field(0).name());
@@ -157,8 +157,8 @@ mod tests {
Ok(())
}
- #[test]
- fn test_without_projection() -> Result<()> {
+ #[tokio::test]
+ async fn test_without_projection() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, false),
@@ -177,7 +177,7 @@ mod tests {
let provider = MemTable::new(schema, vec![vec![batch]])?;
let exec = provider.scan(&None, 1024)?;
- let it = exec.execute(0)?;
+ let it = exec.execute(0).await?;
let batch1 = it.lock().expect("mutex lock").next_batch()?.unwrap();
assert_eq!(3, batch1.schema().fields().len());
assert_eq!(3, batch1.num_columns());
diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rs
index beb450dadb..cdefaad645 100644
--- a/rust/datafusion/src/datasource/parquet.rs
+++ b/rust/datafusion/src/datasource/parquet.rs
@@ -77,12 +77,12 @@ mod tests {
use arrow::record_batch::RecordBatch;
use std::env;
- #[test]
- fn read_small_batches() -> Result<()> {
+ #[tokio::test]
+ async fn read_small_batches() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = None;
let exec = table.scan(&projection, 2)?;
- let it = exec.execute(0)?;
+ let it = exec.execute(0).await?;
let mut it = it.lock().unwrap();
let mut count = 0;
@@ -98,8 +98,8 @@ mod tests {
Ok(())
}
- #[test]
- fn read_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let x: Vec<String> = table
@@ -125,7 +125,7 @@ mod tests {
);
let projection = None;
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(11, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -133,11 +133,11 @@ mod tests {
Ok(())
}
- #[test]
- fn read_bool_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_bool_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = Some(vec![1]);
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(1, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -160,11 +160,11 @@ mod tests {
Ok(())
}
- #[test]
- fn read_i32_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_i32_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = Some(vec![0]);
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(1, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -184,11 +184,11 @@ mod tests {
Ok(())
}
- #[test]
- fn read_i96_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_i96_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = Some(vec![10]);
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(1, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -208,11 +208,11 @@ mod tests {
Ok(())
}
- #[test]
- fn read_f32_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_f32_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = Some(vec![6]);
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(1, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -235,11 +235,11 @@ mod tests {
Ok(())
}
- #[test]
- fn read_f64_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_f64_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = Some(vec![7]);
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(1, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -262,11 +262,11 @@ mod tests {
Ok(())
}
- #[test]
- fn read_binary_alltypes_plain_parquet() -> Result<()> {
+ #[tokio::test]
+ async fn read_binary_alltypes_plain_parquet() -> Result<()> {
let table = load_table("alltypes_plain.parquet")?;
let projection = Some(vec![9]);
- let batch = get_first_batch(table, &projection)?;
+ let batch = get_first_batch(table, &projection).await?;
assert_eq!(1, batch.num_columns());
assert_eq!(8, batch.num_rows());
@@ -297,12 +297,12 @@ mod tests {
Ok(Box::new(table))
}
- fn get_first_batch(
+ async fn get_first_batch(
table: Box<dyn TableProvider>,
projection: &Option<Vec<usize>>,
) -> Result<RecordBatch> {
let exec = table.scan(projection, 1024)?;
- let it = exec.execute(0)?;
+ let it = exec.execute(0).await?;
let mut it = it.lock().expect("failed to lock mutex");
Ok(it
.next_batch()?
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 5f575fd769..7bc2d123b0 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -21,10 +21,7 @@ use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;
use std::string::String;
-use std::{
- sync::Arc,
- thread::{self, JoinHandle},
-};
+use std::sync::Arc;
use arrow::csv;
use arrow::datatypes::*;
@@ -327,11 +324,14 @@ impl ExecutionContext {
}
/// Execute a physical plan and collect the results in memory
- pub fn collect(&self, plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
+ pub async fn collect(
+ &self,
+ plan: Arc<dyn ExecutionPlan>,
+ ) -> Result<Vec<RecordBatch>> {
match plan.output_partitioning().partition_count() {
0 => Ok(vec![]),
1 => {
- let it = plan.execute(0)?;
+ let it = plan.execute(0).await?;
common::collect(it)
}
_ => {
@@ -339,49 +339,37 @@ impl ExecutionContext {
let plan = MergeExec::new(plan.clone(), self.state.config.concurrency);
// MergeExec must produce a single partition
assert_eq!(1, plan.output_partitioning().partition_count());
- common::collect(plan.execute(0)?)
+ common::collect(plan.execute(0).await?)
}
}
}
/// Execute a query and write the results to a partitioned CSV file
- pub fn write_csv(&self, plan: Arc<dyn ExecutionPlan>, path: &str) -> Result<()> {
+ pub async fn write_csv(
+ &self,
+ plan: Arc<dyn ExecutionPlan>,
+ path: String,
+ ) -> Result<()> {
// create directory to contain the CSV files (one per partition)
- let path = path.to_string();
+ let path = path.to_owned();
fs::create_dir(&path)?;
- let threads: Vec<JoinHandle<Result<()>>> =
- (0..plan.output_partitioning().partition_count())
- .enumerate()
- .map(|(i, p)| {
- let p = p.clone();
- let path = path.clone();
- let plan = plan.clone();
- thread::spawn(move || {
- let filename = format!("part-{}.csv", i);
- let path = Path::new(&path).join(&filename);
- let file = fs::File::create(path)?;
- let mut writer = csv::Writer::new(file);
- let reader = plan.execute(p)?;
- let mut reader = reader.lock().unwrap();
- loop {
- match reader.next_batch() {
- Ok(Some(batch)) => {
- writer.write(&batch)?;
- }
- Ok(None) => break,
- Err(e) => return Err(ExecutionError::from(e)),
- }
- }
- Ok(())
- })
- })
- .collect();
-
- // combine the results from each thread
- for thread in threads {
- let join = thread.join().expect("Failed to join thread");
- join?;
+ for i in 0..plan.output_partitioning().partition_count() {
+ let path = path.clone();
+ let plan = plan.clone();
+ let filename = format!("part-{}.csv", i);
+ let path = Path::new(&path).join(&filename);
+ let file = fs::File::create(path).unwrap();
+ let mut writer = csv::Writer::new(file);
+ let reader = plan.execute(i).await.unwrap();
+ let mut reader = reader.lock().unwrap();
+ loop {
+ match reader.next_batch() {
+ Ok(Some(batch)) => writer.write(&batch).unwrap(),
+ Ok(None) => break,
+ Err(e) => return Err(ExecutionError::from(e)),
+ }
+ }
}
Ok(())
@@ -550,15 +538,16 @@ mod tests {
ArrayRef, Float64Array, Int32Array, PrimitiveArrayOps, StringArray,
};
use arrow::compute::add;
+ use std::thread::{self, JoinHandle};
use std::{cell::RefCell, fs::File, rc::Rc};
use std::{io::prelude::*, sync::Mutex};
use tempfile::TempDir;
use test::*;
- #[test]
- fn parallel_projection() -> Result<()> {
+ #[tokio::test]
+ async fn parallel_projection() -> Result<()> {
let partition_count = 4;
- let results = execute("SELECT c1, c2 FROM test", partition_count)?;
+ let results = execute("SELECT c1, c2 FROM test", partition_count).await?;
// there should be one batch per partition
assert_eq!(results.len(), partition_count);
@@ -574,8 +563,8 @@ mod tests {
Ok(())
}
- #[test]
- fn create_variable_expr() -> Result<()> {
+ #[tokio::test]
+ async fn create_variable_expr() -> Result<()> {
let tmp_dir = TempDir::new()?;
let partition_count = 4;
let mut ctx = create_ctx(&tmp_dir, partition_count)?;
@@ -588,7 +577,7 @@ mod tests {
let provider = test::create_table_dual();
ctx.register_table("dual", provider);
- let results = collect(&mut ctx, "SELECT @@version, @name FROM dual")?;
+ let results = collect(&mut ctx, "SELECT @@version, @name FROM dual").await?;
let batch = &results[0];
assert_eq!(2, batch.num_columns());
@@ -612,8 +601,8 @@ mod tests {
Ok(())
}
- #[test]
- fn parallel_query_with_filter() -> Result<()> {
+ #[tokio::test]
+ async fn parallel_query_with_filter() -> Result<()> {
let tmp_dir = TempDir::new()?;
let partition_count = 4;
let mut ctx = create_ctx(&tmp_dir, partition_count)?;
@@ -624,7 +613,7 @@ mod tests {
let physical_plan = ctx.create_physical_plan(&logical_plan)?;
- let results = ctx.collect(physical_plan)?;
+ let results = ctx.collect(physical_plan).await?;
// there should be one batch per partition
assert_eq!(results.len(), partition_count);
@@ -635,8 +624,8 @@ mod tests {
Ok(())
}
- #[test]
- fn projection_on_table_scan() -> Result<()> {
+ #[tokio::test]
+ async fn projection_on_table_scan() -> Result<()> {
let tmp_dir = TempDir::new()?;
let partition_count = 4;
let mut ctx = create_ctx(&tmp_dir, partition_count)?;
@@ -671,7 +660,7 @@ mod tests {
assert_eq!(1, physical_plan.schema().fields().len());
assert_eq!("c2", physical_plan.schema().field(0).name().as_str());
- let batches = ctx.collect(physical_plan)?;
+ let batches = ctx.collect(physical_plan).await?;
assert_eq!(4, batches.len());
assert_eq!(1, batches[0].num_columns());
assert_eq!(10, batches[0].num_rows());
@@ -700,8 +689,8 @@ mod tests {
Ok(())
}
- #[test]
- fn projection_on_memory_scan() -> Result<()> {
+ #[tokio::test]
+ async fn projection_on_memory_scan() -> Result<()> {
let schema = Schema::new(vec![
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, false),
@@ -751,7 +740,7 @@ mod tests {
assert_eq!(1, physical_plan.schema().fields().len());
assert_eq!("b", physical_plan.schema().field(0).name().as_str());
- let batches = ctx.collect(physical_plan)?;
+ let batches = ctx.collect(physical_plan).await?;
assert_eq!(1, batches.len());
assert_eq!(1, batches[0].num_columns());
assert_eq!(4, batches[0].num_rows());
@@ -759,9 +748,10 @@ mod tests {
Ok(())
}
- #[test]
- fn sort() -> Result<()> {
- let results = execute("SELECT c1, c2 FROM test ORDER BY c1 DESC, c2 ASC", 4)?;
+ #[tokio::test]
+ async fn sort() -> Result<()> {
+ let results =
+ execute("SELECT c1, c2 FROM test ORDER BY c1 DESC, c2 ASC", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -776,9 +766,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate() -> Result<()> {
- let results = execute("SELECT SUM(c1), SUM(c2) FROM test", 4)?;
+ #[tokio::test]
+ async fn aggregate() -> Result<()> {
+ let results = execute("SELECT SUM(c1), SUM(c2) FROM test", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -793,9 +783,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_avg() -> Result<()> {
- let results = execute("SELECT AVG(c1), AVG(c2) FROM test", 4)?;
+ #[tokio::test]
+ async fn aggregate_avg() -> Result<()> {
+ let results = execute("SELECT AVG(c1), AVG(c2) FROM test", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -810,9 +800,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_max() -> Result<()> {
- let results = execute("SELECT MAX(c1), MAX(c2) FROM test", 4)?;
+ #[tokio::test]
+ async fn aggregate_max() -> Result<()> {
+ let results = execute("SELECT MAX(c1), MAX(c2) FROM test", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -827,9 +817,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_min() -> Result<()> {
- let results = execute("SELECT MIN(c1), MIN(c2) FROM test", 4)?;
+ #[tokio::test]
+ async fn aggregate_min() -> Result<()> {
+ let results = execute("SELECT MIN(c1), MIN(c2) FROM test", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -844,9 +834,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_grouped() -> Result<()> {
- let results = execute("SELECT c1, SUM(c2) FROM test GROUP BY c1", 4)?;
+ #[tokio::test]
+ async fn aggregate_grouped() -> Result<()> {
+ let results = execute("SELECT c1, SUM(c2) FROM test GROUP BY c1", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -861,9 +851,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_grouped_avg() -> Result<()> {
- let results = execute("SELECT c1, AVG(c2) FROM test GROUP BY c1", 4)?;
+ #[tokio::test]
+ async fn aggregate_grouped_avg() -> Result<()> {
+ let results = execute("SELECT c1, AVG(c2) FROM test GROUP BY c1", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -878,10 +868,10 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_grouped_empty() -> Result<()> {
+ #[tokio::test]
+ async fn aggregate_grouped_empty() -> Result<()> {
let results =
- execute("SELECT c1, AVG(c2) FROM test WHERE c1 = 123 GROUP BY c1", 4)?;
+ execute("SELECT c1, AVG(c2) FROM test WHERE c1 = 123 GROUP BY c1", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -896,9 +886,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_grouped_max() -> Result<()> {
- let results = execute("SELECT c1, MAX(c2) FROM test GROUP BY c1", 4)?;
+ #[tokio::test]
+ async fn aggregate_grouped_max() -> Result<()> {
+ let results = execute("SELECT c1, MAX(c2) FROM test GROUP BY c1", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -913,9 +903,9 @@ mod tests {
Ok(())
}
- #[test]
- fn aggregate_grouped_min() -> Result<()> {
- let results = execute("SELECT c1, MIN(c2) FROM test GROUP BY c1", 4)?;
+ #[tokio::test]
+ async fn aggregate_grouped_min() -> Result<()> {
+ let results = execute("SELECT c1, MIN(c2) FROM test GROUP BY c1", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -930,9 +920,9 @@ mod tests {
Ok(())
}
- #[test]
- fn count_basic() -> Result<()> {
- let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 1)?;
+ #[tokio::test]
+ async fn count_basic() -> Result<()> {
+ let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 1).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -946,9 +936,9 @@ mod tests {
Ok(())
}
- #[test]
- fn count_partitioned() -> Result<()> {
- let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 4)?;
+ #[tokio::test]
+ async fn count_partitioned() -> Result<()> {
+ let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -962,9 +952,9 @@ mod tests {
Ok(())
}
- #[test]
- fn count_aggregated() -> Result<()> {
- let results = execute("SELECT c1, COUNT(c2) FROM test GROUP BY c1", 4)?;
+ #[tokio::test]
+ async fn count_aggregated() -> Result<()> {
+ let results = execute("SELECT c1, COUNT(c2) FROM test GROUP BY c1", 4).await?;
assert_eq!(results.len(), 1);
let batch = &results[0];
@@ -1004,15 +994,15 @@ mod tests {
Ok(())
}
- #[test]
- fn write_csv_results() -> Result<()> {
+ #[tokio::test]
+ async fn write_csv_results() -> Result<()> {
// create partitioned input file and context
let tmp_dir = TempDir::new()?;
let mut ctx = create_ctx(&tmp_dir, 4)?;
// execute a simple query and write the results to CSV
let out_dir = tmp_dir.as_ref().to_str().unwrap().to_string() + "/out";
- write_csv(&mut ctx, "SELECT c1, c2 FROM test", &out_dir)?;
+ write_csv(&mut ctx, "SELECT c1, c2 FROM test", &out_dir).await?;
// create a new context and verify that the results were saved to a partitioned csv file
let mut ctx = ExecutionContext::new();
@@ -1030,11 +1020,11 @@ mod tests {
ctx.register_csv("part3", &format!("{}/part-3.csv", out_dir), csv_read_option)?;
ctx.register_csv("allparts", &out_dir, csv_read_option)?;
- let part0 = collect(&mut ctx, "SELECT c1, c2 FROM part0")?;
- let part1 = collect(&mut ctx, "SELECT c1, c2 FROM part1")?;
- let part2 = collect(&mut ctx, "SELECT c1, c2 FROM part2")?;
- let part3 = collect(&mut ctx, "SELECT c1, c2 FROM part3")?;
- let allparts = collect(&mut ctx, "SELECT c1, c2 FROM allparts")?;
+ let part0 = collect(&mut ctx, "SELECT c1, c2 FROM part0").await?;
+ let part1 = collect(&mut ctx, "SELECT c1, c2 FROM part1").await?;
+ let part2 = collect(&mut ctx, "SELECT c1, c2 FROM part2").await?;
+ let part3 = collect(&mut ctx, "SELECT c1, c2 FROM part3").await?;
+ let allparts = collect(&mut ctx, "SELECT c1, c2 FROM allparts").await?;
let part0_count: usize = part0.iter().map(|batch| batch.num_rows()).sum();
let part1_count: usize = part1.iter().map(|batch| batch.num_rows()).sum();
@@ -1051,8 +1041,8 @@ mod tests {
Ok(())
}
- #[test]
- fn query_csv_with_custom_partition_extension() -> Result<()> {
+ #[tokio::test]
+ async fn query_csv_with_custom_partition_extension() -> Result<()> {
let tmp_dir = TempDir::new()?;
// The main stipulation of this test: use a file extension that isn't .csv.
@@ -1067,7 +1057,8 @@ mod tests {
.schema(&schema)
.file_extension(file_extension),
)?;
- let results = collect(&mut ctx, "SELECT SUM(c1), SUM(c2), COUNT(*) FROM test")?;
+ let results =
+ collect(&mut ctx, "SELECT SUM(c1), SUM(c2), COUNT(*) FROM test").await?;
assert_eq!(results.len(), 1);
assert_eq!(results[0].num_rows(), 1);
@@ -1103,8 +1094,8 @@ mod tests {
Ok(())
}
- #[test]
- fn scalar_udf() -> Result<()> {
+ #[tokio::test]
+ async fn scalar_udf() -> Result<()> {
let schema = Schema::new(vec![
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, false),
@@ -1162,7 +1153,7 @@ mod tests {
let plan = ctx.optimize(&plan)?;
let plan = ctx.create_physical_plan(&plan)?;
- let result = ctx.collect(plan)?;
+ let result = ctx.collect(plan).await?;
let batch = &result[0];
assert_eq!(3, batch.num_columns());
@@ -1195,8 +1186,8 @@ mod tests {
Ok(())
}
- #[test]
- fn simple_avg() -> Result<()> {
+ #[tokio::test]
+ async fn simple_avg() -> Result<()> {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
let batch1 = RecordBatch::try_new(
@@ -1213,7 +1204,7 @@ mod tests {
let provider = MemTable::new(Arc::new(schema), vec![vec![batch1], vec![batch2]])?;
ctx.register_table("t", Box::new(provider));
- let result = collect(&mut ctx, "SELECT AVG(a) FROM t")?;
+ let result = collect(&mut ctx, "SELECT AVG(a) FROM t").await?;
let batch = &result[0];
assert_eq!(1, batch.num_columns());
@@ -1231,8 +1222,8 @@ mod tests {
}
/// tests the creation, registration and usage of a UDAF
- #[test]
- fn simple_udaf() -> Result<()> {
+ #[tokio::test]
+ async fn simple_udaf() -> Result<()> {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
let batch1 = RecordBatch::try_new(
@@ -1264,7 +1255,7 @@ mod tests {
ctx.register_udaf(my_avg);
- let result = collect(&mut ctx, "SELECT MY_AVG(a) FROM t")?;
+ let result = collect(&mut ctx, "SELECT MY_AVG(a) FROM t").await?;
let batch = &result[0];
assert_eq!(1, batch.num_columns());
@@ -1281,14 +1272,14 @@ mod tests {
Ok(())
}
- #[test]
- fn custom_query_planner() -> Result<()> {
+ #[tokio::test]
+ async fn custom_query_planner() -> Result<()> {
let mut ctx = ExecutionContext::with_config(
ExecutionConfig::new().with_query_planner(Arc::new(MyQueryPlanner {})),
);
let df = ctx.sql("SELECT 1")?;
- df.collect().expect_err("query not supported");
+ df.collect().await.expect_err("query not supported");
Ok(())
}
@@ -1320,11 +1311,11 @@ mod tests {
}
/// Execute SQL and return results
- fn collect(ctx: &mut ExecutionContext, sql: &str) -> Result<Vec<RecordBatch>> {
+ async fn collect(ctx: &mut ExecutionContext, sql: &str) -> Result<Vec<RecordBatch>> {
let logical_plan = ctx.create_logical_plan(sql)?;
let logical_plan = ctx.optimize(&logical_plan)?;
let physical_plan = ctx.create_physical_plan(&logical_plan)?;
- ctx.collect(physical_plan)
+ ctx.collect(physical_plan).await
}
fn field_names(result: &RecordBatch) -> Vec<String> {
@@ -1337,18 +1328,22 @@ mod tests {
}
/// Execute SQL and return results
- fn execute(sql: &str, partition_count: usize) -> Result<Vec<RecordBatch>> {
+ async fn execute(sql: &str, partition_count: usize) -> Result<Vec<RecordBatch>> {
let tmp_dir = TempDir::new()?;
let mut ctx = create_ctx(&tmp_dir, partition_count)?;
- collect(&mut ctx, sql)
+ collect(&mut ctx, sql).await
}
/// Execute SQL and write results to partitioned csv files
- fn write_csv(ctx: &mut ExecutionContext, sql: &str, out_dir: &str) -> Result<()> {
+ async fn write_csv(
+ ctx: &mut ExecutionContext,
+ sql: &str,
+ out_dir: &str,
+ ) -> Result<()> {
let logical_plan = ctx.create_logical_plan(sql)?;
let logical_plan = ctx.optimize(&logical_plan)?;
let physical_plan = ctx.create_physical_plan(&logical_plan)?;
- ctx.write_csv(physical_plan, out_dir)
+ ctx.write_csv(physical_plan, out_dir.to_string()).await
}
/// Generate CSV partitions within the supplied directory
diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rs
index 98982127a2..a93e5745a0 100644
--- a/rust/datafusion/src/execution/dataframe_impl.rs
+++ b/rust/datafusion/src/execution/dataframe_impl.rs
@@ -26,6 +26,8 @@ use crate::execution::context::{ExecutionContext, ExecutionContextState};
use crate::logical_plan::{col, Expr, FunctionRegistry, LogicalPlan, LogicalPlanBuilder};
use arrow::datatypes::Schema;
+use async_trait::async_trait;
+
/// Implementation of DataFrame API
pub struct DataFrameImpl {
ctx_state: ExecutionContextState,
@@ -42,6 +44,7 @@ impl DataFrameImpl {
}
}
+#[async_trait]
impl DataFrame for DataFrameImpl {
/// Apply a projection based on a list of column names
fn select_columns(&self, columns: Vec<&str>) -> Result<Arc<dyn DataFrame>> {
@@ -106,11 +109,11 @@ impl DataFrame for DataFrameImpl {
// Convert the logical plan represented by this DataFrame into a physical plan and
// execute it
- fn collect(&self) -> Result<Vec<RecordBatch>> {
+ async fn collect(&self) -> Result<Vec<RecordBatch>> {
let ctx = ExecutionContext::from(self.ctx_state.clone());
let plan = ctx.optimize(&self.plan)?;
let plan = ctx.create_physical_plan(&plan)?;
- Ok(ctx.collect(plan)?)
+ Ok(ctx.collect(plan).await?)
}
/// Returns the schema from the logical plan
diff --git a/rust/datafusion/src/physical_plan/csv.rs b/rust/datafusion/src/physical_plan/csv.rs
index 2cf65cc056..436f5c4b64 100644
--- a/rust/datafusion/src/physical_plan/csv.rs
+++ b/rust/datafusion/src/physical_plan/csv.rs
@@ -29,6 +29,8 @@ use arrow::datatypes::{Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use async_trait::async_trait;
+
/// CSV file read option
#[derive(Copy, Clone)]
pub struct CsvReadOptions<'a> {
@@ -179,6 +181,7 @@ impl CsvExec {
}
}
+#[async_trait]
impl ExecutionPlan for CsvExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -214,7 +217,7 @@ impl ExecutionPlan for CsvExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -276,8 +279,8 @@ mod tests {
use super::*;
use crate::test::{aggr_test_schema, arrow_testdata_path};
- #[test]
- fn csv_exec_with_projection() -> Result<()> {
+ #[tokio::test]
+ async fn csv_exec_with_projection() -> Result<()> {
let schema = aggr_test_schema();
let testdata = arrow_testdata_path();
let filename = "aggregate_test_100.csv";
@@ -291,7 +294,7 @@ mod tests {
assert_eq!(13, csv.schema.fields().len());
assert_eq!(3, csv.projected_schema.fields().len());
assert_eq!(3, csv.schema().fields().len());
- let it = csv.execute(0)?;
+ let it = csv.execute(0).await?;
let mut it = it.lock().unwrap();
let batch = it.next_batch()?.unwrap();
assert_eq!(3, batch.num_columns());
@@ -303,8 +306,8 @@ mod tests {
Ok(())
}
- #[test]
- fn csv_exec_without_projection() -> Result<()> {
+ #[tokio::test]
+ async fn csv_exec_without_projection() -> Result<()> {
let schema = aggr_test_schema();
let testdata = arrow_testdata_path();
let filename = "aggregate_test_100.csv";
@@ -314,7 +317,7 @@ mod tests {
assert_eq!(13, csv.schema.fields().len());
assert_eq!(13, csv.projected_schema.fields().len());
assert_eq!(13, csv.schema().fields().len());
- let it = csv.execute(0)?;
+ let it = csv.execute(0).await?;
let mut it = it.lock().unwrap();
let batch = it.next_batch()?.unwrap();
assert_eq!(13, batch.num_columns());
diff --git a/rust/datafusion/src/physical_plan/empty.rs b/rust/datafusion/src/physical_plan/empty.rs
index 0e364abcc5..7e39eef70b 100644
--- a/rust/datafusion/src/physical_plan/empty.rs
+++ b/rust/datafusion/src/physical_plan/empty.rs
@@ -26,6 +26,8 @@ use crate::physical_plan::{Distribution, ExecutionPlan, Partitioning};
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatchReader;
+use async_trait::async_trait;
+
/// Execution plan for empty relation (produces no rows)
#[derive(Debug)]
pub struct EmptyExec {
@@ -39,6 +41,7 @@ impl EmptyExec {
}
}
+#[async_trait]
impl ExecutionPlan for EmptyExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -74,7 +77,7 @@ impl ExecutionPlan for EmptyExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -101,15 +104,15 @@ mod tests {
use crate::physical_plan::common;
use crate::test;
- #[test]
- fn empty() -> Result<()> {
+ #[tokio::test]
+ async fn empty() -> Result<()> {
let schema = test::aggr_test_schema();
let empty = EmptyExec::new(schema.clone());
assert_eq!(empty.schema(), schema);
// we should have no results
- let iter = empty.execute(0)?;
+ let iter = empty.execute(0).await?;
let batches = common::collect(iter)?;
assert!(batches.is_empty());
@@ -132,14 +135,14 @@ mod tests {
Ok(())
}
- #[test]
- fn invalid_execute() -> Result<()> {
+ #[tokio::test]
+ async fn invalid_execute() -> Result<()> {
let schema = test::aggr_test_schema();
let empty = EmptyExec::new(schema.clone());
// ask for the wrong partition
- assert!(empty.execute(1).is_err());
- assert!(empty.execute(20).is_err());
+ assert!(empty.execute(1).await.is_err());
+ assert!(empty.execute(20).await.is_err());
Ok(())
}
}
diff --git a/rust/datafusion/src/physical_plan/explain.rs b/rust/datafusion/src/physical_plan/explain.rs
index 7636860ef0..4e3957f71c 100644
--- a/rust/datafusion/src/physical_plan/explain.rs
+++ b/rust/datafusion/src/physical_plan/explain.rs
@@ -33,6 +33,8 @@ use arrow::{
use crate::physical_plan::Partitioning;
+use async_trait::async_trait;
+
/// Explain execution plan operator. This operator contains the string
/// values of the various plans it has when it is created, and passes
/// them to its output.
@@ -55,6 +57,7 @@ impl ExplainExec {
}
}
+#[async_trait]
impl ExecutionPlan for ExplainExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -88,7 +91,7 @@ impl ExecutionPlan for ExplainExec {
)))
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
diff --git a/rust/datafusion/src/physical_plan/filter.rs b/rust/datafusion/src/physical_plan/filter.rs
index 9cb199a41b..ffc9fa5ff6 100644
--- a/rust/datafusion/src/physical_plan/filter.rs
+++ b/rust/datafusion/src/physical_plan/filter.rs
@@ -29,6 +29,8 @@ use arrow::datatypes::{DataType, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use async_trait::async_trait;
+
/// FilterExec evaluates a boolean predicate against all input batches to determine which rows to
/// include in its output batches.
#[derive(Debug)]
@@ -58,6 +60,7 @@ impl FilterExec {
}
}
+#[async_trait]
impl ExecutionPlan for FilterExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -94,14 +97,14 @@ impl ExecutionPlan for FilterExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
Ok(Arc::new(Mutex::new(FilterExecIter {
schema: self.input.schema().clone(),
predicate: self.predicate.clone(),
- input: self.input.execute(partition)?,
+ input: self.input.execute(partition).await?,
})))
}
}
@@ -171,8 +174,8 @@ mod tests {
use crate::test;
use std::iter::Iterator;
- #[test]
- fn simple_predicate() -> Result<()> {
+ #[tokio::test]
+ async fn simple_predicate() -> Result<()> {
let schema = test::aggr_test_schema();
let partitions = 4;
@@ -201,7 +204,7 @@ mod tests {
let filter: Arc<dyn ExecutionPlan> =
Arc::new(FilterExec::try_new(predicate, Arc::new(csv))?);
- let results = test::execute(filter)?;
+ let results = test::execute(filter).await?;
results
.iter()
diff --git a/rust/datafusion/src/physical_plan/hash_aggregate.rs b/rust/datafusion/src/physical_plan/hash_aggregate.rs
index eda508b83f..8bb679b3f3 100644
--- a/rust/datafusion/src/physical_plan/hash_aggregate.rs
+++ b/rust/datafusion/src/physical_plan/hash_aggregate.rs
@@ -42,6 +42,8 @@ use fnv::FnvHashMap;
use super::{common, expressions::Column};
+use async_trait::async_trait;
+
/// Hash aggregate modes
#[derive(Debug, Copy, Clone)]
pub enum AggregateMode {
@@ -116,6 +118,7 @@ impl HashAggregateExec {
}
}
+#[async_trait]
impl ExecutionPlan for HashAggregateExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -142,11 +145,11 @@ impl ExecutionPlan for HashAggregateExec {
self.input.output_partitioning()
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- let input = self.input.execute(partition)?;
+ let input = self.input.execute(partition).await?;
let group_expr = self.group_expr.iter().map(|x| x.0.clone()).collect();
if self.group_expr.is_empty() {
@@ -729,8 +732,8 @@ mod tests {
))
}
- #[test]
- fn aggregate() -> Result<()> {
+ #[tokio::test]
+ async fn aggregate() -> Result<()> {
let (schema, batches) = some_data().unwrap();
let input: Arc<dyn ExecutionPlan> = Arc::new(
@@ -753,7 +756,7 @@ mod tests {
input,
)?);
- let result = common::collect(partial_aggregate.execute(0)?)?;
+ let result = common::collect(partial_aggregate.execute(0).await?)?;
let keys = result[0]
.column(0)
@@ -792,7 +795,7 @@ mod tests {
merge,
)?);
- let result = common::collect(merged_aggregate.execute(0)?)?;
+ let result = common::collect(merged_aggregate.execute(0).await?)?;
assert_eq!(result.len(), 1);
let batch = &result[0];
diff --git a/rust/datafusion/src/physical_plan/limit.rs b/rust/datafusion/src/physical_plan/limit.rs
index 85582e81f8..a42140e9ca 100644
--- a/rust/datafusion/src/physical_plan/limit.rs
+++ b/rust/datafusion/src/physical_plan/limit.rs
@@ -28,6 +28,8 @@ use arrow::compute::limit;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use async_trait::async_trait;
+
/// Limit execution plan
#[derive(Debug)]
pub struct GlobalLimitExec {
@@ -50,6 +52,7 @@ impl GlobalLimitExec {
}
}
+#[async_trait]
impl ExecutionPlan for GlobalLimitExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -89,7 +92,7 @@ impl ExecutionPlan for GlobalLimitExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -108,7 +111,7 @@ impl ExecutionPlan for GlobalLimitExec {
));
}
- let it = self.input.execute(0)?;
+ let it = self.input.execute(0).await?;
Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
collect_with_limit(it, self.limit)?,
self.input.schema(),
@@ -131,6 +134,7 @@ impl LocalLimitExec {
}
}
+#[async_trait]
impl ExecutionPlan for LocalLimitExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -164,11 +168,11 @@ impl ExecutionPlan for LocalLimitExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- let it = self.input.execute(partition)?;
+ let it = self.input.execute(partition).await?;
Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
collect_with_limit(it, self.limit)?,
self.input.schema(),
@@ -231,8 +235,8 @@ mod tests {
use crate::physical_plan::merge::MergeExec;
use crate::test;
- #[test]
- fn limit() -> Result<()> {
+ #[tokio::test]
+ async fn limit() -> Result<()> {
let schema = test::aggr_test_schema();
let num_partitions = 4;
@@ -249,7 +253,7 @@ mod tests {
GlobalLimitExec::new(Arc::new(MergeExec::new(Arc::new(csv), 2)), 7, 2);
// the result should contain 4 batches (one per input partition)
- let iter = limit.execute(0)?;
+ let iter = limit.execute(0).await?;
let batches = common::collect(iter)?;
// there should be a total of 100 rows
diff --git a/rust/datafusion/src/physical_plan/memory.rs b/rust/datafusion/src/physical_plan/memory.rs
index 13447a4217..fd86006885 100644
--- a/rust/datafusion/src/physical_plan/memory.rs
+++ b/rust/datafusion/src/physical_plan/memory.rs
@@ -26,6 +26,8 @@ use arrow::datatypes::SchemaRef;
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use async_trait::async_trait;
+
/// Execution plan for reading in-memory batches of data
#[derive(Debug)]
pub struct MemoryExec {
@@ -37,6 +39,7 @@ pub struct MemoryExec {
projection: Option<Vec<usize>>,
}
+#[async_trait]
impl ExecutionPlan for MemoryExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -68,7 +71,7 @@ impl ExecutionPlan for MemoryExec {
)))
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
diff --git a/rust/datafusion/src/physical_plan/merge.rs b/rust/datafusion/src/physical_plan/merge.rs
index 89dc7f0126..5c8a25a216 100644
--- a/rust/datafusion/src/physical_plan/merge.rs
+++ b/rust/datafusion/src/physical_plan/merge.rs
@@ -20,7 +20,6 @@
use std::any::Any;
use std::sync::{Arc, Mutex};
-use std::thread::{self, JoinHandle};
use crate::error::{ExecutionError, Result};
use crate::physical_plan::common::RecordBatchIterator;
@@ -30,6 +29,9 @@ use crate::physical_plan::{common, ExecutionPlan};
use arrow::datatypes::SchemaRef;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use async_trait::async_trait;
+use tokio::task::{self, JoinHandle};
+
/// Merge execution plan executes partitions in parallel and combines them into a single
/// partition. No guarantees are made about the order of the resulting partition.
#[derive(Debug)]
@@ -50,6 +52,7 @@ impl MergeExec {
}
}
+#[async_trait]
impl ExecutionPlan for MergeExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -84,7 +87,7 @@ impl ExecutionPlan for MergeExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -103,33 +106,38 @@ impl ExecutionPlan for MergeExec {
)),
1 => {
// bypass any threading if there is a single partition
- self.input.execute(0)
+ self.input.execute(0).await
}
_ => {
let partitions_per_thread = (input_partitions / self.concurrency).max(1);
let range: Vec<usize> = (0..input_partitions).collect();
let chunks = range.chunks(partitions_per_thread);
- let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = chunks
- .map(|chunk| {
- let chunk = chunk.to_vec();
- let input = self.input.clone();
- thread::spawn(move || {
- let mut batches = vec![];
+
+ let mut tasks = vec![];
+ for chunk in chunks {
+ let chunk = chunk.to_vec();
+ let input = self.input.clone();
+ let task: JoinHandle<Result<Vec<Arc<RecordBatch>>>> =
+ task::spawn(async move {
+ let mut batches: Vec<Arc<RecordBatch>> = vec![];
for partition in chunk {
- let it = input.execute(partition)?;
+ let it = input.execute(partition).await?;
common::collect(it)?
.iter()
- .for_each(|b| batches.push(b.clone()));
+ .for_each(|b| batches.push(Arc::new(b.clone())));
}
Ok(batches)
- })
- })
- .collect();
+ });
+ tasks.push(task);
+ }
// combine the results from each thread
let mut combined_results: Vec<Arc<RecordBatch>> = vec![];
- for thread in threads {
- collect_from_thread(thread, &mut combined_results)?;
+ for task in tasks {
+ let result = task.await.unwrap()?;
+ for batch in &result {
+ combined_results.push(batch.clone());
+ }
}
Ok(Arc::new(Mutex::new(RecordBatchIterator::new(
@@ -141,24 +149,6 @@ impl ExecutionPlan for MergeExec {
}
}
-fn collect_from_thread(
- thread: JoinHandle<Result<Vec<RecordBatch>>>,
- combined_results: &mut Vec<Arc<RecordBatch>>,
-) -> Result<()> {
- match thread.join() {
- Ok(join) => {
- join?
- .iter()
- .for_each(|batch| combined_results.push(Arc::new(batch.clone())));
- Ok(())
- }
- Err(e) => Err(ExecutionError::General(format!(
- "Error collecting batches from thread: {:?}",
- e
- ))),
- }
-}
-
#[cfg(test)]
mod tests {
@@ -167,8 +157,8 @@ mod tests {
use crate::physical_plan::csv::{CsvExec, CsvReadOptions};
use crate::test;
- #[test]
- fn merge() -> Result<()> {
+ #[tokio::test]
+ async fn merge() -> Result<()> {
let schema = test::aggr_test_schema();
let num_partitions = 4;
@@ -187,7 +177,7 @@ mod tests {
assert_eq!(merge.output_partitioning().partition_count(), 1);
// the result should contain 4 batches (one per input partition)
- let iter = merge.execute(0)?;
+ let iter = merge.execute(0).await?;
let batches = common::collect(iter)?;
assert_eq!(batches.len(), num_partitions);
diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rs
index bdd971617c..243014519e 100644
--- a/rust/datafusion/src/physical_plan/mod.rs
+++ b/rust/datafusion/src/physical_plan/mod.rs
@@ -30,6 +30,8 @@ use arrow::datatypes::{DataType, Schema, SchemaRef};
use arrow::record_batch::{RecordBatch, RecordBatchReader};
use arrow::{array::ArrayRef, datatypes::Field};
+use async_trait::async_trait;
+
/// Physical query planner that converts a `LogicalPlan` to an
/// `ExecutionPlan` suitable for execution.
pub trait PhysicalPlanner {
@@ -42,6 +44,7 @@ pub trait PhysicalPlanner {
}
/// Partition-aware execution plan for a relation
+#[async_trait]
pub trait ExecutionPlan: Debug + Send + Sync {
/// Returns the execution plan as [`Any`](std::any::Any) so that it can be
/// downcast to a specific implementation.
@@ -65,7 +68,7 @@ pub trait ExecutionPlan: Debug + Send + Sync {
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>>;
/// Execute one partition and return an iterator over RecordBatch
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>>;
diff --git a/rust/datafusion/src/physical_plan/parquet.rs b/rust/datafusion/src/physical_plan/parquet.rs
index 3d74e520d6..ddffdf8d60 100644
--- a/rust/datafusion/src/physical_plan/parquet.rs
+++ b/rust/datafusion/src/physical_plan/parquet.rs
@@ -35,6 +35,8 @@ use crossbeam::channel::{bounded, Receiver, RecvError, Sender};
use fmt::Debug;
use parquet::arrow::{ArrowReader, ParquetFileArrowReader};
+use async_trait::async_trait;
+
/// Execution plan for scanning a Parquet file
#[derive(Debug, Clone)]
pub struct ParquetExec {
@@ -87,6 +89,7 @@ impl ParquetExec {
}
}
+#[async_trait]
impl ExecutionPlan for ParquetExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -121,7 +124,7 @@ impl ExecutionPlan for ParquetExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -220,15 +223,15 @@ mod tests {
use super::*;
use std::env;
- #[test]
- fn test() -> Result<()> {
+ #[tokio::test]
+ async fn test() -> Result<()> {
let testdata =
env::var("PARQUET_TEST_DATA").expect("PARQUET_TEST_DATA not defined");
let filename = format!("{}/alltypes_plain.parquet", testdata);
let parquet_exec = ParquetExec::try_new(&filename, Some(vec![0, 1, 2]), 1024)?;
assert_eq!(parquet_exec.output_partitioning().partition_count(), 1);
- let results = parquet_exec.execute(0)?;
+ let results = parquet_exec.execute(0).await?;
let mut results = results.lock().unwrap();
let batch = results.next_batch()?.unwrap();
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index 2fa0e2fc82..3335f93854 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -553,6 +553,7 @@ mod tests {
datatypes::{DataType, Field, SchemaRef},
record_batch::RecordBatchReader,
};
+ use async_trait::async_trait;
use fmt::Debug;
use std::{any::Any, collections::HashMap, fmt, sync::Mutex};
@@ -773,6 +774,7 @@ mod tests {
schema: SchemaRef,
}
+ #[async_trait]
impl ExecutionPlan for NoOpExecutionPlan {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -799,7 +801,7 @@ mod tests {
}
/// Execute one partition and return an iterator over RecordBatch
- fn execute(
+ async fn execute(
&self,
_partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
diff --git a/rust/datafusion/src/physical_plan/projection.rs b/rust/datafusion/src/physical_plan/projection.rs
index d686b0fa71..43f60510b6 100644
--- a/rust/datafusion/src/physical_plan/projection.rs
+++ b/rust/datafusion/src/physical_plan/projection.rs
@@ -29,6 +29,8 @@ use arrow::datatypes::{Field, Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use async_trait::async_trait;
+
/// Execution plan for a projection
#[derive(Debug)]
pub struct ProjectionExec {
@@ -69,6 +71,7 @@ impl ProjectionExec {
}
}
+#[async_trait]
impl ExecutionPlan for ProjectionExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -104,14 +107,14 @@ impl ExecutionPlan for ProjectionExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
Ok(Arc::new(Mutex::new(ProjectionIterator {
schema: self.schema.clone(),
expr: self.expr.iter().map(|x| x.0.clone()).collect(),
- input: self.input.execute(partition)?,
+ input: self.input.execute(partition).await?,
})))
}
}
@@ -154,8 +157,8 @@ mod tests {
use crate::physical_plan::expressions::col;
use crate::test;
- #[test]
- fn project_first_column() -> Result<()> {
+ #[tokio::test]
+ async fn project_first_column() -> Result<()> {
let schema = test::aggr_test_schema();
let partitions = 4;
@@ -172,7 +175,7 @@ mod tests {
let mut row_count = 0;
for partition in 0..projection.output_partitioning().partition_count() {
partition_count += 1;
- let iterator = projection.execute(partition)?;
+ let iterator = projection.execute(partition).await?;
let mut iterator = iterator.lock().unwrap();
while let Some(batch) = iterator.next_batch()? {
assert_eq!(1, batch.num_columns());
diff --git a/rust/datafusion/src/physical_plan/sort.rs b/rust/datafusion/src/physical_plan/sort.rs
index 8f5e5340ec..139bb4285e 100644
--- a/rust/datafusion/src/physical_plan/sort.rs
+++ b/rust/datafusion/src/physical_plan/sort.rs
@@ -31,6 +31,8 @@ use crate::physical_plan::common::RecordBatchIterator;
use crate::physical_plan::expressions::PhysicalSortExpr;
use crate::physical_plan::{common, Distribution, ExecutionPlan, Partitioning};
+use async_trait::async_trait;
+
/// Sort execution plan
#[derive(Debug)]
pub struct SortExec {
@@ -57,6 +59,7 @@ impl SortExec {
}
}
+#[async_trait]
impl ExecutionPlan for SortExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -96,7 +99,7 @@ impl ExecutionPlan for SortExec {
}
}
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -113,7 +116,7 @@ impl ExecutionPlan for SortExec {
"SortExec requires a single input partition".to_owned(),
));
}
- let it = self.input.execute(0)?;
+ let it = self.input.execute(0).await?;
let batches = common::collect(it)?;
// combine all record batches into one for each column
@@ -181,8 +184,8 @@ mod tests {
use arrow::array::*;
use arrow::datatypes::*;
- #[test]
- fn test_sort() -> Result<()> {
+ #[tokio::test]
+ async fn test_sort() -> Result<()> {
let schema = test::aggr_test_schema();
let partitions = 4;
let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;
@@ -211,7 +214,7 @@ mod tests {
2,
)?);
- let result: Vec<RecordBatch> = test::execute(sort_exec)?;
+ let result: Vec<RecordBatch> = test::execute(sort_exec).await?;
assert_eq!(result.len(), 1);
let columns = result[0].columns();
@@ -231,8 +234,8 @@ mod tests {
Ok(())
}
- #[test]
- fn test_lex_sort_by_float() -> Result<()> {
+ #[tokio::test]
+ async fn test_lex_sort_by_float() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Float32, true),
Field::new("b", DataType::Float64, true),
@@ -289,7 +292,7 @@ mod tests {
assert_eq!(DataType::Float32, *sort_exec.schema().field(0).data_type());
assert_eq!(DataType::Float64, *sort_exec.schema().field(1).data_type());
- let result: Vec<RecordBatch> = test::execute(sort_exec)?;
+ let result: Vec<RecordBatch> = test::execute(sort_exec).await?;
assert_eq!(result.len(), 1);
let columns = result[0].columns();
diff --git a/rust/datafusion/src/test/mod.rs b/rust/datafusion/src/test/mod.rs
index be46c8a4c1..42d930cb8d 100644
--- a/rust/datafusion/src/test/mod.rs
+++ b/rust/datafusion/src/test/mod.rs
@@ -56,9 +56,9 @@ pub fn arrow_testdata_path() -> String {
}
/// Execute a physical plan and collect the results
-pub fn execute(plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
+pub async fn execute(plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
let ctx = ExecutionContext::new();
- ctx.collect(plan)
+ ctx.collect(plan).await
}
/// Generated partitioned copy of a CSV file
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index c3f31822df..b4e07b644e 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -31,8 +31,8 @@ use datafusion::execution::context::ExecutionContext;
use datafusion::logical_plan::LogicalPlan;
use datafusion::prelude::create_udf;
-#[test]
-fn nyc() -> Result<()> {
+#[tokio::test]
+async fn nyc() -> Result<()> {
// schema for nyxtaxi csv files
let schema = Schema::new(vec![
Field::new("VendorID", DataType::Utf8, true),
@@ -86,22 +86,22 @@ fn nyc() -> Result<()> {
Ok(())
}
-#[test]
-fn parquet_query() {
+#[tokio::test]
+async fn parquet_query() {
let mut ctx = ExecutionContext::new();
register_alltypes_parquet(&mut ctx);
// NOTE that string_col is actually a binary column and does not have the UTF8 logical type
// so we need an explicit cast
let sql = "SELECT id, CAST(string_col AS varchar) FROM alltypes_plain";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected =
"4\t\"0\"\n5\t\"1\"\n6\t\"0\"\n7\t\"1\"\n2\t\"0\"\n3\t\"1\"\n0\t\"0\"\n1\t\"1\""
.to_string();
assert_eq!(expected, actual);
}
-#[test]
-fn parquet_single_nan_schema() {
+#[tokio::test]
+async fn parquet_single_nan_schema() {
let mut ctx = ExecutionContext::new();
let testdata = env::var("PARQUET_TEST_DATA").expect("PARQUET_TEST_DATA not defined");
ctx.register_parquet("single_nan", &format!("{}/single_nan.parquet", testdata))
@@ -110,86 +110,86 @@ fn parquet_single_nan_schema() {
let plan = ctx.create_logical_plan(&sql).unwrap();
let plan = ctx.optimize(&plan).unwrap();
let plan = ctx.create_physical_plan(&plan).unwrap();
- let results = ctx.collect(plan).unwrap();
+ let results = ctx.collect(plan).await.unwrap();
for batch in results {
assert_eq!(1, batch.num_rows());
assert_eq!(1, batch.num_columns());
}
}
-#[test]
-fn csv_count_star() -> Result<()> {
+#[tokio::test]
+async fn csv_count_star() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(*), COUNT(1), COUNT(c1) FROM aggregate_test_100";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "100\t100\t100".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_with_predicate() -> Result<()> {
+#[tokio::test]
+async fn csv_query_with_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, c12 FROM aggregate_test_100 WHERE c12 > 0.376 AND c12 < 0.4";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "\"e\"\t0.39144436569161134\n\"d\"\t0.38870280983958583".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_with_negated_predicate() -> Result<()> {
+#[tokio::test]
+async fn csv_query_with_negated_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE NOT(c1 != 'a')";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "21".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_with_is_not_null_predicate() -> Result<()> {
+#[tokio::test]
+async fn csv_query_with_is_not_null_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE c1 IS NOT NULL";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "100".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_with_is_null_predicate() -> Result<()> {
+#[tokio::test]
+async fn csv_query_with_is_null_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE c1 IS NULL";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "0".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_group_by_int_min_max() -> Result<()> {
+#[tokio::test]
+async fn csv_query_group_by_int_min_max() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c2, MIN(c12), MAX(c12) FROM aggregate_test_100 GROUP BY c2";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = "1\t0.05636955101974106\t0.9965400387585364\n2\t0.16301110515739792\t0.991517828651004\n3\t0.047343434291126085\t0.9293883502480845\n4\t0.02182578039211991\t0.9237877978193884\n5\t0.01479305307777301\t0.9723580396501548".to_string();
assert_eq!(expected, actual.join("\n"));
Ok(())
}
-#[test]
-fn csv_query_group_by_two_columns() -> Result<()> {
+#[tokio::test]
+async fn csv_query_group_by_two_columns() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, c2, MIN(c3) FROM aggregate_test_100 GROUP BY c1, c2";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = [
"\"a\"\t1\t-85",
@@ -222,12 +222,12 @@ fn csv_query_group_by_two_columns() -> Result<()> {
Ok(())
}
-#[test]
-fn csv_query_avg_sqrt() -> Result<()> {
+#[tokio::test]
+async fn csv_query_avg_sqrt() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(custom_sqrt(c12)) FROM aggregate_test_100";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = "0.6706002946036462".to_string();
assert_eq!(actual.join("\n"), expected);
@@ -237,37 +237,37 @@ fn csv_query_avg_sqrt() -> Result<()> {
/// test that casting happens on udfs.
/// c11 is f32, but `custom_sqrt` requires f64. Casting happens but the logical plan and
/// physical plan have the same schema.
-#[test]
-fn csv_query_custom_udf_with_cast() -> Result<()> {
+#[tokio::test]
+async fn csv_query_custom_udf_with_cast() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(custom_sqrt(c11)) FROM aggregate_test_100";
- let actual = execute(&mut ctx, sql);
+ let actual = execute(&mut ctx, sql).await;
let expected = "0.6584408483418833".to_string();
assert_eq!(actual.join("\n"), expected);
Ok(())
}
/// sqrt(f32) is sligthly different than sqrt(CAST(f32 AS double)))
-#[test]
-fn sqrt_f32_vs_f64() -> Result<()> {
+#[tokio::test]
+async fn sqrt_f32_vs_f64() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
// sqrt(f32)'s plan passes
let sql = "SELECT avg(sqrt(c11)) FROM aggregate_test_100";
- let actual = &execute(&mut ctx, sql)[0];
+ let actual = &execute(&mut ctx, sql).await[0];
let expected = "0.6584408485889435".to_string();
assert_eq!(*actual, expected);
let sql = "SELECT avg(sqrt(CAST(c11 AS double))) FROM aggregate_test_100";
- let actual = &execute(&mut ctx, sql)[0];
+ let actual = &execute(&mut ctx, sql).await[0];
let expected = "0.6584408483418833".to_string();
assert_eq!(*actual, expected);
Ok(())
}
-#[test]
-fn csv_query_error() -> Result<()> {
+#[tokio::test]
+async fn csv_query_error() -> Result<()> {
// sin(utf8) should error
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
@@ -278,12 +278,12 @@ fn csv_query_error() -> Result<()> {
}
// this query used to deadlock due to the call udf(udf())
-#[test]
-fn csv_query_sqrt_sqrt() -> Result<()> {
+#[tokio::test]
+async fn csv_query_sqrt_sqrt() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT sqrt(sqrt(c12)) FROM aggregate_test_100 LIMIT 1";
- let actual = execute(&mut ctx, sql);
+ let actual = execute(&mut ctx, sql).await;
// sqrt(sqrt(c12=0.9294097332465232)) = 0.9818650561397431
let expected = "0.9818650561397431".to_string();
assert_eq!(actual.join("\n"), expected);
@@ -321,51 +321,51 @@ fn custom_sqrt(args: &[ArrayRef]) -> Result<ArrayRef> {
Ok(Arc::new(builder.finish()))
}
-#[test]
-fn csv_query_avg() -> Result<()> {
+#[tokio::test]
+async fn csv_query_avg() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(c12) FROM aggregate_test_100";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = "0.5089725099127211".to_string();
assert_eq!(expected, actual.join("\n"));
Ok(())
}
-#[test]
-fn csv_query_group_by_avg() -> Result<()> {
+#[tokio::test]
+async fn csv_query_group_by_avg() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, avg(c12) FROM aggregate_test_100 GROUP BY c1";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = "\"a\"\t0.48754517466109415\n\"b\"\t0.41040709263815384\n\"c\"\t0.6600456536439784\n\"d\"\t0.48855379387549824\n\"e\"\t0.48600669271341534".to_string();
assert_eq!(expected, actual.join("\n"));
Ok(())
}
-#[test]
-fn csv_query_group_by_avg_with_projection() -> Result<()> {
+#[tokio::test]
+async fn csv_query_group_by_avg_with_projection() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(c12), c1 FROM aggregate_test_100 GROUP BY c1";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = "0.41040709263815384\t\"b\"\n0.48600669271341534\t\"e\"\n0.48754517466109415\t\"a\"\n0.48855379387549824\t\"d\"\n0.6600456536439784\t\"c\"".to_string();
assert_eq!(expected, actual.join("\n"));
Ok(())
}
-#[test]
-fn csv_query_avg_multi_batch() -> Result<()> {
+#[tokio::test]
+async fn csv_query_avg_multi_batch() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(c12) FROM aggregate_test_100";
let plan = ctx.create_logical_plan(&sql).unwrap();
let plan = ctx.optimize(&plan).unwrap();
let plan = ctx.create_physical_plan(&plan).unwrap();
- let results = ctx.collect(plan).unwrap();
+ let results = ctx.collect(plan).await.unwrap();
let batch = &results[0];
let column = batch.column(0);
let array = column.as_any().downcast_ref::<Float64Array>().unwrap();
@@ -377,35 +377,35 @@ fn csv_query_avg_multi_batch() -> Result<()> {
Ok(())
}
-#[test]
-fn csv_query_count() -> Result<()> {
+#[tokio::test]
+async fn csv_query_count() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT count(c12) FROM aggregate_test_100";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "100".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_group_by_int_count() -> Result<()> {
+#[tokio::test]
+async fn csv_query_group_by_int_count() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, count(c12) FROM aggregate_test_100 GROUP BY c1";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = "\"a\"\t21\n\"b\"\t19\n\"c\"\t21\n\"d\"\t18\n\"e\"\t21".to_string();
assert_eq!(expected, actual.join("\n"));
Ok(())
}
-#[test]
-fn csv_query_group_by_string_min_max() -> Result<()> {
+#[tokio::test]
+async fn csv_query_group_by_string_min_max() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, MIN(c12), MAX(c12) FROM aggregate_test_100 GROUP BY c1";
- let mut actual = execute(&mut ctx, sql);
+ let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected =
"\"a\"\t0.02182578039211991\t0.9800193410444061\n\"b\"\t0.04893135681998029\t0.9185813970744787\n\"c\"\t0.0494924465469434\t0.991517828651004\n\"d\"\t0.061029375346466685\t0.9748360509016578\n\"e\"\t0.01479305307777301\t0.9965400387585364".to_string();
@@ -413,133 +413,133 @@ fn csv_query_group_by_string_min_max() -> Result<()> {
Ok(())
}
-#[test]
-fn csv_query_cast() -> Result<()> {
+#[tokio::test]
+async fn csv_query_cast() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT CAST(c12 AS float) FROM aggregate_test_100 WHERE c12 > 0.376 AND c12 < 0.4";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "0.39144436569161134\n0.38870280983958583".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_cast_literal() -> Result<()> {
+#[tokio::test]
+async fn csv_query_cast_literal() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c12, CAST(1 AS float) FROM aggregate_test_100 WHERE c12 > CAST(0 AS float) LIMIT 2";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "0.9294097332465232\t1.0\n0.3114712539863804\t1.0".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_limit() -> Result<()> {
+#[tokio::test]
+async fn csv_query_limit() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1 FROM aggregate_test_100 LIMIT 2";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "\"c\"\n\"d\"".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_limit_bigger_than_nbr_of_rows() -> Result<()> {
+#[tokio::test]
+async fn csv_query_limit_bigger_than_nbr_of_rows() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c2 FROM aggregate_test_100 LIMIT 200";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "2\n5\n1\n1\n5\n4\n3\n3\n1\n4\n1\n4\n3\n2\n1\n1\n2\n1\n3\n2\n4\n1\n5\n4\n2\n1\n4\n5\n2\n3\n4\n2\n1\n5\n3\n1\n2\n3\n3\n3\n2\n4\n1\n3\n2\n5\n2\n1\n4\n1\n4\n2\n5\n4\n2\n3\n4\n4\n4\n5\n4\n2\n1\n2\n4\n2\n3\n5\n1\n1\n4\n2\n1\n2\n1\n1\n5\n4\n5\n2\n3\n2\n4\n1\n3\n4\n3\n2\n5\n3\n3\n2\n5\n5\n4\n1\n3\n3\n4\n4".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_limit_with_same_nbr_of_rows() -> Result<()> {
+#[tokio::test]
+async fn csv_query_limit_with_same_nbr_of_rows() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c2 FROM aggregate_test_100 LIMIT 100";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "2\n5\n1\n1\n5\n4\n3\n3\n1\n4\n1\n4\n3\n2\n1\n1\n2\n1\n3\n2\n4\n1\n5\n4\n2\n1\n4\n5\n2\n3\n4\n2\n1\n5\n3\n1\n2\n3\n3\n3\n2\n4\n1\n3\n2\n5\n2\n1\n4\n1\n4\n2\n5\n4\n2\n3\n4\n4\n4\n5\n4\n2\n1\n2\n4\n2\n3\n5\n1\n1\n4\n2\n1\n2\n1\n1\n5\n4\n5\n2\n3\n2\n4\n1\n3\n4\n3\n2\n5\n3\n3\n2\n5\n5\n4\n1\n3\n3\n4\n4".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_limit_zero() -> Result<()> {
+#[tokio::test]
+async fn csv_query_limit_zero() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1 FROM aggregate_test_100 LIMIT 0";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn csv_query_create_external_table() {
+#[tokio::test]
+async fn csv_query_create_external_table() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "SELECT c1, c2, c3, c4, c5, c6, c7, c8, c9, 10, c11, c12, c13 FROM aggregate_test_100 LIMIT 1";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "\"c\"\t2\t1\t18109\t2033001162\t-6513304855495910254\t25\t43062\t1491205016\t10\t0.110830784\t0.9294097332465232\t\"6WfVFBVGJSQb7FhA7E0lBwdvjfZnSW\"".to_string();
assert_eq!(expected, actual);
}
-#[test]
-fn csv_query_external_table_count() {
+#[tokio::test]
+async fn csv_query_external_table_count() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "SELECT COUNT(c12) FROM aggregate_test_100";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "100".to_string();
assert_eq!(expected, actual);
}
-#[test]
-fn csv_query_count_star() {
+#[tokio::test]
+async fn csv_query_count_star() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "SELECT COUNT(*) FROM aggregate_test_100";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "100".to_string();
assert_eq!(expected, actual);
}
-#[test]
-fn csv_query_count_one() {
+#[tokio::test]
+async fn csv_query_count_one() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "SELECT COUNT(1) FROM aggregate_test_100";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "100".to_string();
assert_eq!(expected, actual);
}
-#[test]
-fn csv_explain() {
+#[tokio::test]
+async fn csv_explain() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "EXPLAIN SELECT c1 FROM aggregate_test_100 where c2 > 10";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "\"logical_plan\"\t\"Projection: #c1\\n Filter: #c2 Gt Int64(10)\\n TableScan: aggregate_test_100 projection=None\"".to_string();
assert_eq!(expected, actual);
// Also, expect same result with lowercase explain
let sql = "explain SELECT c1 FROM aggregate_test_100 where c2 > 10";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
assert_eq!(expected, actual);
}
-#[test]
-fn csv_explain_verbose() {
+#[tokio::test]
+async fn csv_explain_verbose() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "EXPLAIN VERBOSE SELECT c1 FROM aggregate_test_100 where c2 > 10";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
// Don't actually test the contents of the debuging output (as
// that may change and keeping this test updated will be a
// pain). Instead just check for a few key pieces.
@@ -566,7 +566,7 @@ fn aggr_test_schema() -> SchemaRef {
]))
}
-fn register_aggregate_csv_by_sql(ctx: &mut ExecutionContext) {
+async fn register_aggregate_csv_by_sql(ctx: &mut ExecutionContext) {
let testdata = env::var("ARROW_TEST_DATA").expect("ARROW_TEST_DATA not defined");
// TODO: The following c9 should be migrated to UInt32 and c10 should be UInt64 once
@@ -599,7 +599,7 @@ fn register_aggregate_csv_by_sql(ctx: &mut ExecutionContext) {
// Mimic the CLI and execute the resulting plan -- even though it
// is effectively a no-op (returns zero rows)
- let results = df.collect().expect("Executing CREATE EXTERNAL TABLE");
+ let results = df.collect().await.expect("Executing CREATE EXTERNAL TABLE");
assert!(
results.is_empty(),
"Expected no rows from executing CREATE EXTERNAL TABLE"
@@ -627,14 +627,14 @@ fn register_alltypes_parquet(ctx: &mut ExecutionContext) {
}
/// Execute query and return result set as tab delimited string
-fn execute(ctx: &mut ExecutionContext, sql: &str) -> Vec<String> {
+async fn execute(ctx: &mut ExecutionContext, sql: &str) -> Vec<String> {
let plan = ctx.create_logical_plan(&sql).unwrap();
let logical_schema = plan.schema();
let plan = ctx.optimize(&plan).unwrap();
let optimized_logical_schema = plan.schema();
let plan = ctx.create_physical_plan(&plan).unwrap();
let physical_schema = plan.schema();
- let results = ctx.collect(plan).unwrap();
+ let results = ctx.collect(plan).await.unwrap();
assert_eq!(logical_schema.as_ref(), optimized_logical_schema.as_ref());
assert_eq!(logical_schema.as_ref(), physical_schema.as_ref());
@@ -732,8 +732,8 @@ fn result_str(results: &[RecordBatch]) -> Vec<String> {
result
}
-#[test]
-fn query_length() -> Result<()> {
+#[tokio::test]
+async fn query_length() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Utf8, false)]));
let data = RecordBatch::try_new(
@@ -746,14 +746,14 @@ fn query_length() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Box::new(table));
let sql = "SELECT length(c1) FROM test";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "0\n1\n2\n3".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn query_not() -> Result<()> {
+#[tokio::test]
+async fn query_not() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Boolean, true)]));
let data = RecordBatch::try_new(
@@ -770,14 +770,14 @@ fn query_not() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Box::new(table));
let sql = "SELECT NOT c1 FROM test";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "true\nNULL\nfalse".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn query_concat() -> Result<()> {
+#[tokio::test]
+async fn query_concat() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("c1", DataType::Utf8, false),
Field::new("c2", DataType::Int32, true),
@@ -796,14 +796,14 @@ fn query_concat() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Box::new(table));
let sql = "SELECT concat(c1, '-hi-', cast(c2 as varchar)) FROM test";
- let actual = execute(&mut ctx, sql);
+ let actual = execute(&mut ctx, sql).await;
let expected = vec!["\"-hi-0\"", "\"a-hi-1\"", "NULL", "\"aaa-hi-3\""];
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn query_array() -> Result<()> {
+#[tokio::test]
+async fn query_array() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("c1", DataType::Utf8, false),
Field::new("c2", DataType::Int32, true),
@@ -822,7 +822,7 @@ fn query_array() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Box::new(table));
let sql = "SELECT array(c1, cast(c2 as varchar)) FROM test";
- let actual = execute(&mut ctx, sql);
+ let actual = execute(&mut ctx, sql).await;
let expected = vec![
"[\"\",\"0\"]",
"[\"a\",\"1\"]",
@@ -833,23 +833,23 @@ fn query_array() -> Result<()> {
Ok(())
}
-#[test]
-fn csv_query_sum_cast() {
+#[tokio::test]
+async fn csv_query_sum_cast() {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
// c8 = i32; c9 = i64
let sql = "SELECT c8 + c9 FROM aggregate_test_100";
// check that the physical and logical schemas are equal
- execute(&mut ctx, sql);
+ execute(&mut ctx, sql).await;
}
-#[test]
-fn like() -> Result<()> {
+#[tokio::test]
+async fn like() -> Result<()> {
let mut ctx = ExecutionContext::new();
- register_aggregate_csv_by_sql(&mut ctx);
+ register_aggregate_csv_by_sql(&mut ctx).await;
let sql = "SELECT COUNT(c1) FROM aggregate_test_100 WHERE c13 LIKE '%FB%'";
// check that the physical and logical schemas are equal
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "1".to_string();
assert_eq!(expected, actual);
@@ -879,21 +879,21 @@ fn make_timestamp_nano_table() -> Result<Box<MemTable>> {
Ok(Box::new(table))
}
-#[test]
-fn to_timstamp() -> Result<()> {
+#[tokio::test]
+async fn to_timstamp() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("ts_data", make_timestamp_nano_table()?);
let sql = "SELECT COUNT(*) FROM ts_data where ts > to_timestamp('2020-09-08T12:00:00+00:00')";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "2".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn query_is_null() -> Result<()> {
+#[tokio::test]
+async fn query_is_null() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Float64, true)]));
let data = RecordBatch::try_new(
@@ -910,14 +910,14 @@ fn query_is_null() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Box::new(table));
let sql = "SELECT c1 IS NULL FROM test";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "false\ntrue\nfalse".to_string();
assert_eq!(expected, actual);
Ok(())
}
-#[test]
-fn query_is_not_null() -> Result<()> {
+#[tokio::test]
+async fn query_is_not_null() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Float64, true)]));
let data = RecordBatch::try_new(
@@ -934,7 +934,7 @@ fn query_is_not_null() -> Result<()> {
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Box::new(table));
let sql = "SELECT c1 IS NOT NULL FROM test";
- let actual = execute(&mut ctx, sql).join("\n");
+ let actual = execute(&mut ctx, sql).await.join("\n");
let expected = "true\nfalse\ntrue".to_string();
assert_eq!(expected, actual);
Ok(())
diff --git a/rust/datafusion/tests/user_defined_plan.rs b/rust/datafusion/tests/user_defined_plan.rs
index c956d58891..aa55238c16 100644
--- a/rust/datafusion/tests/user_defined_plan.rs
+++ b/rust/datafusion/tests/user_defined_plan.rs
@@ -86,21 +86,23 @@ use std::{
sync::{Arc, Mutex},
};
+use async_trait::async_trait;
+
/// Execute the specified sql and return the resulting record batches
/// pretty printed as a String.
-fn exec_sql(ctx: &mut ExecutionContext, sql: &str) -> Result<String> {
+async fn exec_sql(ctx: &mut ExecutionContext, sql: &str) -> Result<String> {
let df = ctx.sql(sql)?;
- let batches = df.collect()?;
+ let batches = df.collect().await?;
pretty_format_batches(&batches).map_err(|e| ExecutionError::ArrowError(e))
}
/// Create a test table.
-fn setup_table(mut ctx: ExecutionContext) -> Result<ExecutionContext> {
+async fn setup_table(mut ctx: ExecutionContext) -> Result<ExecutionContext> {
let sql = "CREATE EXTERNAL TABLE sales(customer_id VARCHAR, revenue BIGINT) STORED AS CSV location 'tests/customer.csv'";
let expected = vec!["++", "++"];
- let s = exec_sql(&mut ctx, sql)?;
+ let s = exec_sql(&mut ctx, sql).await?;
let actual = s.lines().collect::<Vec<_>>();
assert_eq!(expected, actual, "Creating table");
@@ -112,7 +114,10 @@ const QUERY: &str =
// Run the query using the specified execution context and compare it
// to the known result
-fn run_and_compare_query(mut ctx: ExecutionContext, description: &str) -> Result<()> {
+async fn run_and_compare_query(
+ mut ctx: ExecutionContext,
+ description: &str,
+) -> Result<()> {
let expected = vec![
"+-------------+---------+",
"| customer_id | revenue |",
@@ -123,7 +128,7 @@ fn run_and_compare_query(mut ctx: ExecutionContext, description: &str) -> Result
"+-------------+---------+",
];
- let s = exec_sql(&mut ctx, QUERY)?;
+ let s = exec_sql(&mut ctx, QUERY).await?;
let actual = s.lines().collect::<Vec<_>>();
assert_eq!(
@@ -137,25 +142,25 @@ fn run_and_compare_query(mut ctx: ExecutionContext, description: &str) -> Result
Ok(())
}
-#[test]
+#[tokio::test]
// Run the query using default planners and optimizer
-fn normal_query() -> Result<()> {
- let ctx = setup_table(ExecutionContext::new())?;
- run_and_compare_query(ctx, "Default context")
+async fn normal_query() -> Result<()> {
+ let ctx = setup_table(ExecutionContext::new()).await?;
+ run_and_compare_query(ctx, "Default context").await
}
-#[test]
+#[tokio::test]
// Run the query using topk optimization
-fn topk_query() -> Result<()> {
+async fn topk_query() -> Result<()> {
// Note the only difference is that the top
- let ctx = setup_table(make_topk_context())?;
- run_and_compare_query(ctx, "Topk context")
+ let ctx = setup_table(make_topk_context()).await?;
+ run_and_compare_query(ctx, "Topk context").await
}
-#[test]
+#[tokio::test]
// Run EXPLAIN PLAN and show the plan was in fact rewritten
-fn topk_plan() -> Result<()> {
- let mut ctx = setup_table(make_topk_context())?;
+async fn topk_plan() -> Result<()> {
+ let mut ctx = setup_table(make_topk_context()).await?;
let expected = vec![
"| logical_plan after topk | TopK: k=3 |",
@@ -164,7 +169,7 @@ fn topk_plan() -> Result<()> {
].join("\n");
let explain_query = format!("EXPLAIN VERBOSE {}", QUERY);
- let actual_output = exec_sql(&mut ctx, &explain_query)?;
+ let actual_output = exec_sql(&mut ctx, &explain_query).await?;
// normalize newlines (output on windows uses \r\n)
let actual_output = actual_output.replace("\r\n", "\n");
@@ -354,6 +359,7 @@ impl Debug for TopKExec {
}
}
+#[async_trait]
impl ExecutionPlan for TopKExec {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
@@ -392,7 +398,7 @@ impl ExecutionPlan for TopKExec {
}
/// Execute one partition and return an iterator over RecordBatch
- fn execute(
+ async fn execute(
&self,
partition: usize,
) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
@@ -404,7 +410,7 @@ impl ExecutionPlan for TopKExec {
}
Ok(Arc::new(Mutex::new(TopKReader {
- input: self.input.execute(partition)?,
+ input: self.input.execute(partition).await?,
k: self.k,
top_values: BTreeMap::new(),
done: false,