You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/11/01 21:54:45 UTC

[GitHub] [arrow-datafusion] waitingkuo commented on a diff in pull request #4069: support `SET` variable

waitingkuo commented on code in PR #4069:
URL: https://github.com/apache/arrow-datafusion/pull/4069#discussion_r1010931287


##########
datafusion/core/src/execution/context.rs:
##########
@@ -341,6 +341,60 @@ impl SessionContext {
                     ))),
                 }
             }
+
+            LogicalPlan::SetVariable(SetVariable {
+                variable, value, ..
+            }) => {
+                let config_options = &self.state.write().config.config_options;
+

Review Comment:
   better refactor this part in the follow on pr once #3909 merged



##########
datafusion/sql/src/planner.rs:
##########
@@ -2451,6 +2458,84 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         self.statement_to_plan(rewrite.pop_front().unwrap())
     }
 
+    fn set_variable_to_plan(
+        &self,
+        local: bool,
+        hivevar: bool,
+        variable: &ObjectName,
+        value: Vec<sqlparser::ast::Expr>,
+    ) -> Result<LogicalPlan> {
+        if local {
+            return Err(DataFusionError::NotImplemented(
+                "LOCAL is not supported".to_string(),
+            ));
+        }
+
+        if hivevar {
+            return Err(DataFusionError::NotImplemented(
+                "HIVEVAR is not supported".to_string(),
+            ));
+        }
+
+        let variable = variable.to_string();
+        let mut variable_lower = variable.to_lowercase();
+
+        if variable_lower == "timezone" || variable_lower == "time.zone" {
+            // we could introduce alias in OptionDefinition if this string matching thing grows
+            variable_lower = "datafusion.execution.time_zone".to_string();
+        }

Review Comment:
   alias `timezone` and `time zone`
   note that `time zone` is converted to `time.zone` during sql parsing



##########
datafusion/sql/src/planner.rs:
##########
@@ -2451,6 +2458,84 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         self.statement_to_plan(rewrite.pop_front().unwrap())
     }
 
+    fn set_variable_to_plan(
+        &self,
+        local: bool,
+        hivevar: bool,
+        variable: &ObjectName,
+        value: Vec<sqlparser::ast::Expr>,
+    ) -> Result<LogicalPlan> {
+        if local {
+            return Err(DataFusionError::NotImplemented(
+                "LOCAL is not supported".to_string(),
+            ));
+        }
+
+        if hivevar {
+            return Err(DataFusionError::NotImplemented(
+                "HIVEVAR is not supported".to_string(),
+            ));
+        }
+
+        let variable = variable.to_string();
+        let mut variable_lower = variable.to_lowercase();
+
+        if variable_lower == "timezone" || variable_lower == "time.zone" {
+            // we could introduce alias in OptionDefinition if this string matching thing grows
+            variable_lower = "datafusion.execution.time_zone".to_string();
+        }
+
+        // we don't support change time zone until we complete time zone related implementation
+        if variable_lower == "datafusion.execution.time_zone" {
+            return Err(DataFusionError::Plan(
+                "Changing Time Zone isn't supported yet".to_string(),
+            ));
+        }
+
+        // parse value string from Expr
+        let value_string = match &value[0] {
+            SQLExpr::Identifier(i) => i.to_string(),
+            SQLExpr::Value(v) => match v {
+                Value::SingleQuotedString(s) => s.to_string(),
+                Value::Number(_, _) | Value::Boolean(_) => v.to_string(),
+                Value::DoubleQuotedString(_)
+                | Value::EscapedStringLiteral(_)
+                | Value::NationalStringLiteral(_)
+                | Value::HexStringLiteral(_)
+                | Value::Null
+                | Value::Placeholder(_) => {
+                    return Err(DataFusionError::Plan(format!(
+                        "Unspported Value {}",
+                        value[0]
+                    )))
+                }
+            },
+            // for capture signed number e.g. +8, -8
+            SQLExpr::UnaryOp { op, expr } => match op {
+                UnaryOperator::Plus => format!("+{}", expr),
+                UnaryOperator::Minus => format!("-{}", expr),

Review Comment:
   to support signed number e.g. +8, -8



##########
datafusion/core/src/execution/context.rs:
##########
@@ -341,6 +341,60 @@ impl SessionContext {
                     ))),
                 }
             }
