Apache DataFusion SQL Query Engine
ARROW-10865: [Rust] Easier to use Schema -> DFSchema conversion
Andrew Lambfc8b4f4e21cc
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 8e62ac392c..2ecccb7728 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -35,7 +35,7 @@ use crate::datasource::TableProvider;use crate::error::{DataFusionError, Result};use crate::execution::dataframe_impl::DataFrameImpl;use crate::logical_plan::{- DFSchema, DFSchemaRef, FunctionRegistry, LogicalPlan, LogicalPlanBuilder, TableSource,+ FunctionRegistry, LogicalPlan, LogicalPlanBuilder, TableSource, ToDFSchema,};use crate::optimizer::filter_push_down::FilterPushDown;use crate::optimizer::optimizer::OptimizerRule;@@ -230,7 +230,7 @@ impl ExecutionContext {schema_name: "".to_string(),source: TableSource::FromProvider(provider),table_schema: schema.clone(),- projected_schema: DFSchemaRef::new(DFSchema::from(&schema)?),+ projected_schema: schema.to_dfschema_ref()?,projection: None,};Ok(Arc::new(DataFrameImpl::new(@@ -282,7 +282,7 @@ impl ExecutionContext {schema_name: "".to_string(),source: TableSource::FromContext(table_name.to_string()),table_schema: schema.clone(),- projected_schema: DFSchemaRef::new(DFSchema::from(&schema)?),+ projected_schema: schema.to_dfschema_ref()?,projection: None,};Ok(Arc::new(DataFrameImpl::new(diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex f20feb0cae..942de72388 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -31,6 +31,7 @@ use crate::{prelude::CsvReadOptions,};+use super::dfschema::ToDFSchema;use super::{col, exprlist_to_fields, Expr, JoinType, LogicalPlan, PlanType, StringifiedPlan,TableSource,@@ -68,9 +69,9 @@ impl LogicalPlanBuilder {let provider = Arc::new(MemTable::try_new(schema.clone(), partitions)?);let projected_schema = projection- .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()));- let projected_schema = projected_schema.map_or(schema.clone(), SchemaRef::new);- let projected_schema = DFSchemaRef::new(DFSchema::from(&projected_schema)?);+ .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))+ .map_or(schema.clone(), SchemaRef::new)+ .to_dfschema_ref()?;let table_scan = LogicalPlan::TableScan {schema_name: "".to_string(),@@ -99,9 +100,8 @@ impl LogicalPlanBuilder {let projected_schema = projection.map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))- .or(Some(schema))- .unwrap();- let projected_schema = DFSchemaRef::new(DFSchema::from(&projected_schema)?);+ .map_or(SchemaRef::new(schema), SchemaRef::new)+ .to_dfschema_ref()?;let provider = Arc::new(CsvFile::try_new(path, options)?);let schema = provider.schema();@@ -123,9 +123,9 @@ impl LogicalPlanBuilder {let schema = provider.schema();let projected_schema = projection- .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()));- let projected_schema = projected_schema.map_or(schema.clone(), SchemaRef::new);- let projected_schema = DFSchemaRef::new(DFSchema::from(&projected_schema)?);+ .map(|p| Schema::new(p.iter().map(|i| schema.field(*i).clone()).collect()))+ .map_or(schema.clone(), SchemaRef::new)+ .to_dfschema_ref()?;let table_scan = LogicalPlan::TableScan {schema_name: "".to_string(),@@ -156,7 +156,7 @@ impl LogicalPlanBuilder {schema_name: schema_name.to_owned(),source: TableSource::FromContext(table_name.to_owned()),table_schema,- projected_schema: DFSchemaRef::new(DFSchema::from(&projected_schema)?),+ projected_schema: projected_schema.to_dfschema_ref()?,projection,}))}@@ -278,7 +278,7 @@ impl LogicalPlanBuilder {verbose,plan: Arc::new(self.plan.clone()),stringified_plans,- schema: DFSchemaRef::new(DFSchema::from(&schema)?),+ schema: schema.to_dfschema_ref()?,}))}diff --git a/rust/datafusion/src/logical_plan/dfschema.rs b/rust/datafusion/src/logical_plan/dfschema.rsindex d781a0cadc..5d72df833d 100644--- a/rust/datafusion/src/logical_plan/dfschema.rs+++ b/rust/datafusion/src/logical_plan/dfschema.rs@@ -19,6 +19,7 @@//! fields with optional relation names.use std::collections::HashSet;+use std::convert::TryFrom;use std::sync::Arc;use crate::error::{DataFusionError, Result};@@ -89,21 +90,7 @@ impl DFSchema {}/// Create a `DFSchema` from an Arrow schema- pub fn from(schema: &Schema) -> Result<Self> {- Self::new(- schema- .fields()- .iter()- .map(|f| DFField {- field: f.clone(),- qualifier: None,- })- .collect(),- )- }-- /// Create a `DFSchema` from an Arrow schema- pub fn from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> {+ pub fn try_from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> {Self::new(schema.fields()@@ -202,10 +189,11 @@ impl DFSchema {}impl Into<Schema> for DFSchema {+ /// Convert a schema into a DFSchemafn into(self) -> Schema {Schema::new(self.fields- .iter()+ .into_iter().map(|f| {if f.qualifier().is_some() {Field::new(@@ -214,7 +202,7 @@ impl Into<Schema> for DFSchema {f.is_nullable(),)} else {- f.field.clone()+ f.field}}).collect(),@@ -222,12 +210,66 @@ impl Into<Schema> for DFSchema {}}+/// Create a `DFSchema` from an Arrow schema+impl TryFrom<Schema> for DFSchema {+ type Error = DataFusionError;+ fn try_from(schema: Schema) -> std::result::Result<Self, Self::Error> {+ Self::new(+ schema+ .fields()+ .into_iter()+ .map(|f| DFField {+ field: f.clone(),+ qualifier: None,+ })+ .collect(),+ )+ }+}+impl Into<SchemaRef> for DFSchema {fn into(self) -> SchemaRef {SchemaRef::new(self.into())}}+/// Convenience trait to convert Schema like things to DFSchema and DFSchemaRef with fewer keystrokes+pub trait ToDFSchema+where+ Self: Sized,+{+ /// Attempt to create a DSSchema+ fn to_dfschema(self) -> Result<DFSchema>;++ /// Attempt to create a DSSchemaRef+ fn to_dfschema_ref(self) -> Result<DFSchemaRef> {+ Ok(Arc::new(self.to_dfschema()?))+ }+}++impl ToDFSchema for Schema {+ fn to_dfschema(self) -> Result<DFSchema> {+ DFSchema::try_from(self)+ }+}++impl ToDFSchema for SchemaRef {+ fn to_dfschema(self) -> Result<DFSchema> {+ // Attempt to use the Schema directly if there are no other+ // references, otherwise clone+ match Self::try_unwrap(self) {+ Ok(schema) => DFSchema::try_from(schema),+ Err(schemaref) => DFSchema::try_from(schemaref.as_ref().clone()),+ }+ }+}++impl ToDFSchema for Vec<DFField> {+ fn to_dfschema(self) -> Result<DFSchema> {+ DFSchema::new(self)+ }+}+impl Display for DFSchema {fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {write!(@@ -334,21 +376,21 @@ mod tests {#[test]fn from_unqualified_schema() -> Result<()> {- let schema = DFSchema::from(&test_schema_1())?;+ let schema = DFSchema::try_from(test_schema_1())?;assert_eq!("c0, c1", schema.to_string());Ok(())}#[test]fn from_qualified_schema() -> Result<()> {- let schema = DFSchema::from_qualified("t1", &test_schema_1())?;+ let schema = DFSchema::try_from_qualified("t1", &test_schema_1())?;assert_eq!("t1.c0, t1.c1", schema.to_string());Ok(())}#[test]fn from_qualified_schema_into_arrow_schema() -> Result<()> {- let schema = DFSchema::from_qualified("t1", &test_schema_1())?;+ let schema = DFSchema::try_from_qualified("t1", &test_schema_1())?;let arrow_schema: Schema = schema.into();assert_eq!("t1.c0: Boolean, t1.c1: Boolean", arrow_schema.to_string());Ok(())@@ -356,8 +398,8 @@ mod tests {#[test]fn join_qualified() -> Result<()> {- let left = DFSchema::from_qualified("t1", &test_schema_1())?;- let right = DFSchema::from_qualified("t2", &test_schema_1())?;+ let left = DFSchema::try_from_qualified("t1", &test_schema_1())?;+ let right = DFSchema::try_from_qualified("t2", &test_schema_1())?;let join = left.join(&right)?;assert_eq!("t1.c0, t1.c1, t2.c0, t2.c1", join.to_string());// test valid access@@ -372,8 +414,8 @@ mod tests {#[test]fn join_qualified_duplicate() -> Result<()> {- let left = DFSchema::from_qualified("t1", &test_schema_1())?;- let right = DFSchema::from_qualified("t1", &test_schema_1())?;+ let left = DFSchema::try_from_qualified("t1", &test_schema_1())?;+ let right = DFSchema::try_from_qualified("t1", &test_schema_1())?;let join = left.join(&right);assert!(join.is_err());assert_eq!(@@ -386,8 +428,8 @@ mod tests {#[test]fn join_unqualified_duplicate() -> Result<()> {- let left = DFSchema::from(&test_schema_1())?;- let right = DFSchema::from(&test_schema_1())?;+ let left = DFSchema::try_from(test_schema_1())?;+ let right = DFSchema::try_from(test_schema_1())?;let join = left.join(&right);assert!(join.is_err());assert_eq!(@@ -400,8 +442,8 @@ mod tests {#[test]fn join_mixed() -> Result<()> {- let left = DFSchema::from_qualified("t1", &test_schema_1())?;- let right = DFSchema::from(&test_schema_2())?;+ let left = DFSchema::try_from_qualified("t1", &test_schema_1())?;+ let right = DFSchema::try_from(test_schema_2())?;let join = left.join(&right)?;assert_eq!("t1.c0, t1.c1, c100, c101", join.to_string());// test valid access@@ -418,8 +460,8 @@ mod tests {#[test]fn join_mixed_duplicate() -> Result<()> {- let left = DFSchema::from_qualified("t1", &test_schema_1())?;- let right = DFSchema::from(&test_schema_1())?;+ let left = DFSchema::try_from_qualified("t1", &test_schema_1())?;+ let right = DFSchema::try_from(test_schema_1())?;let join = left.join(&right);assert!(join.is_err());assert_eq!(@@ -430,6 +472,37 @@ mod tests {Ok(())}+ #[test]+ fn into() {+ // Demonstrate how to convert back and forth between Schema, SchemaRef, DFSchema, and DFSchemaRef+ let arrow_schema = Schema::new(vec![Field::new("c0", DataType::Int64, true)]);+ let arrow_schema_ref = Arc::new(arrow_schema.clone());++ let df_schema =+ DFSchema::new(vec![DFField::new(None, "c0", DataType::Int64, true)]).unwrap();+ let df_schema_ref = Arc::new(df_schema.clone());++ {+ let arrow_schema = arrow_schema.clone();+ let arrow_schema_ref = arrow_schema_ref.clone();++ assert_eq!(df_schema, arrow_schema.to_dfschema().unwrap());+ assert_eq!(df_schema, arrow_schema_ref.to_dfschema().unwrap());+ }++ {+ let arrow_schema = arrow_schema.clone();+ let arrow_schema_ref = arrow_schema_ref.clone();++ assert_eq!(df_schema_ref, arrow_schema.to_dfschema_ref().unwrap());+ assert_eq!(df_schema_ref, arrow_schema_ref.to_dfschema_ref().unwrap());+ }++ // Now, consume the refs+ assert_eq!(df_schema_ref, arrow_schema.to_dfschema_ref().unwrap());+ assert_eq!(df_schema_ref, arrow_schema_ref.to_dfschema_ref().unwrap());+ }+fn test_schema_1() -> Schema {Schema::new(vec![Field::new("c0", DataType::Boolean, true),diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rsindex 8757014bb8..d6fd5fcfa5 100644--- a/rust/datafusion/src/logical_plan/mod.rs+++ b/rust/datafusion/src/logical_plan/mod.rs@@ -31,7 +31,7 @@ mod plan;mod registry;pub use builder::LogicalPlanBuilder;-pub use dfschema::{DFField, DFSchema, DFSchemaRef};+pub use dfschema::{DFField, DFSchema, DFSchemaRef, ToDFSchema};pub use display::display_schema;pub use expr::{abs, acos, and, array, asin, atan, avg, binary_expr, case, ceil, col, concat, cos,diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex e4571e71bc..72b14bc530 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -19,7 +19,7 @@//! loaded into memoryuse crate::error::{DataFusionError, Result};-use crate::logical_plan::{DFField, DFSchema, DFSchemaRef, LogicalPlan};+use crate::logical_plan::{DFField, DFSchema, DFSchemaRef, LogicalPlan, ToDFSchema};use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::utils;use arrow::datatypes::Schema;@@ -103,10 +103,7 @@ fn get_projected_schema(projected_fields.push(DFField::from(schema.fields()[*i].clone()));}- Ok((- projection,- DFSchemaRef::new(DFSchema::new(projected_fields)?),- ))+ Ok((projection, projected_fields.to_dfschema_ref()?))}/// Recursively transverses the logical plan removing expressions and that are not needed.diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 7248f4c955..a134fa4213 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -24,7 +24,7 @@ use arrow::datatypes::Schema;use super::optimizer::OptimizerRule;use crate::error::{DataFusionError, Result};use crate::logical_plan::{- DFSchema, DFSchemaRef, Expr, LogicalPlan, Operator, PlanType, StringifiedPlan,+ Expr, LogicalPlan, Operator, PlanType, StringifiedPlan, ToDFSchema,};use crate::prelude::{col, lit};use crate::scalar::ScalarValue;@@ -131,7 +131,7 @@ pub fn optimize_explain(verbose,plan,stringified_plans,- schema: DFSchemaRef::new(DFSchema::from(schema)?),+ schema: schema.clone().to_dfschema_ref()?,})}diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex c4c42632f1..a807ed08f6 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -22,8 +22,8 @@ use std::sync::Arc;use crate::logical_plan::Expr::Alias;use crate::logical_plan::{- and, lit, DFSchema, DFSchemaRef, Expr, LogicalPlan, LogicalPlanBuilder, Operator,- PlanType, StringifiedPlan,+ and, lit, DFSchema, Expr, LogicalPlan, LogicalPlanBuilder, Operator, PlanType,+ StringifiedPlan, ToDFSchema,};use crate::scalar::ScalarValue;use crate::{@@ -141,7 +141,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {let schema = self.build_schema(&columns)?;Ok(LogicalPlan::CreateExternalTable {- schema: DFSchemaRef::new(DFSchema::from(&schema)?),+ schema: schema.to_dfschema_ref()?,name: name.clone(),location: location.clone(),file_type: file_type.clone(),@@ -170,7 +170,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {verbose,plan,stringified_plans,- schema: DFSchemaRef::new(DFSchema::from(&schema)?),+ schema: schema.to_dfschema_ref()?,})}diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 57cb8c4625..1ba8c043e3 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -32,7 +32,7 @@ use arrow::{use datafusion::datasource::{csv::CsvReadOptions, MemTable};use datafusion::error::Result;use datafusion::execution::context::ExecutionContext;-use datafusion::logical_plan::{DFSchema, LogicalPlan};+use datafusion::logical_plan::{LogicalPlan, ToDFSchema};use datafusion::prelude::create_udf;#[tokio::test]@@ -1352,7 +1352,7 @@ async fn execute(ctx: &mut ExecutionContext, sql: &str) -> Vec<Vec<String>> {assert_eq!(logical_schema.as_ref(), optimized_logical_schema.as_ref());assert_eq!(logical_schema.as_ref(),- &DFSchema::from(physical_schema.as_ref()).unwrap()+ &physical_schema.to_dfschema().unwrap());result_vec(&results)