jayzhan211 commented on code in PR #27531:
URL: https://github.com/apache/datafusion/pull/27531#discussion_r4649910116


##########
datafusion/sqllogictest/src/engines/datafusion_unparser_roundtrip_engine/runner.rs:
##########
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::sync::Arc;
+use std::{path::PathBuf, time::Duration};
+
+use crate::engines::currently_executed_sql::CurrentlyExecutingSqlTracker;
+use crate::engines::datafusion_engine::Result;
+use crate::engines::output::{DFColumnType, DFOutput};
+use crate::memory_drift::rewrap_replaced_pool;
+use crate::{DFSqlLogicTestError, convert_batches, convert_schema_to_types};
+use arrow::record_batch::RecordBatch;
+use async_trait::async_trait;
+use datafusion::logical_expr::LogicalPlan;
+use datafusion::physical_plan::common::collect;
+use datafusion::physical_plan::execute_stream;
+use datafusion::prelude::SessionContext;
+use datafusion::sql::unparser::plan_to_sql;
+use indicatif::ProgressBar;
+use log::Level::{Debug, Info};
+use log::{debug, log_enabled, warn};
+use sqllogictest::DBOutput;
+use tokio::time::Instant;
+
+pub struct DataFusionUnparserRoundTrip {
+    ctx: SessionContext,
+    relative_path: PathBuf,
+    pb: ProgressBar,
+    currently_executing_sql_tracker: CurrentlyExecutingSqlTracker,
+    optimize_before_round_trip: bool,
+}
+
+impl DataFusionUnparserRoundTrip {
+    pub fn new(ctx: SessionContext, relative_path: PathBuf, pb: ProgressBar) 
-> Self {
+        Self {
+            ctx,
+            relative_path,
+            pb,
+            currently_executing_sql_tracker: 
CurrentlyExecutingSqlTracker::default(),
+            optimize_before_round_trip: false,
+        }
+    }
+
+    /// Optimize the logical plan before unparsing it to SQL.
+    pub fn with_optimization(mut self, optimize: bool) -> Self {
+        self.optimize_before_round_trip = optimize;
+        self
+    }
+
+    /// Add a tracker that will track the currently executed SQL statement.
+    ///
+    /// This is useful for logging and debugging purposes.
+    pub fn with_currently_executing_sql_tracker(
+        self,
+        currently_executing_sql_tracker: CurrentlyExecutingSqlTracker,
+    ) -> Self {
+        Self {
+            currently_executing_sql_tracker,
+            ..self
+        }
+    }
+
+    fn update_slow_count(&self) {
+        let msg = self.pb.message();
+        let split: Vec<&str> = msg.split(' ').collect();
+        let mut current_count = 0;
+
+        if split.len() > 2 {
+            // third match will be current slow count
+            current_count = split[2].parse::<i32>().unwrap();
+        }
+
+        current_count += 1;
+
+        self.pb
+            .set_message(format!("{} - {} took > 500 ms", split[0], 
current_count));
+    }
+}
+
+#[async_trait]
+impl sqllogictest::AsyncDB for DataFusionUnparserRoundTrip {
+    type Error = DFSqlLogicTestError;
+    type ColumnType = DFColumnType;
+
+    async fn run(&mut self, sql: &str) -> Result<DFOutput> {
+        if log_enabled!(Debug) {
+            debug!(
+                "[{}] Running query: \"{}\"",
+                self.relative_path.display(),
+                sql
+            );
+        }
+
+        let tracked_sql = self.currently_executing_sql_tracker.set_sql(sql);
+
+        let start = Instant::now();
+        let result = run_query_unparser_round_trip(
+            &self.ctx,
+            sql,
+            self.optimize_before_round_trip,
+        )
+        .await;
+        let duration = start.elapsed();
+        rewrap_replaced_pool(&self.ctx, 
&self.relative_path.display().to_string());
+
+        self.currently_executing_sql_tracker.remove_sql(tracked_sql);
+
+        if duration.gt(&Duration::from_millis(500)) {
+            self.update_slow_count();
+        }
+
+        self.pb.inc(1);
+
+        if log_enabled!(Info) && duration.gt(&Duration::from_secs(2)) {
+            warn!(
+                "[{}] Running query took more than 2 sec ({duration:?}): 
\"{sql}\"",
+                self.relative_path.display()
+            );
+        }
+
+        result
+    }
+
+    /// Engine name of current database.
+    fn engine_name(&self) -> &str {
+        "DataFusionUnparserRoundTrip"
+    }
+
+    /// `DataFusion` calls this function to perform sleep.
+    ///
+    /// The default implementation is `std::thread::sleep`, which is universal 
to any async runtime
+    /// but would block the current thread. If you are running in tokio 
runtime, you should override
+    /// this by `tokio::time::sleep`.
+    async fn sleep(dur: Duration) {
+        tokio::time::sleep(dur).await;
+    }
+
+    async fn shutdown(&mut self) {}
+}
+
+async fn run_query_unparser_round_trip(
+    ctx: &SessionContext,
+    sql: impl Into<String>,
+    optimize: bool,
+) -> Result<DFOutput> {
+    // `SessionContext::sql` runs DDL eagerly and returns an empty plan in its
+    // place, so plan the statement first to see the original plan.
+    let state = ctx.state();
+    let logical_plan = state.create_logical_plan(&sql.into()).await?;
+    let round_tripped_plan = match &logical_plan {
+        // SQL cannot express these plans as a query, so they run unchanged.
+        LogicalPlan::Ddl(_)
+        | LogicalPlan::Analyze(_)
+        | LogicalPlan::Explain(_)
+        | LogicalPlan::Dml(_)
+        | LogicalPlan::Copy(_)
+        | LogicalPlan::Show(_)
+        | LogicalPlan::Statement(_) => logical_plan,
+        logical_plan => {
+            let to_unparse = if optimize {
+                state.optimize(logical_plan)?
+            } else {
+                logical_plan.clone()
+            };
+            let unparsed_sql = plan_to_sql(&to_unparse)?.to_string();
+            debug!("Unparsed SQL: \"{unparsed_sql}\"");
+            state.create_logical_plan(&unparsed_sql).await?
+        }
+    };

Review Comment:
   Optional cleanup: the Substrait engine has the same pass-through list but 
without `Analyze`, so `--substrait-round-trip` still fails on `EXPLAIN ANALYZE` 
(32 `Unsupported plan type: Analyze` errors in `explain_analyze.slt`). One 
shared helper gives both engines your fix, and the next plan that must pass 
through only needs adding once:
   
   ```diff
   --- a/datafusion/sqllogictest/src/engines/mod.rs
   +++ b/datafusion/sqllogictest/src/engines/mod.rs
   @@ -23,6 +23,23 @@ pub use output::DFOutput;
    
    pub use currently_executed_sql::CurrentlyExecutingSqlTracker;
    
   +use datafusion::logical_expr::LogicalPlan;
   +
   +/// Plans that the round-trip engines run unchanged, because they are not
   +/// queries: the unparser and the Substrait producer both reject them.
   +pub(crate) fn skips_round_trip(plan: &LogicalPlan) -> bool {
   +    matches!(
   +        plan,
   +        LogicalPlan::Ddl(_)
   +            | LogicalPlan::Analyze(_)
   +            | LogicalPlan::Explain(_)
   +            | LogicalPlan::Dml(_)
   +            | LogicalPlan::Copy(_)
   +            | LogicalPlan::Show(_)
   +            | LogicalPlan::Statement(_)
   +    )
   +}
   +
    #[cfg(feature = "postgres")]
    mod postgres_engine;
   ```
   
   <details>
   <summary>Both call sites, checked with clippy and the slt runs with and 
without <code>--features substrait</code></summary>
   
   ```diff
   --- 
a/datafusion/sqllogictest/src/engines/datafusion_substrait_roundtrip_engine/runner.rs
   +++ 
b/datafusion/sqllogictest/src/engines/datafusion_substrait_roundtrip_engine/runner.rs
   @@ -8,11 +8,11 @@
    use crate::engines::output::{DFColumnType, DFOutput};
   +use crate::engines::skips_round_trip;
    use crate::memory_drift::rewrap_replaced_pool;
    use crate::{DFSqlLogicTestError, convert_batches, convert_schema_to_types};
    use arrow::record_batch::RecordBatch;
    use async_trait::async_trait;
   -use datafusion::logical_expr::LogicalPlan;
   @@ -154,19 +154,11 @@ async fn run_query_substrait_round_trip(
   -    let round_tripped_plan = match &logical_plan {
   -        // Substrait does not handle these plans
   -        LogicalPlan::Ddl(_)
   -        | LogicalPlan::Explain(_)
   -        | LogicalPlan::Dml(_)
   -        | LogicalPlan::Copy(_)
   -        | LogicalPlan::Show(_)
   -        | LogicalPlan::Statement(_) => logical_plan,
   -        // For any other plan, convert to Substrait
   -        logical_plan => {
   -            let plan = to_substrait_plan(logical_plan, &state)?;
   -            from_substrait_plan(&state, &plan).await?
   -        }
   +    let round_tripped_plan = if skips_round_trip(&logical_plan) {
   +        logical_plan
   +    } else {
   +        let plan = to_substrait_plan(&logical_plan, &state)?;
   +        from_substrait_plan(&state, &plan).await?
        };
   --- 
a/datafusion/sqllogictest/src/engines/datafusion_unparser_roundtrip_engine/runner.rs
   +++ 
b/datafusion/sqllogictest/src/engines/datafusion_unparser_roundtrip_engine/runner.rs
   @@ -8,11 +8,11 @@
    use crate::engines::output::{DFColumnType, DFOutput};
   +use crate::engines::skips_round_trip;
    use crate::memory_drift::rewrap_replaced_pool;
    use crate::{DFSqlLogicTestError, convert_batches, convert_schema_to_types};
    use arrow::record_batch::RecordBatch;
    use async_trait::async_trait;
   -use datafusion::logical_expr::LogicalPlan;
   @@ -148,25 +148,17 @@ async fn run_query_unparser_round_trip(
   -    let round_tripped_plan = match &logical_plan {
   -        // SQL cannot express these plans as a query, so they run unchanged.
   -        LogicalPlan::Ddl(_)
   -        | LogicalPlan::Analyze(_)
   -        | LogicalPlan::Explain(_)
   -        | LogicalPlan::Dml(_)
   -        | LogicalPlan::Copy(_)
   -        | LogicalPlan::Show(_)
   -        | LogicalPlan::Statement(_) => logical_plan,
   -        logical_plan => {
   -            let to_unparse = if optimize {
   -                state.optimize(logical_plan)?
   -            } else {
   -                logical_plan.clone()
   -            };
   -            let unparsed_sql = plan_to_sql(&to_unparse)?.to_string();
   -            debug!("Unparsed SQL: \"{unparsed_sql}\"");
   -            state.create_logical_plan(&unparsed_sql).await?
   -        }
   +    let round_tripped_plan = if skips_round_trip(&logical_plan) {
   +        logical_plan
   +    } else {
   +        let to_unparse = if optimize {
   +            state.optimize(&logical_plan)?
   +        } else {
   +            logical_plan
   +        };
   +        let unparsed_sql = plan_to_sql(&to_unparse)?.to_string();
   +        debug!("Unparsed SQL: \"{unparsed_sql}\"");
   +        state.create_logical_plan(&unparsed_sql).await?
        };
   ```
   
   </details>
   



##########
datafusion/sqllogictest/src/engines/datafusion_unparser_roundtrip_engine/runner.rs:
##########
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::sync::Arc;
+use std::{path::PathBuf, time::Duration};
+
+use crate::engines::currently_executed_sql::CurrentlyExecutingSqlTracker;
+use crate::engines::datafusion_engine::Result;
+use crate::engines::output::{DFColumnType, DFOutput};
+use crate::memory_drift::rewrap_replaced_pool;
+use crate::{DFSqlLogicTestError, convert_batches, convert_schema_to_types};
+use arrow::record_batch::RecordBatch;
+use async_trait::async_trait;
+use datafusion::logical_expr::LogicalPlan;
+use datafusion::physical_plan::common::collect;
+use datafusion::physical_plan::execute_stream;
+use datafusion::prelude::SessionContext;
+use datafusion::sql::unparser::plan_to_sql;
+use indicatif::ProgressBar;
+use log::Level::{Debug, Info};
+use log::{debug, log_enabled, warn};
+use sqllogictest::DBOutput;
+use tokio::time::Instant;
+
+pub struct DataFusionUnparserRoundTrip {

Review Comment:
   Optional cleanup: `DataFusionUnparserRoundTrip` is a new public type, so it 
needs a rustdoc comment. Without one, readers of the crate's docs can't tell 
what it does:
   
   ```suggestion
   /// A sqllogictest engine that unparses each query's logical plan to SQL with
   /// [`plan_to_sql`] and plans that SQL again before running it.
   pub struct DataFusionUnparserRoundTrip {
   ```
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to