+
+            LogicalPlan::SetVariable(SetVariable {
+                variable, value, ..
+            }) => {
+                let config_options = &self.state.write().config.config_options;
+
+                let old_value =
+                    config_options.read().get(&variable).ok_or_else(|| {
+                        DataFusionError::Execution(format!(
+                            "Unknown Variable {}",
+                            variable
+                        ))
+                    })?;
+
+                match old_value {
+                    ScalarValue::Boolean(_) => {
+                        let new_value = value.parse::<bool>().map_err(|_| {
+                            DataFusionError::Execution(format!(
+                                "Failed to parse {} as bool",
+                                value,
+                            ))
+                        })?;
+                        config_options.write().set_bool(&variable, new_value);
+                    }
+
+                    ScalarValue::UInt64(_) => {
+                        let new_value = value.parse::<u64>().map_err(|_| {
+                            DataFusionError::Execution(format!(
+                                "Failed to parse {} as u64",
+                                value,
+                            ))
+                        })?;
+                        config_options.write().set_u64(&variable, new_value);
+                    }
+
+                    ScalarValue::Utf8(_) => {
+                        let new_value = value.parse::<String>().map_err(|_| {
+                            DataFusionError::Execution(format!(
+                                "Failed to parse {} as String",
+                                value,
+                            ))
+                        })?;
+                        config_options.write().set_string(&variable, new_value);
+                    }
+
+                    _ => {
+                        return Err(DataFusionError::Execution(
+                            "Unsupported Scalar Value Type".to_string(),
+                        ))
+                    }
+                }

Review Comment:
   not sure whether it's a good way to check the data type. ideally we should use DataType defined in `ConfigDefinition` https://github.com/apache/arrow-datafusion/blob/97f2e4fd5517c762b0862d22b81f957db511e22e/datafusion/core/src/config.rs#L72-L80
   
   but this information is gone once it's been converted to `ConfigOptions`
   https://github.com/apache/arrow-datafusion/blob/97f2e4fd5517c762b0862d22b81f957db511e22e/datafusion/core/src/config.rs#L279-L281



##########
datafusion/core/src/execution/context.rs:
##########
@@ -341,6 +341,60 @@ impl SessionContext {
                     ))),
                 }
             }
+
+            LogicalPlan::SetVariable(SetVariable {
+                variable, value, ..
+            }) => {
+                let config_options = &self.state.write().config.config_options;
+
+                let old_value =
+                    config_options.read().get(&variable).ok_or_else(|| {
+                        DataFusionError::Execution(format!(
+                            "Unknown Variable {}",
+                            variable
+                        ))
+                    })?;

Review Comment:
   return error if variable isn't in config_options



##########
datafusion/sql/src/planner.rs:
##########
@@ -2451,6 +2458,84 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         self.statement_to_plan(rewrite.pop_front().unwrap())
     }
 
+    fn set_variable_to_plan(
+        &self,
+        local: bool,
+        hivevar: bool,
+        variable: &ObjectName,
+        value: Vec<sqlparser::ast::Expr>,
+    ) -> Result<LogicalPlan> {
+        if local {
+            return Err(DataFusionError::NotImplemented(
+                "LOCAL is not supported".to_string(),
+            ));
+        }

Review Comment:
   we don't support `SET LOCAL VARIABLE TO VALUE`



##########
datafusion/sql/src/planner.rs:
##########
@@ -2451,6 +2458,84 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         self.statement_to_plan(rewrite.pop_front().unwrap())
     }
 
+    fn set_variable_to_plan(
+        &self,
+        local: bool,
+        hivevar: bool,
+        variable: &ObjectName,
+        value: Vec<sqlparser::ast::Expr>,
+    ) -> Result<LogicalPlan> {
+        if local {
+            return Err(DataFusionError::NotImplemented(
+                "LOCAL is not supported".to_string(),
+            ));
+        }
+
+        if hivevar {
+            return Err(DataFusionError::NotImplemented(
+                "HIVEVAR is not supported".to_string(),
+            ));
+        }

Review Comment:
   we don't support HIVEVAR. I'm not sure what it is



##########
datafusion/sql/src/planner.rs:
##########
@@ -2451,6 +2458,84 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         self.statement_to_plan(rewrite.pop_front().unwrap())
     }
 
