matthewgapp commented on code in PR #8839:
URL: https://github.com/apache/arrow-datafusion/pull/8839#discussion_r1458161958


##########
datafusion/sql/src/query.rs:
##########
@@ -65,16 +65,128 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
                         "WITH query name {cte_name:?} specified more than once"
                     )));
                 }
-                // create logical plan & pass backreferencing CTEs
-                // CTE expr don't need extend outer_query_schema
-                let logical_plan =
-                    self.query_to_plan(*cte.query, &mut 
planner_context.clone())?;
+                let cte_query = cte.query;
+
+                if is_recursive {
+                    if !self
+                        .context_provider
+                        .options()
+                        .execution
+                        .enable_recursive_ctes
+                    {
+                        return not_impl_err!("Recursive CTEs are not enabled");
+                    }
+
+                    match *cte_query.body {
+                        SetExpr::SetOperation {
+                            op: SetOperator::Union,
+                            left,
+                            right,
+                            set_quantifier,
+                        } => {
+                            let distinct = set_quantifier != 
SetQuantifier::All;
+
+                            // Each recursive CTE consists from two parts in 
the logical plan:
+                            //   1. A static term   (the left hand side on the 
SQL, where the
+                            //                       referencing to the same 
CTE is not allowed)
+                            //
+                            //   2. A recursive term (the right hand side, and 
the recursive
+                            //                       part)
+
+                            // Since static term does not have any specific 
properties, it can
+                            // be compiled as if it was a regular expression. 
This will
+                            // allow us to infer the schema to be used in the 
recursive term.
+
+                            // ---------- Step 1: Compile the static term 
------------------
+                            let static_plan = self
+                                .set_expr_to_plan(*left, &mut 
planner_context.clone())?;
+
+                            // Since the recursive CTEs include a component 
that references a
+                            // table with its name, like the example below:
+                            //
+                            // WITH RECURSIVE values(n) AS (
+                            //      SELECT 1 as n -- static term
+                            //    UNION ALL
+                            //      SELECT n + 1
+                            //      FROM values -- self reference
+                            //      WHERE n < 100
+                            // )
+                            //
+                            // We need a temporary 'relation' to be referenced 
and used. PostgreSQL
+                            // calls this a 'working table', but it is 
entirely an implementation
+                            // detail and a 'real' table with that name might 
not even exist (as
+                            // in the case of DataFusion).
+                            //
+                            // Since we can't simply register a table during 
planning stage (it is
+                            // an execution problem), we'll use a relation 
object that preserves the
+                            // schema of the input perfectly and also knows 
which recursive CTE it is
+                            // bound to.
 
-                // Each `WITH` block can change the column names in the last
-                // projection (e.g. "WITH table(t1, t2) AS SELECT 1, 2").
-                let logical_plan = self.apply_table_alias(logical_plan, 
cte.alias)?;
+                            // ---------- Step 2: Create a temporary relation 
------------------
+                            // Step 2.1: Create a table source for the 
temporary relation
+                            let work_table_source =
+                                self.context_provider.create_cte_work_table(
+                                    &cte_name,
+                                    
Arc::new(Schema::from(static_plan.schema().as_ref())),
+                                )?;
 
-                planner_context.insert_cte(cte_name, logical_plan);
+                            // Step 2.2: Create a temporary relation logical 
plan that will be used
+                            // as the input to the recursive term
+                            let work_table_plan = LogicalPlanBuilder::scan(
+                                cte_name.to_string(),
+                                work_table_source,
+                                None,
+                            )?
+                            .build()?;
+
+                            let name = cte_name.clone();
+
+                            // Step 2.3: Register the temporary relation in 
the planning context
+                            // For all the self references in the variadic 
term, we'll replace it
+                            // with the temporary relation we created above by 
temporarily registering
+                            // it as a CTE. This temporary relation in the 
planning context will be
+                            // replaced by the actual CTE plan once we're done 
with the planning.
+                            planner_context.insert_cte(cte_name.clone(), 
work_table_plan);
+
+                            // ---------- Step 3: Compile the recursive term 
------------------
+                            // this uses the named_relation we inserted above 
to resolve the
+                            // relation. This ensures that the recursive term 
uses the named relation logical plan
+                            // and thus the 'continuance' physical plan as its 
input and source
+                            let recursive_plan = self
+                                .set_expr_to_plan(*right, &mut 
planner_context.clone())?;
+
+                            // ---------- Step 4: Create the final plan 
------------------
+                            // Step 4.1: Compile the final plan
+                            let logical_plan = 
LogicalPlanBuilder::from(static_plan)
+                                .to_recursive_query(name, recursive_plan, 
distinct)?
+                                .build()?;
+
+                            let final_plan =
+                                self.apply_table_alias(logical_plan, 
cte.alias)?;
+
+                            // Step 4.2: Remove the temporary relation from 
the planning context and replace it
+                            // with the final plan.
+                            planner_context.insert_cte(cte_name.clone(), 
final_plan);
+                        }
+                        _ => {
+                            return Err(DataFusionError::SQL(
+                                ParserError("Invalid recursive 
CTE".to_string()),

Review Comment:
   done



-- 
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]

Reply via email to