You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "waynexia (via GitHub)" <gi...@apache.org> on 2023/04/10 08:43:20 UTC

[GitHub] [arrow-datafusion] waynexia commented on a diff in pull request #5775: feat: extend substrait type support, including type variations

waynexia commented on code in PR #5775:
URL: https://github.com/apache/arrow-datafusion/pull/5775#discussion_r1161550000


##########
datafusion/substrait/tests/roundtrip_logical_plan.rs:
##########
@@ -333,6 +405,23 @@ mod tests {
         Ok(())
     }
 
+    async fn roundtrip_all_types(sql: &str) -> Result<()> {

Review Comment:
   It works! I rewrite this case. But only a few SQL types are supported for now (I guess they are defined in [this function](https://github.com/apache/arrow-datafusion/blob/524a3c534a9307e9d29ba5bf8aed2d2a70ae68e6/datafusion/sql/src/planner.rs#L278)).



##########
datafusion/substrait/src/lib.rs:
##########
@@ -18,6 +18,7 @@
 pub mod logical_plan;
 pub mod physical_plan;
 pub mod serializer;
+mod variation_const;

Review Comment:
   Good catch!



##########
datafusion/substrait/src/variation_const.rs:
##########
@@ -0,0 +1,31 @@
+// 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.
+
+//! Type variation constants
+
+pub const DEFAULT_TYPE_REF: u32 = 0;

Review Comment:
   Good idea. I add some documents and links to mod-level documentation.



##########
datafusion/substrait/src/logical_plan/consumer.rs:
##########
@@ -910,20 +908,196 @@ fn from_substrait_bound(
     }
 }
 
+fn from_substrait_literal(lit: &Literal) -> Result<ScalarValue> {
+    let scalar_value = match &lit.literal_type {
+        Some(LiteralType::Boolean(b)) => ScalarValue::Boolean(Some(*b)),
+        Some(LiteralType::I8(n)) => match lit.type_variation_reference {
+            DEFAULT_TYPE_REF => ScalarValue::Int8(Some(*n as i8)),
+            UNSIGNED_INTEGER_TYPE_REF => ScalarValue::UInt8(Some(*n as u8)),
+            others => {
+                return Err(DataFusionError::Substrait(format!(
+                    "Unknown type variation reference {others}",
+                )));
+            }
+        },
+        Some(LiteralType::I16(n)) => match lit.type_variation_reference {
+            DEFAULT_TYPE_REF => ScalarValue::Int16(Some(*n as i16)),
+            UNSIGNED_INTEGER_TYPE_REF => ScalarValue::UInt16(Some(*n as u16)),
+            others => {
+                return Err(DataFusionError::Substrait(format!(
+                    "Unknown type variation reference {others}",
+                )));
+            }
+        },
+        Some(LiteralType::I32(n)) => match lit.type_variation_reference {
+            DEFAULT_TYPE_REF => ScalarValue::Int32(Some(*n)),
+            UNSIGNED_INTEGER_TYPE_REF => ScalarValue::UInt32(Some(unsafe {

Review Comment:
   >it is perfectly safe to cast i32 to u32
   
   This is because the "producer" (encoder) transmutes u32 to i32, which changes the actual number. E.g., when encoding an u32::MAX. Thus here we should also transmute back to get the original value.
   
   These transmutations are dangerous and not straightforward. What do you think about replacing them with this [`cast`](https://docs.rs/bytemuck/1.13.1/bytemuck/) method? Though it's also a `transmute` underlying, it would make the code looks more concrete like the following, and I believe those type annotations (`::<u32,i32>`) can be omitted.
   ```rust
   // producer
   ScalarValue::UInt32(Some(n)) => LiteralType::I32(cast::<u32,i32>(n)}),
   
   // consumer
   UNSIGNED_INTEGER_TYPE_REF => ScalarValue::UInt32(Some(cast::<i32,u32>(n))),
   ```



##########
datafusion/substrait/tests/roundtrip_logical_plan.rs:
##########
@@ -373,4 +462,52 @@ mod tests {
             .await?;
         Ok(ctx)
     }
+
+    /// Cover all supported types
+    async fn create_all_type_context() -> Result<SessionContext> {
+        let ctx = SessionContext::new();
+        let mut explicit_options = CsvReadOptions::new();
+        let schema = Schema::new(vec![
+            Field::new("a", DataType::Boolean, true),

Review Comment:
   Thanks for the suggestion, it looks cleaner now 👍 



##########
datafusion/substrait/tests/roundtrip_logical_plan.rs:
##########
@@ -262,7 +262,79 @@ mod tests {
 
     #[tokio::test]
     async fn qualified_catalog_schema_table_reference() -> Result<()> {
-        roundtrip("SELECT * FROM datafusion.public.data;").await
+        roundtrip("SELECT a,b,c,d,e FROM datafusion.public.data;").await
+    }
+
+    #[tokio::test]
+    async fn read_all_types() -> Result<()> {
+        let mut ctx = create_all_type_context().await?;
+        let df = ctx
+            .sql(
+                "select * from data where 
+                a = TRUE AND
+                b = 0 AND
+                c = 0 AND
+                d = 0 AND
+                e = 0 AND
+                f = 0 AND
+                g = 0 AND
+                h = 0 AND
+                i = 0;",
+            )
+            .await?;
+        println!("{:?}", df.clone().collect().await.unwrap());
+        let plan = df.into_optimized_plan()?;
+        let proto = to_substrait_plan(&plan)?;
+        let plan2 = from_substrait_plan(&mut ctx, &proto).await?;
+        let plan2 = ctx.state().optimize(&plan2)?;
+
+        println!("{plan:#?}");
+        println!("{plan2:#?}");
+
+        let plan1str = format!("{plan:?}");
+        let plan2str = format!("{plan2:?}");
+        assert_eq!(plan1str, plan2str);
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn integer_type_literal() -> Result<()> {
+        roundtrip_all_types(
+            "select * from data where 
+            a = TRUE AND
+            b = 0 AND
+            c = 0 AND
+            d = 0 AND
+            e = 0 AND
+            f = 0 AND
+            g = 0 AND
+            h = 0 AND
+            i = 0;",
+        )
+        .await
+    }
+
+    // Literal in this cases have incorrect type. This is not a good case
+    #[tokio::test]
+    async fn other_type_literal() -> Result<()> {

Review Comment:
   TIL, thanks for your help!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org