+    fn set_variable_to_plan(
+        &self,
+        local: bool,
+        hivevar: bool,
+        variable: &ObjectName,
+        value: Vec<sqlparser::ast::Expr>,
+    ) -> Result<LogicalPlan> {
+        if local {
+            return Err(DataFusionError::NotImplemented(
+                "LOCAL is not supported".to_string(),
+            ));
+        }
+
+        if hivevar {
+            return Err(DataFusionError::NotImplemented(
+                "HIVEVAR is not supported".to_string(),
+            ));
+        }
+
+        let variable = variable.to_string();
+        let mut variable_lower = variable.to_lowercase();
+
+        if variable_lower == "timezone" || variable_lower == "time.zone" {
+            // we could introduce alias in OptionDefinition if this string matching thing grows
+            variable_lower = "datafusion.execution.time_zone".to_string();
+        }
+
+        // we don't support change time zone until we complete time zone related implementation
+        if variable_lower == "datafusion.execution.time_zone" {
+            return Err(DataFusionError::Plan(
+                "Changing Time Zone isn't supported yet".to_string(),
+            ));
+        }
+
+        // parse value string from Expr
+        let value_string = match &value[0] {
+            SQLExpr::Identifier(i) => i.to_string(),
+            SQLExpr::Value(v) => match v {
+                Value::SingleQuotedString(s) => s.to_string(),
+                Value::Number(_, _) | Value::Boolean(_) => v.to_string(),

Review Comment:
   to support `SingleQuotedString`, `number` and `Bool`



##########
datafusion/core/tests/sql/set_variable.rs:
##########
@@ -0,0 +1,293 @@
+// 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 super::*;
+
+#[tokio::test]
+async fn set_variable_to_value() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    ctx.sql("SET datafusion.execution.batch_size to 1")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 1       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_sorted_eq!(expected, &result);
+}
+
+#[tokio::test]
+async fn set_variable_to_value_with_equal_sign() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    ctx.sql("SET datafusion.execution.batch_size = 1")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 1       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_sorted_eq!(expected, &result);
+}
+
+#[tokio::test]
+async fn set_variable_to_value_with_single_quoted_string() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    ctx.sql("SET datafusion.execution.batch_size to '1'")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 1       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_sorted_eq!(expected, &result);
+}
+
+#[tokio::test]
+async fn set_variable_to_value_case_insensitive() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    ctx.sql("SET datafusion.EXECUTION.batch_size to '1'")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 1       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_sorted_eq!(expected, &result);
+}
+
+#[tokio::test]
+async fn set_variable_unknown_variable() {
+    let ctx = SessionContext::new();
+
+    let err = plan_and_collect(&ctx, "SET aabbcc to '1'")
+        .await
+        .unwrap_err();
+    assert_eq!(err.to_string(), "Execution error: Unknown Variable aabbcc");
+}
+
+#[tokio::test]
+async fn set_bool_variable() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    ctx.sql("SET datafusion.execution.coalesce_batches to true")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.coalesce_batches")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------------+---------+",
+        "| name                                  | setting |",
+        "+---------------------------------------+---------+",
+        "| datafusion.execution.coalesce_batches | true    |",
+        "+---------------------------------------+---------+",
+    ];
+    assert_batches_eq!(expected, &result);
+
+    ctx.sql("SET datafusion.execution.coalesce_batches to 'false'")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.coalesce_batches")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------------+---------+",
+        "| name                                  | setting |",
+        "+---------------------------------------+---------+",
+        "| datafusion.execution.coalesce_batches | false   |",
+        "+---------------------------------------+---------+",
+    ];
+    assert_batches_eq!(expected, &result);
+}
+
+#[tokio::test]
+async fn set_bool_variable_bad_value() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    let err = plan_and_collect(&ctx, "SET datafusion.execution.coalesce_batches to 1")
+        .await
+        .unwrap_err();
+
+    assert_eq!(
+        err.to_string(),
+        "Execution error: Failed to parse 1 as bool"
+    );
+
+    let err = plan_and_collect(&ctx, "SET datafusion.execution.coalesce_batches to abc")
+        .await
+        .unwrap_err();
+
+    assert_eq!(
+        err.to_string(),
+        "Execution error: Failed to parse abc as bool"
+    );
+}
+
+#[tokio::test]
+async fn set_u64_variable() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    ctx.sql("SET datafusion.execution.batch_size to 0")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 0       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_eq!(expected, &result);
+
+    ctx.sql("SET datafusion.execution.batch_size to '1'")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 1       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_eq!(expected, &result);
+
+    ctx.sql("SET datafusion.execution.batch_size to +2")
+        .await
+        .unwrap();
+    let result = plan_and_collect(&ctx, "SHOW datafusion.execution.batch_size")
+        .await
+        .unwrap();
+    let expected = vec![
+        "+---------------------------------+---------+",
+        "| name                            | setting |",
+        "+---------------------------------+---------+",
+        "| datafusion.execution.batch_size | 2       |",
+        "+---------------------------------+---------+",
+    ];
+    assert_batches_eq!(expected, &result);
+}
+
+#[tokio::test]
+async fn set_u64_variable_bad_value() {
+    let ctx =
+        SessionContext::with_config(SessionConfig::new().with_information_schema(true));
+
+    let err = plan_and_collect(&ctx, "SET datafusion.execution.batch_size to -1")
+        .await
+        .unwrap_err();
+
+    assert_eq!(
+        err.to_string(),
+        "Execution error: Failed to parse -1 as u64"
+    );
+
+    let err = plan_and_collect(&ctx, "SET datafusion.execution.batch_size to abc")
+        .await
+        .unwrap_err();
+
+    assert_eq!(
+        err.to_string(),
+        "Execution error: Failed to parse abc as u64"
+    );
+
+    let err = plan_and_collect(&ctx, "SET datafusion.execution.batch_size to 0.1")
+        .await
+        .unwrap_err();
+
+    assert_eq!(
+        err.to_string(),
+        "Execution error: Failed to parse 0.1 as u64"
+    );
+}
+
+#[tokio::test]
+async fn set_time_zone() {
+    // we don't support changing time zone for now until all time zone issues fixed and related function completed
+
+    let ctx = SessionContext::new();
+
+    // for full variable name
+    let err = plan_and_collect(&ctx, "set datafusion.execution.time_zone = '8'")
+        .await
+        .unwrap_err();
+
+    assert_eq!(
+        err.to_string(),
+        "Error during planning: Changing Time Zone isn't supported yet"
+    );

Review Comment:
   should get back to this once time zone is fully integrated



##########
datafusion/sql/src/planner.rs:
##########
@@ -2451,6 +2458,84 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         self.statement_to_plan(rewrite.pop_front().unwrap())
     }
 
