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


##########
datafusion/sql/src/planner.rs:
##########
@@ -61,6 +61,15 @@ pub trait ContextProvider {
         not_impl_err!("Table Functions are not supported")
     }
 
+    /// TODO: add doc
+    fn create_cte_work_table(

Review Comment:
   I think the `ContextProvider` is designed so the parser doesn't depend on 
the rest of the DataFusion execution machinery so it can supply table providers
   
   However, in this case it seems to me like the work tables aren't going to 
come from a context provider (they will be made once per query)
   
   Thus I wonder if this function would be better simply as a function on the 
`SqlToRel ` planner itself
   



##########
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:
   Is this invalid? It is more like "Unsupported CTE", right? It would also 
help to improve the error message to include the part of the query that is not 
supported
   
   ```suggestion
                                   not_impl_err!("Unsupported recursive CTE: 
{cte}")
   
   ```



##########
datafusion/sql/tests/sql_integration.rs:
##########
@@ -1394,11 +1394,46 @@ fn recursive_ctes() {
         select * from numbers;";
     let err = logical_plan(sql).expect_err("query should have failed");
     assert_eq!(
-        "This feature is not implemented: Recursive CTEs are not supported",
+        "This feature is not implemented: Recursive CTEs are not enabled",
         err.strip_backtrace()
     );
 }
 
+#[test]
+fn recursive_ctes_enabled() {
+    let sql = "
+        WITH RECURSIVE numbers AS (
+              select 1 as n
+            UNION ALL
+              select n + 1 FROM numbers WHERE N < 10
+        )
+        select * from numbers;";
+
+    // manually setting up test here so that we can enable recursive ctes
+    let mut context = MockContextProvider::default();
+    context.options_mut().execution.enable_recursive_ctes = true;
+
+    let planner = SqlToRel::new_with_options(&context, 
ParserOptions::default());
+    let result = DFParser::parse_sql_with_dialect(sql, &GenericDialect {});
+    let mut ast = result.unwrap();
+
+    let plan = planner
+        .statement_to_plan(ast.pop_front().unwrap())
+        .expect("recursive cte plan creation failed");
+
+    assert_eq!(
+        format!("{plan:?}"),
+        "Projection: numbers.n\
+        \n  SubqueryAlias: numbers\
+        \n    RecursiveQuery: is_distinct=false\

Review Comment:
   👍 



##########
datafusion/expr/src/logical_plan/builder.rs:
##########
@@ -121,6 +123,27 @@ impl LogicalPlanBuilder {
         }))
     }
 
+    /// Convert a regular plan into a recursive query.

Review Comment:
   Can we please document what `is_distinct` means here? I think it means "when 
updating the working table, should the results be deduplicated ('UNION') or not 
(UNION ALL)



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -1718,6 +1751,42 @@ pub struct EmptyRelation {
     pub schema: DFSchemaRef,
 }
 
+/// A variadic query operation, Recursive CTE.
+///
+/// # Recursive Query Evaluation
+///
+/// From the [Postgres Docs]:
+///
+/// 1. Evaluate the non-recursive term. For `UNION` (but not `UNION ALL`),
+/// discard duplicate rows. Include all remaining rows in the result of the
+/// recursive query, and also place them in a temporary working table.
+//
+/// 2. So long as the working table is not empty, repeat these steps:
+///
+/// * Evaluate the recursive term, substituting the current contents of the
+/// working table for the recursive self-reference. For `UNION` (but not `UNION
+/// ALL`), discard duplicate rows and rows that duplicate any previous result
+/// row. Include all remaining rows in the result of the recursive query, and
+/// also place them in a temporary intermediate table.
+///
+/// * Replace the contents of the working table with the contents of the
+/// intermediate table, then empty the intermediate table.
+///
+/// [Postgres Docs]: 
https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-RECURSIVE
+#[derive(Clone, PartialEq, Eq, Hash)]
+pub struct RecursiveQuery {
+    /// Name of the query
+    pub name: String,
+    /// The static term (initial contents of the working table)
+    pub static_term: Arc<LogicalPlan>,
+    /// The recursive term (evaluated on the contents of the working table 
until
+    /// it returns an empty set)
+    pub recursive_term: Arc<LogicalPlan>,
+    /// Should the output of the recursive term be deduplicated (`UNION`) or
+    /// not (`UNION ALL`).
+    pub is_distinct: bool,

Review Comment:
   I wonder if using the term `all` would be easier here as it more closely 
matches the CTE Syntax (UNON vs UNION ALL)
   
   Something like
   
   ```suggestion
       pub all: bool,
   ```



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