pub fn plan_to_sql(plan: &LogicalPlan) -> Result<Statement, DataFusionError>Expand description
Convert a DataFusion LogicalPlan to ast::Statement
This function is the opposite of SqlToRel::sql_statement_to_plan and can
be used to, among other things, to convert LogicalPlans to SQL strings.
§Errors
This function returns an error if the plan cannot be converted to SQL.
§See Also
expr_to_sqlfor convertingExpr, a single expression to SQL
§Example
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_expr::{col, logical_plan::table_scan};
use datafusion_sql::unparser::plan_to_sql;
let schema = Schema::new(vec![
Field::new("id", DataType::Utf8, false),
Field::new("value", DataType::Utf8, false),
]);
// Scan 'table' and select columns 'id' and 'value'
let plan = table_scan(Some("table"), &schema, None)
.unwrap()
.project(vec![col("id"), col("value")])
.unwrap()
.build()
.unwrap();
let sql = plan_to_sql(&plan).unwrap(); // convert to AST
// use the Display impl to convert to SQL text
assert_eq!(sql.to_string(), "SELECT \"table\".id, \"table\".\"value\" FROM \"table\"")