Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions datafusion/core/src/execution/session_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,16 @@ impl SessionState {

let sql_expr = self.sql_to_expr_with_alias(sql, &dialect)?;

self.create_logical_expr_from_sql_expr(sql_expr, df_schema)
}

/// Creates a datafusion style AST [`Expr`] from a SQL expression.
#[cfg(feature = "sql")]
pub fn create_logical_expr_from_sql_expr(
&self,
sql_expr: SQLExprWithAlias,
df_schema: &DFSchema,
) -> datafusion_common::Result<Expr> {
let provider = SessionContextProvider {
state: self,
tables: HashMap::new(),
Expand Down Expand Up @@ -2095,6 +2105,36 @@ mod tests {
assert!(sql_to_expr(&state).is_err())
}

#[test]
#[cfg(feature = "sql")]
fn test_create_logical_expr_from_sql_expr() {
let state = SessionStateBuilder::new().with_default_features().build();

let provider = SessionContextProvider {
state: &state,
tables: HashMap::new(),
};

let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
let df_schema = DFSchema::try_from(schema).unwrap();
let dialect = state.config.options().sql_parser.dialect;
let query = SqlToRel::new_with_options(&provider, state.get_parser_options());

for sql in ["[1,2,3]", "a > 10", "SUM(a)"] {
let sql_expr = state.sql_to_expr(sql, &dialect).unwrap();
Copy link
Member

Choose a reason for hiding this comment

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

The api name is strange to me first, I think it wants to say "sql string to expr"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, it can be a bit ambiguous. Either way, sql_to_expr is an existing public API before this PR.

let from_str = query
.sql_to_expr(sql_expr, &df_schema, &mut PlannerContext::new())
.unwrap();

let sql_expr_with_alias =
state.sql_to_expr_with_alias(sql, &dialect).unwrap();
let from_expr = state
.create_logical_expr_from_sql_expr(sql_expr_with_alias, &df_schema)
.unwrap();
assert_eq!(from_str, from_expr);
}
}

#[test]
fn test_from_existing() -> Result<()> {
fn employee_batch() -> RecordBatch {
Expand Down