+    fn set_variable_to_plan(
+        &self,
+        local: bool,
+        hivevar: bool,
+        variable: &ObjectName,
+        value: Vec<sqlparser::ast::Expr>,
+    ) -> Result<LogicalPlan> {
+        if local {
+            return Err(DataFusionError::NotImplemented(
+                "LOCAL is not supported".to_string(),
+            ));
+        }
+
+        if hivevar {
+            return Err(DataFusionError::NotImplemented(
+                "HIVEVAR is not supported".to_string(),
+            ));
+        }
+
+        let variable = variable.to_string();
+        let mut variable_lower = variable.to_lowercase();
+
+        if variable_lower == "timezone" || variable_lower == "time.zone" {
+            // we could introduce alias in OptionDefinition if this string matching thing grows
+            variable_lower = "datafusion.execution.time_zone".to_string();
+        }
+
+        // we don't support change time zone until we complete time zone related implementation
+        if variable_lower == "datafusion.execution.time_zone" {
+            return Err(DataFusionError::Plan(
+                "Changing Time Zone isn't supported yet".to_string(),
+            ));
+        }
+
+        // parse value string from Expr
+        let value_string = match &value[0] {
+            SQLExpr::Identifier(i) => i.to_string(),

Review Comment:
   to support non-whitespace-separated string



-- 
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