Apache DataFusion SQL Query Engine
ARROW-7684: [Rust] Example Flight client and server for DataFusion
Andy Grove5960a20f8f0d
diff --git a/dev/release/00-prepare-test.rb b/dev/release/00-prepare-test.rbindex e9894d0bc8..afabe88fa7 100644--- a/dev/release/00-prepare-test.rb+++ b/dev/release/00-prepare-test.rb@@ -276,7 +276,9 @@ class PrepareTest < Test::Unit::TestCase["-arrow = { path = \"../arrow\", version = \"#{@snapshot_version}\" }","-parquet = { path = \"../parquet\", version = \"#{@snapshot_version}\" }","+arrow = { path = \"../arrow\", version = \"#{@release_version}\" }",- "+parquet = { path = \"../parquet\", version = \"#{@release_version}\" }"]+ "+parquet = { path = \"../parquet\", version = \"#{@release_version}\" }"],+ ["-arrow-flight = { path = \"../arrow-flight\", version = \"#{@snapshot_version}\" }",+ "+arrow-flight = { path = \"../arrow-flight\", version = \"#{@release_version}\" }"]],},{@@ -458,7 +460,9 @@ class PrepareTest < Test::Unit::TestCase["-arrow = { path = \"../arrow\", version = \"#{@release_version}\" }","-parquet = { path = \"../parquet\", version = \"#{@release_version}\" }","+arrow = { path = \"../arrow\", version = \"#{@next_snapshot_version}\" }",- "+parquet = { path = \"../parquet\", version = \"#{@next_snapshot_version}\" }"]+ "+parquet = { path = \"../parquet\", version = \"#{@next_snapshot_version}\" }"],+ ["-arrow-flight = { path = \"../arrow-flight\", version = \"#{@release_version}\" }",+ "+arrow-flight = { path = \"../arrow-flight\", version = \"#{@next_snapshot_version}\" }"]],},{diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex 018f8017ce..1a3149aa01 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -56,6 +56,12 @@ crossbeam = "0.7.1"[dev-dependencies]criterion = "0.2.0"tempdir = "0.3.7"+futures = "0.3"+prost = "0.6"+tokio = { version = "0.2", features = ["macros"] }+tonic = "0.1"+flatbuffers = "0.6.0"+arrow-flight = { path = "../arrow-flight", version = "0.16.0-SNAPSHOT" }[[bench]]name = "aggregate_query_sql"diff --git a/rust/datafusion/examples/README.md b/rust/datafusion/examples/README.mdnew file mode 100644index 0000000000..163ef3d952--- /dev/null+++ b/rust/datafusion/examples/README.md@@ -0,0 +1,28 @@+<!---+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+-->++# DataFusion Examples++## Single Process++The examples `csv_sql.rs` and `parquet_sql.rs` demonstrate building a query plan from a SQL statement and then executing the query plan against local CSV and Parquet files, respectively.++## Distributed++The `flight-client.rs` and `flight-server.rs` examples demonstrate how to run DataFusion as a standalone process and execute SQL queries from a client using the Flight protocol.\ No newline at end of filediff --git a/rust/datafusion/examples/flight-client.rs b/rust/datafusion/examples/flight-client.rsnew file mode 100644index 0000000000..97db793462--- /dev/null+++ b/rust/datafusion/examples/flight-client.rs@@ -0,0 +1,62 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use std::convert::TryFrom;+use std::sync::Arc;++use arrow::array::Int32Array;+use arrow::datatypes::Schema;+use arrow::flight::flight_data_to_batch;+use flight::flight_service_client::FlightServiceClient;+use flight::Ticket;++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let mut client = FlightServiceClient::connect("http://localhost:50051").await?;++ let request = tonic::Request::new(Ticket {+ ticket: "SELECT id FROM alltypes_plain".into(),+ });++ let mut stream = client.do_get(request).await?.into_inner();++ // the schema should be the first message returned, else client should error+ let flight_data = stream.message().await?.unwrap();+ // convert FlightData to a stream+ let schema = Arc::new(Schema::try_from(&flight_data)?);+ println!("Schema: {:?}", schema);++ // all the remaining stream messages should be dictionary and record batches+ while let Some(flight_data) = stream.message().await? {+ // the unwrap is infallible and thus safe+ let record_batch = flight_data_to_batch(&flight_data, schema.clone())?.unwrap();++ println!(+ "record_batch has {} columns and {} rows",+ record_batch.num_columns(),+ record_batch.num_rows()+ );+ let column = record_batch.column(0);+ let column = column+ .as_any()+ .downcast_ref::<Int32Array>()+ .expect("Unable to get column");+ println!("Column 1: {:?}", column);+ }++ Ok(())+}diff --git a/rust/datafusion/examples/flight-server.rs b/rust/datafusion/examples/flight-server.rsnew file mode 100644index 0000000000..e6cc22ac50--- /dev/null+++ b/rust/datafusion/examples/flight-server.rs@@ -0,0 +1,174 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use std::pin::Pin;++use futures::Stream;+use tonic::transport::Server;+use tonic::{Request, Response, Status, Streaming};++use datafusion::execution::context::ExecutionContext;++use flight::{+ flight_service_server::FlightService, flight_service_server::FlightServiceServer,+ Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo,+ HandshakeRequest, HandshakeResponse, PutResult, SchemaResult, Ticket,+};++#[derive(Clone)]+pub struct FlightServiceImpl {}++#[tonic::async_trait]+impl FlightService for FlightServiceImpl {+ type HandshakeStream = Pin<+ Box<dyn Stream<Item = Result<HandshakeResponse, Status>> + Send + Sync + 'static>,+ >;+ type ListFlightsStream =+ Pin<Box<dyn Stream<Item = Result<FlightInfo, Status>> + Send + Sync + 'static>>;+ type DoGetStream =+ Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send + Sync + 'static>>;+ type DoPutStream =+ Pin<Box<dyn Stream<Item = Result<PutResult, Status>> + Send + Sync + 'static>>;+ type DoActionStream = Pin<+ Box<dyn Stream<Item = Result<flight::Result, Status>> + Send + Sync + 'static>,+ >;+ type ListActionsStream =+ Pin<Box<dyn Stream<Item = Result<ActionType, Status>> + Send + Sync + 'static>>;++ async fn do_get(+ &self,+ request: Request<Ticket>,+ ) -> Result<Response<Self::DoGetStream>, Status> {+ let ticket = request.into_inner();+ match String::from_utf8(ticket.ticket.to_vec()) {+ Ok(sql) => {+ println!("do_get: {}", sql);++ // create local execution context+ let mut ctx = ExecutionContext::new();++ let testdata = std::env::var("PARQUET_TEST_DATA")+ .expect("PARQUET_TEST_DATA not defined");++ // register parquet file with the execution context+ ctx.register_parquet(+ "alltypes_plain",+ &format!("{}/alltypes_plain.parquet", testdata),+ )+ .map_err(|e| to_tonic_err(&e))?;++ // create the query plan+ let plan = ctx+ .create_logical_plan(&sql)+ .and_then(|plan| ctx.optimize(&plan))+ .and_then(|plan| ctx.create_physical_plan(&plan, 1024 * 1024))+ .map_err(|e| to_tonic_err(&e))?;++ // execute the query+ let results = ctx.collect(plan.as_ref()).map_err(|e| to_tonic_err(&e))?;+ if results.is_empty() {+ return Err(Status::internal("There were no results from ticket"));+ }++ // add an initial FlightData message that sends schema+ let schema = plan.schema();+ let mut flights: Vec<Result<FlightData, Status>> =+ vec![Ok(FlightData::from(schema.as_ref()))];++ let mut batches: Vec<Result<FlightData, Status>> = results+ .iter()+ .map(|batch| Ok(FlightData::from(batch)))+ .collect();++ // append batch vector to schema vector, so that the first message sent is the schema+ flights.append(&mut batches);++ let output = futures::stream::iter(flights);++ Ok(Response::new(Box::pin(output) as Self::DoGetStream))+ }+ Err(e) => Err(Status::invalid_argument(format!("Invalid ticket: {:?}", e))),+ }+ }++ async fn handshake(+ &self,+ _request: Request<Streaming<HandshakeRequest>>,+ ) -> Result<Response<Self::HandshakeStream>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }++ async fn list_flights(+ &self,+ _request: Request<Criteria>,+ ) -> Result<Response<Self::ListFlightsStream>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }++ async fn get_flight_info(+ &self,+ _request: Request<FlightDescriptor>,+ ) -> Result<Response<FlightInfo>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }++ async fn get_schema(+ &self,+ _request: Request<FlightDescriptor>,+ ) -> Result<Response<SchemaResult>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }++ async fn do_put(+ &self,+ _request: Request<Streaming<FlightData>>,+ ) -> Result<Response<Self::DoPutStream>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }++ async fn do_action(+ &self,+ _request: Request<Action>,+ ) -> Result<Response<Self::DoActionStream>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }++ async fn list_actions(+ &self,+ _request: Request<Empty>,+ ) -> Result<Response<Self::ListActionsStream>, Status> {+ Err(Status::unimplemented("Not yet implemented"))+ }+}++fn to_tonic_err(e: &datafusion::error::ExecutionError) -> Status {+ Status::internal(format!("{:?}", e))+}++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let addr = "0.0.0.0:50051".parse()?;+ let service = FlightServiceImpl {};++ let svc = FlightServiceServer::new(service);++ println!("Listening on {:?}", addr);++ Server::builder().add_service(svc).serve(addr).await?;++ Ok(())+}