Apache DataFusion SQL Query Engine
Add NULL literal support for decimal and integers (#5077)
Nuttiiya Seekhao7d2318b359f0
diff --git a/datafusion/substrait/src/consumer.rs b/datafusion/substrait/src/consumer.rsindex a650592d56..e7303e21cd 100644--- a/datafusion/substrait/src/consumer.rs+++ b/datafusion/substrait/src/consumer.rs@@ -38,11 +38,11 @@ use substrait::proto::{},extensions::simple_extension_declaration::MappingType,function_argument::ArgType,- join_rel, plan_rel,+ join_rel, plan_rel, r#type,read_rel::ReadType,rel::RelType,sort_field::{SortDirection, SortKind::*},- AggregateFunction, Expression, Plan, Rel,+ AggregateFunction, Expression, Plan, Rel, Type,};use datafusion::logical_expr::expr::Sort;@@ -78,7 +78,7 @@ pub fn name_to_op(name: &str) -> Result<Operator> {"bitwise_shift_right" => Ok(Operator::BitwiseShiftRight),"bitwise_shift_left" => Ok(Operator::BitwiseShiftLeft),_ => Err(DataFusionError::NotImplemented(format!(- "Unsupported function name: {name:?}",+ "Unsupported function name: {name:?}"))),}}@@ -98,7 +98,7 @@ pub async fn from_substrait_plan(Ok((ext_f.function_anchor, &ext_f.name))}_ => Err(DataFusionError::NotImplemented(format!(- "Extension type not supported: {ext:?}",+ "Extension type not supported: {ext:?}"))),},None => Err(DataFusionError::NotImplemented(@@ -429,13 +429,13 @@ fn from_substrait_jointype(join_type: i32) -> Result<JoinType> {join_rel::JoinType::Semi => Ok(JoinType::LeftSemi),_ => {return Err(DataFusionError::Internal(format!(- "unsupported join type {substrait_join_type:?}",+ "unsupported join type {substrait_join_type:?}")))}}} else {return Err(DataFusionError::Internal(format!(- "invalid join type variant {join_type:?}",+ "invalid join type variant {join_type:?}")));}}@@ -597,7 +597,7 @@ pub async fn from_substrait_rex(})))}(l, r) => Err(DataFusionError::NotImplemented(format!(- "Invalid arguments for binary expression: {l:?} and {r:?}",+ "Invalid arguments for binary expression: {l:?} and {r:?}"))),}}@@ -635,12 +635,12 @@ pub async fn from_substrait_rex())?;let p = d.precision.try_into().map_err(|e| {DataFusionError::Substrait(format!(- "Failed to parse decimal precision: {e}",+ "Failed to parse decimal precision: {e}"))})?;let s = d.scale.try_into().map_err(|e| {DataFusionError::Substrait(format!(- "Failed to parse decimal scale: {e}",+ "Failed to parse decimal scale: {e}"))})?;Ok(Arc::new(Expr::Literal(ScalarValue::Decimal128(@@ -655,6 +655,9 @@ pub async fn from_substrait_rex(Some(LiteralType::Binary(b)) => Ok(Arc::new(Expr::Literal(ScalarValue::Binary(Some(b.clone())),))),+ Some(LiteralType::Null(ntype)) => {+ Ok(Arc::new(Expr::Literal(from_substrait_null(ntype)?)))+ }_ => {return Err(DataFusionError::NotImplemented(format!("Unsupported literal_type: {:?}",@@ -668,3 +671,26 @@ pub async fn from_substrait_rex()),}}++fn from_substrait_null(null_type: &Type) -> Result<ScalarValue> {+ if let Some(kind) = &null_type.kind {+ match kind {+ r#type::Kind::I8(_) => Ok(ScalarValue::Int8(None)),+ r#type::Kind::I16(_) => Ok(ScalarValue::Int16(None)),+ r#type::Kind::I32(_) => Ok(ScalarValue::Int32(None)),+ r#type::Kind::I64(_) => Ok(ScalarValue::Int64(None)),+ r#type::Kind::Decimal(d) => Ok(ScalarValue::Decimal128(+ None,+ d.precision as u8,+ d.scale as i8,+ )),+ _ => Err(DataFusionError::NotImplemented(format!(+ "Unsupported null kind: {kind:?}"+ ))),+ }+ } else {+ Err(DataFusionError::NotImplemented(+ "Null type without kind is not supported".to_string(),+ ))+ }+}diff --git a/datafusion/substrait/src/producer.rs b/datafusion/substrait/src/producer.rsindex 0b05f1dc14..3a9c4923b7 100644--- a/datafusion/substrait/src/producer.rs+++ b/datafusion/substrait/src/producer.rs@@ -45,7 +45,7 @@ use substrait::proto::{simple_extension_declaration::{ExtensionFunction, MappingType},},function_argument::ArgType,- join_rel, plan_rel,+ join_rel, plan_rel, r#type,read_rel::{NamedTable, ReadType},rel::RelType,sort_field::{SortDirection, SortKind},@@ -297,7 +297,7 @@ pub fn to_substrait_rel(to_substrait_rel(alias.input.as_ref(), extension_info)}_ => Err(DataFusionError::NotImplemented(format!(- "Unsupported operator: {plan:?}",+ "Unsupported operator: {plan:?}"))),}}@@ -380,9 +380,14 @@ pub fn to_substrait_agg_measure(None => None}})- },+ }+ Expr::Alias(expr, _name) => {+ to_substrait_agg_measure(expr, schema, extension_info)+ }_ => Err(DataFusionError::Internal(format!(- "Expression must be compatible with aggregation. Unsupported expression: {expr:?}",+ "Expression must be compatible with aggregation. Unsupported expression: {:?}. ExpressionType: {:?}",+ expr,+ expr.variant_name()))),}}@@ -589,11 +594,7 @@ pub fn to_substrait_rex(ScalarValue::Binary(Some(b)) => Some(LiteralType::Binary(b.clone())),ScalarValue::LargeBinary(Some(b)) => Some(LiteralType::Binary(b.clone())),ScalarValue::Date32(Some(d)) => Some(LiteralType::Date(*d)),- _ => {- return Err(DataFusionError::NotImplemented(format!(- "Unsupported literal: {value:?}",- )))- }+ _ => Some(try_to_substrait_null(value)?),};Ok(Expression {rex_type: Some(RexType::Literal(Literal {@@ -610,6 +611,51 @@ pub fn to_substrait_rex(}}+fn try_to_substrait_null(v: &ScalarValue) -> Result<LiteralType> {+ let default_type_ref = 0;+ let default_nullability = r#type::Nullability::Nullable as i32;+ match v {+ ScalarValue::Int8(None) => Ok(LiteralType::Null(substrait::proto::Type {+ kind: Some(r#type::Kind::I8(r#type::I8 {+ type_variation_reference: default_type_ref,+ nullability: default_nullability,+ })),+ })),+ ScalarValue::Int16(None) => Ok(LiteralType::Null(substrait::proto::Type {+ kind: Some(r#type::Kind::I16(r#type::I16 {+ type_variation_reference: default_type_ref,+ nullability: default_nullability,+ })),+ })),+ ScalarValue::Int32(None) => Ok(LiteralType::Null(substrait::proto::Type {+ kind: Some(r#type::Kind::I32(r#type::I32 {+ type_variation_reference: default_type_ref,+ nullability: default_nullability,+ })),+ })),+ ScalarValue::Int64(None) => Ok(LiteralType::Null(substrait::proto::Type {+ kind: Some(r#type::Kind::I64(r#type::I64 {+ type_variation_reference: default_type_ref,+ nullability: default_nullability,+ })),+ })),+ ScalarValue::Decimal128(None, p, s) => {+ Ok(LiteralType::Null(substrait::proto::Type {+ kind: Some(r#type::Kind::Decimal(r#type::Decimal {+ scale: *s as i32,+ precision: *p as i32,+ type_variation_reference: default_type_ref,+ nullability: default_nullability,+ })),+ }))+ }+ // TODO: Extend support for remaining data types+ _ => Err(DataFusionError::NotImplemented(format!(+ "Unsupported literal: {v:?}"+ ))),+ }+}+fn substrait_sort_field(expr: &Expr,schema: &DFSchemaRef,diff --git a/datafusion/substrait/tests/roundtrip.rs b/datafusion/substrait/tests/roundtrip.rsindex febc08ac7c..0ddde17549 100644--- a/datafusion/substrait/tests/roundtrip.rs+++ b/datafusion/substrait/tests/roundtrip.rs@@ -100,6 +100,11 @@ mod tests {roundtrip("SELECT * FROM data WHERE b > 2.5").await}+ #[tokio::test]+ async fn null_decimal_literal() -> Result<()> {+ roundtrip("SELECT * FROM data WHERE b = NULL").await+ }+#[tokio::test]async fn simple_distinct() -> Result<()> {test_alias(@@ -170,6 +175,17 @@ mod tests {.await}+ #[tokio::test]+ async fn aggregate_case() -> Result<()> {+ assert_expected_plan(+ "SELECT SUM(CASE WHEN a > 0 THEN 1 ELSE NULL END) FROM data",+ "Projection: SUM(CASE WHEN data.a > Int64(0) THEN Int64(1) ELSE Int64(NULL) END)\+ \n Aggregate: groupBy=[[]], aggr=[[SUM(CASE WHEN data.a > Int64(0) THEN Int64(1) ELSE Int64(NULL) END)]]\+ \n TableScan: data projection=[a]",+ )+ .await+ }+#[tokio::test]async fn roundtrip_inner_join() -> Result<()> {roundtrip("SELECT data.a FROM data JOIN data2 ON data.a = data2.a").await@@ -304,9 +320,9 @@ mod tests {Field::new("d", DataType::Boolean, true),]);explicit_options.schema = Some(&schema);- ctx.register_csv("data", "tests/testdata/data.csv", explicit_options.clone())+ ctx.register_csv("data", "tests/testdata/data.csv", explicit_options).await?;- ctx.register_csv("data2", "tests/testdata/data.csv", explicit_options)+ ctx.register_csv("data2", "tests/testdata/data.csv", CsvReadOptions::new()).await?;Ok(ctx)}