Skip to content

Commit

Permalink
chore: support recursive cte with normal cte (#16932)
Browse files Browse the repository at this point in the history
Co-authored-by: wubx <[email protected]>
Co-authored-by: Bohu <[email protected]>
  • Loading branch information
3 people authored Nov 26, 2024
1 parent 6505b7a commit 73cd346
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl Binder {
if self.bind_recursive_cte {
self.bind_r_cte_scan(bind_context, cte_info, &table_name, alias)
} else {
self.bind_r_cte(bind_context, cte_info, &table_name, alias)
self.bind_r_cte(*span, bind_context, cte_info, &table_name, alias)
}
} else {
self.bind_cte(*span, bind_context, &table_name, alias, cte_info)
Expand Down
6 changes: 2 additions & 4 deletions src/query/sql/src/planner/binder/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,12 +405,12 @@ impl Binder {

pub(crate) fn bind_r_cte(
&mut self,
span: Span,
bind_context: &mut BindContext,
cte_info: &CteInfo,
cte_name: &str,
alias: &Option<TableAlias>,
) -> Result<(SExpr, BindContext)> {
// Recursive cte's query must be a union(all)
match &cte_info.query.body {
SetExpr::SetOperation(set_expr) => {
if set_expr.op != SetOperator::Union {
Expand All @@ -437,9 +437,7 @@ impl Binder {
}
Ok((union_s_expr, new_bind_ctx.clone()))
}
_ => Err(ErrorCode::SyntaxException(
"Recursive CTE must contain a UNION(ALL) query".to_string(),
)),
_ => self.bind_cte(span, bind_context, cte_name, alias, cte_info),
}
}

Expand Down
71 changes: 71 additions & 0 deletions tests/sqllogictests/suites/query/cte/basic_r_cte.test
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,74 @@ with recursive t as (select 1 as x union all select m.x+f.x from t as m, t as f
1
2
4

# recursive cte with normal cte
statement ok
create or replace table t1(a int);

statement ok
insert into t1 values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

query II
WITH RECURSIVE t(n) as (
select 1
union all
select n+1 from t where n<10
),
cte1 as (
select a from t1
)
select n, cte1.a from t join cte1 where t.n=cte1.a;
----
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9


query II
WITH RECURSIVE cte1 as (
select a from t1
),
t(n) as (
select 1
union all
select n+1 from t where n<10
)
select n, cte1.a from t join cte1 where t.n=cte1.a;
----
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9


query I
WITH RECURSIVE cte1 as (
select a from t1
)
select cte1.a from cte1;
----
0
1
2
3
4
5
6
7
8
9

statement ok
drop table t1;

0 comments on commit 73cd346

Please sign in to comment.