Apache DataFusion SQL Query Engine
ARROW-9760: [Rust] [DataFusion] Added DataFrame::explain
Jorge C. Leitao873b17ec37da
diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rsindex 532543d303..0a0611c644 100644--- a/rust/datafusion/src/dataframe.rs+++ b/rust/datafusion/src/dataframe.rs@@ -174,4 +174,18 @@ pub trait DataFrame {/// Return the logical plan represented by this DataFrame.fn to_logical_plan(&self) -> LogicalPlan;++ /// Return a DataFrame with the explanation of its plan so far.+ ///+ /// ```+ /// # use datafusion::prelude::*;+ /// # use datafusion::error::Result;+ /// # fn main() -> Result<()> {+ /// let mut ctx = ExecutionContext::new();+ /// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;+ /// let batches = df.limit(100)?.explain(false)?.collect()?;+ /// # Ok(())+ /// # }+ /// ```+ fn explain(&self, verbose: bool) -> Result<Arc<dyn DataFrame>>;}diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex 61bb57613d..4698a84d9b 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -113,6 +113,13 @@ impl DataFrame for DataFrameImpl {fn schema(&self) -> &Schema {self.plan.schema().as_ref()}++ fn explain(&self, verbose: bool) -> Result<Arc<dyn DataFrame>> {+ let plan = LogicalPlanBuilder::from(&self.plan)+ .explain(verbose)?+ .build()?;+ Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))+ }}#[cfg(test)]@@ -201,6 +208,26 @@ mod tests {Ok(())}+ #[test]+ fn explain() -> Result<()> {+ // build query using Table API+ let df = test_table()?;+ let df = df+ .select_columns(vec!["c1", "c2", "c11"])?+ .limit(10)?+ .explain(false)?;+ let plan = df.to_logical_plan();++ // build query using SQL+ let sql_plan =+ create_plan("EXPLAIN SELECT c1, c2, c11 FROM aggregate_test_100 LIMIT 10")?;++ // the two plans should be identical+ assert_same_plan(&plan, &sql_plan);++ Ok(())+ }+/// Compare the formatted string representation of two plans for equalityfn assert_same_plan(plan1: &LogicalPlan, plan2: &LogicalPlan) {assert_eq!(format!("{:?}", plan1), format!("{:?}", plan2));diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex 314283f9c4..a56cb46a61 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -1251,6 +1251,23 @@ impl LogicalPlanBuilder {}))}+ /// Create an expression to represent the explanation of the plan+ pub fn explain(&self, verbose: bool) -> Result<Self> {+ let stringified_plans = vec![StringifiedPlan::new(+ PlanType::LogicalPlan,+ format!("{:#?}", self.plan.clone()),+ )];++ let schema = LogicalPlan::explain_schema();++ Ok(Self::from(&LogicalPlan::Explain {+ verbose,+ plan: Box::new(self.plan.clone()),+ stringified_plans,+ schema,+ }))+ }+/// Build the planpub fn build(&self) -> Result<LogicalPlan> {Ok(self.plan.clone())