Apache DataFusion SQL Query Engine
ARROW-5039: [Rust] [DataFusion] Re-implement CAST support
Andy Grovec1693a222269
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex a18d7690f8..1618e6a23d 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -127,7 +127,7 @@ impl ExecutionContext {}/// Optimize the logical plan by applying optimizer rules- fn optimize(&self, plan: &LogicalPlan) -> Result<Arc<LogicalPlan>> {+ pub fn optimize(&self, plan: &LogicalPlan) -> Result<Arc<LogicalPlan>> {let rules: Vec<Box<OptimizerRule>> = vec![Box::new(ProjectionPushDown::new()),Box::new(TypeCoercionRule::new()),diff --git a/rust/datafusion/src/execution/expression.rs b/rust/datafusion/src/execution/expression.rsindex f152a14e80..45adaac08b 100644--- a/rust/datafusion/src/execution/expression.rs+++ b/rust/datafusion/src/execution/expression.rs@@ -15,7 +15,7 @@// specific language governing permissions and limitations// under the License.-//! Runtime expression support+//! Evaluation of expressions against RecordBatch instances.use std::rc::Rc;use std::sync::Arc;@@ -46,7 +46,7 @@ pub enum AggregateType {Avg,}-/// Compiled expression+/// Compiled expression that can be invoked against a RecordBatch to produce an Arraypub(super) struct CompiledExpr {name: String,f: ArrayFunction,@@ -180,7 +180,10 @@ macro_rules! math_ops {(DataType::Float64, DataType::Float64) => {binary_op!(left_values, right_values, $OP, Float64Array)}- _ => Err(ExecutionError::ExecutionError(format!("math_ops"))),+ (l, r) => Err(ExecutionError::ExecutionError(format!(+ "Cannot perform math operation on {:?} and {:?}",+ l, r+ ))),}}};}@@ -220,8 +223,10 @@ macro_rules! comparison_ops {(DataType::Float64, DataType::Float64) => {binary_op!(left_values, right_values, $OP, Float64Array)}- //TODO other types- _ => Err(ExecutionError::ExecutionError(format!("comparison_ops"))),+ (l, r) => Err(ExecutionError::ExecutionError(format!(+ "Cannot compare {:?} with {:?}",+ l, r+ ))),}}};}@@ -285,15 +290,26 @@ pub(super) fn compile_expr(ScalarValue::Float32(n) => literal_array!(n, Float32Array, Float32),ScalarValue::Float64(n) => literal_array!(n, Float64Array, Float64),other => Err(ExecutionError::ExecutionError(format!(- "No support for literal type {:?}",+ "Unsupported literal type {:?}",other))),},- &Expr::Column(index) => Ok(CompiledExpr {- name: input_schema.field(index).name().clone(),- f: Rc::new(move |batch: &RecordBatch| Ok((*batch.column(index)).clone())),- t: input_schema.field(index).data_type().clone(),- }),+ &Expr::Column(index) => {+ if index < input_schema.fields().len() {+ Ok(CompiledExpr {+ name: input_schema.field(index).name().clone(),+ f: Rc::new(move |batch: &RecordBatch| {+ Ok((*batch.column(index)).clone())+ }),+ t: input_schema.field(index).data_type().clone(),+ })+ } else {+ Err(ExecutionError::InvalidColumn(format!(+ "Column index {} out of bounds",+ index+ )))+ }+ }&Expr::Cast {ref expr,ref data_type,@@ -310,40 +326,21 @@ pub(super) fn compile_expr(}),})}- &Expr::Literal(ref value) => {- //NOTE this is all very inefficient and needs to be optimized - tracking- // issue is https://github.com/andygrove/datafusion/issues/191- match value {- ScalarValue::Int64(n) => {- let nn = *n;- match data_type {- DataType::Float64 => Ok(CompiledExpr {- name: "lit".to_string(),- f: Rc::new(move |batch: &RecordBatch| {- let mut b = Float64Array::builder(batch.num_rows());- for _ in 0..batch.num_rows() {- b.append_value(nn as f64)?;- }- Ok(Arc::new(b.finish()) as ArrayRef)- }),- t: data_type.clone(),- }),- other => Err(ExecutionError::NotImplemented(format!(- "CAST from Int64 to {:?}",- other- ))),- }- }- other => Err(ExecutionError::NotImplemented(format!(- "CAST from {:?} to {:?}",- other, data_type- ))),- }+ other => {+ let compiled_expr = compile_expr(ctx, other, input_schema)?;+ let dt = data_type.clone();+ Ok(CompiledExpr {+ name: "CAST".to_string(),+ t: data_type.clone(),+ f: Rc::new(move |batch: &RecordBatch| {+ // evaluate the expression+ let array = compiled_expr.invoke(batch)?;+ // cast the result+ compute::cast(&array, &dt)+ .map_err(|e| ExecutionError::ArrowError(e))+ }),+ })}- other => Err(ExecutionError::General(format!(- "CAST not implemented for expression {:?}",- other- ))),},&Expr::BinaryExpr {ref left,@@ -439,14 +436,14 @@ pub(super) fn compile_expr(}),t: op_type,}),- other => Err(ExecutionError::ExecutionError(format!(- "operator: {:?}",+ other => Err(ExecutionError::NotImplemented(format!(+ "Unsupported operator: {:?}",other))),}}- other => Err(ExecutionError::ExecutionError(format!(- "expression {:?}",+ other => Err(ExecutionError::NotImplemented(format!(+ "Unsupported expression {:?}",other))),}diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 9c64a447a0..6a61eb5d7e 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -89,6 +89,16 @@ fn csv_query_cast() {assert_eq!(expected, actual);}+#[test]+fn csv_query_cast_literal() {+ 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);+ let expected = "0.9294097332465232\t1.0\n0.3114712539863804\t1.0\n".to_string();+ assert_eq!(expected, actual);+}+#[test]fn csv_query_limit() {let mut ctx = ExecutionContext::new();