-
Notifications
You must be signed in to change notification settings - Fork 1.9k
feat: plan-time SQL expression simplifying #19311
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
d9b39a3
Allow to run datafusion-examples relation_planner without parameters
theirix 3421187
datafusion-sql: expose relation module
theirix 690e167
Add SqlToRelRelationContext constructor
theirix 5b5a838
Add parse_sql_literal module
theirix b2bc6cf
Switch table sample example to lib sql parsing
theirix a46e040
Reformat
theirix 1cb87c1
Use unwrap_or_else
theirix e5a95d4
Ignore doctest
theirix 93ba06e
Gate parse_sql_literal with sql feature
theirix 90f7a4b
Enable optimizer feature sql
theirix 964a326
Enable sql feature for datafusion in examples
theirix df70b24
Set sql feature for optimizer crate
theirix 78e2dc1
Omit example launcher change
theirix 7aa15c8
Simplify signature by deriving a primitive type from ArrowPrimitiveType
theirix ff8f3cc
Use an empty schema to avoid passing it around
theirix 16d93a6
Merge branch 'main' into parse_sql_literal
theirix d519934
Accept logical expression
theirix 803c333
Change TableSamplePlanner to provide logical expression
theirix 8e0fecc
Remove sql feature on optimizer crate
theirix f78f7ac
Rename to parse_literal
theirix c989bab
Refactor tests to use pre-baked logical expressions
theirix ffa5bee
Reformat
theirix 171f0b0
Reformat
theirix 46d4d9e
Unpublish SqlToRelRelationContext
theirix File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
151 changes: 151 additions & 0 deletions
151
datafusion/optimizer/src/simplify_expressions/simplify_literal.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| // 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. | ||
|
|
||
| //! Parses and simplifies an expression to a literal of a given type. | ||
| //! | ||
| //! This module provides functionality to parse and simplify static expressions | ||
| //! used in SQL constructs like `FROM TABLE SAMPLE (10 + 50 * 2)`. If they are required | ||
| //! in a planning (not an execution) phase, they need to be reduced to literals of a given type. | ||
|
|
||
| use crate::simplify_expressions::ExprSimplifier; | ||
| use arrow::datatypes::ArrowPrimitiveType; | ||
| use datafusion_common::{ | ||
| DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue, plan_datafusion_err, | ||
| plan_err, | ||
| }; | ||
| use datafusion_expr::Expr; | ||
| use datafusion_expr::execution_props::ExecutionProps; | ||
| use datafusion_expr::simplify::SimplifyContext; | ||
| use std::sync::Arc; | ||
|
|
||
| /// Parse and simplifies an expression to a numeric literal, | ||
| /// corresponding to an arrow primitive type `T` (for example, Float64Type). | ||
| /// | ||
| /// This function simplifies and coerces the expression, then extracts the underlying | ||
| /// native type using `TryFrom<ScalarValue>`. | ||
| /// | ||
| /// # Example | ||
| /// ```ignore | ||
| /// let value: f64 = parse_literal::<Float64Type>(expr)?; | ||
| /// ``` | ||
| pub fn parse_literal<T>(expr: &Expr) -> Result<T::Native> | ||
| where | ||
| T: ArrowPrimitiveType, | ||
| T::Native: TryFrom<ScalarValue, Error = DataFusionError>, | ||
| { | ||
| // Empty schema is sufficient because it parses only literal expressions | ||
| let schema = DFSchemaRef::new(DFSchema::empty()); | ||
|
|
||
| log::debug!("Parsing expr {:?} to type {}", expr, T::DATA_TYPE); | ||
|
|
||
| let execution_props = ExecutionProps::new(); | ||
| let simplifier = ExprSimplifier::new( | ||
| SimplifyContext::new(&execution_props).with_schema(Arc::clone(&schema)), | ||
| ); | ||
|
|
||
| // Simplify and coerce expression in case of constant arithmetic operations (e.g., 10 + 5) | ||
| let simplified_expr: Expr = simplifier | ||
| .simplify(expr.clone()) | ||
| .map_err(|err| plan_datafusion_err!("Cannot simplify {expr:?}: {err}"))?; | ||
| let coerced_expr: Expr = simplifier.coerce(simplified_expr, schema.as_ref())?; | ||
| log::debug!("Coerced expression: {:?}", &coerced_expr); | ||
|
|
||
| match coerced_expr { | ||
| Expr::Literal(scalar_value, _) => { | ||
| // It is a literal - proceed to the underlying value | ||
| // Cast to the target type if needed | ||
| let casted_scalar = scalar_value.cast_to(&T::DATA_TYPE)?; | ||
|
|
||
| // Extract the native type | ||
| T::Native::try_from(casted_scalar).map_err(|err| { | ||
| plan_datafusion_err!( | ||
| "Cannot extract {} from scalar value: {err}", | ||
| std::any::type_name::<T>() | ||
| ) | ||
| }) | ||
| } | ||
| actual => { | ||
| plan_err!( | ||
| "Cannot extract literal from coerced {actual:?} expression given {expr:?} expression" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use arrow::datatypes::{Float64Type, Int64Type}; | ||
| use datafusion_expr::{BinaryExpr, lit}; | ||
| use datafusion_expr_common::operator::Operator; | ||
|
|
||
| #[test] | ||
| fn test_parse_sql_float_literal() { | ||
| let test_cases = vec![ | ||
| (Expr::Literal(ScalarValue::Float64(Some(0.0)), None), 0.0), | ||
| (Expr::Literal(ScalarValue::Float64(Some(1.0)), None), 1.0), | ||
| ( | ||
| Expr::BinaryExpr(BinaryExpr::new( | ||
| Box::new(lit(50.0)), | ||
| Operator::Minus, | ||
| Box::new(lit(10.0)), | ||
| )), | ||
| 40.0, | ||
| ), | ||
| ( | ||
| Expr::Literal(ScalarValue::Utf8(Some("1e2".into())), None), | ||
| 100.0, | ||
| ), | ||
| ( | ||
| Expr::Literal(ScalarValue::Utf8(Some("2.5e-1".into())), None), | ||
| 0.25, | ||
| ), | ||
| ]; | ||
|
|
||
| for (expr, expected) in test_cases { | ||
| let result: Result<f64> = parse_literal::<Float64Type>(&expr); | ||
|
|
||
| match result { | ||
| Ok(value) => { | ||
| assert!( | ||
| (value - expected).abs() < 1e-10, | ||
| "For expression '{expr}': expected {expected}, got {value}", | ||
| ); | ||
| } | ||
| Err(e) => panic!("Failed to parse expression '{expr}': {e}"), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_parse_sql_integer_literal() { | ||
| let expr = Expr::BinaryExpr(BinaryExpr::new( | ||
| Box::new(lit(2)), | ||
| Operator::Plus, | ||
| Box::new(lit(4)), | ||
| )); | ||
|
|
||
| let result: Result<i64> = parse_literal::<Int64Type>(&expr); | ||
|
|
||
| match result { | ||
| Ok(value) => { | ||
| assert_eq!(6, value); | ||
| } | ||
| Err(e) => panic!("Failed to parse expression: {e}"), | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@geoffreyclaude I wonder what your thoughts on this PR and the approach of parse_sql_literal?