Skip to content

Conversation

@Sevenannn
Copy link
Contributor

Which issue does this PR close?

N/A

Rationale for this change

Datafusion enforces an eager cast of value to Binary / BinaryView value in the logical plan where a comparison with binary value is presented. For example, in the following plan

Filter: value = CAST(Utf8("binary_value") AS Binary
However, when using unparser to convert the plan back to sql, where the sql will be sent to various query engine (e.g. DuckDB). the cast is not needed for the value, in the example above the value "binary_value", since the raw value can be directly used in SQL engines without casting to an engine specific dictionary type. Therefore, the plan can simply be rewritten into where value = 'binary_value'

What changes are included in this PR?

  • Add function cast_to_sql, which directly pass inner_expr instead of cast inner_expr when casting to binary / binaryview / dictionary in the Expr::Cast, and keep the original casting logic in all other cases.
  • Add a test for the change

Are these changes tested?

Yes

Are there any user-facing changes?

No

Sevenannn and others added 2 commits November 14, 2024 14:20
* Skip casting to binary when inner expr is value

* Update datafusion/sql/src/unparser/expr.rs

Co-authored-by: Jack Eadie <[email protected]>

---------

Co-authored-by: Jack Eadie <[email protected]>
@github-actions github-actions bot added the sql SQL Planner label Nov 14, 2024
Copy link
Contributor

@alamb alamb left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Sevenannn -- this makes sense to me. I have some small suggestions but I don't think they are needed to merge this PR

Comment on lines +2181 to +2186
Expr::Cast(Cast {
expr: Box::new(Expr::Literal(ScalarValue::Utf8(Some(
"blah".to_string(),
)))),
data_type: DataType::Binary,
}),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can write this more concisely with lit

Suggested change
Expr::Cast(Cast {
expr: Box::new(Expr::Literal(ScalarValue::Utf8(Some(
"blah".to_string(),
)))),
data_type: DataType::Binary,
}),
Expr::Cast(Cast {
expr: Box::new(lit("blah"))
data_type: DataType::Binary,
}),

You could also try to use https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html#method.cast_to but that requires a valid schema

@alamb
Copy link
Contributor

alamb commented Nov 18, 2024

🚀

@alamb
Copy link
Contributor

alamb commented Nov 18, 2024

Thanks @Sevenannn @phillipleblanc and @Jeadie

@alamb alamb merged commit 900552c into apache:main Nov 18, 2024
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

sql SQL Planner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants