Skip to content

Commit c2402bd

Browse files
Dousir9everpcpc
authored andcommitted
chore(binder): fix bind cte (databendlabs#17183)
* chore(binder): fix bind cte * chore(test): add sqllogictest * chore(binder): refine code * chore(binder): remove materialized cte in create table stmt with * chore(binder): fix m_cte_to_temp_table * chore(code): refine code * chore(code): refine code
1 parent 0465f2e commit c2402bd

File tree

2 files changed

+24
-3
lines changed
  • src/query/sql/src/planner/binder/bind_query
  • tests/sqllogictests/suites/query/cte

2 files changed

+24
-3
lines changed

src/query/sql/src/planner/binder/bind_query/bind.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ impl Binder {
101101
};
102102
// If the CTE is materialized, we'll construct a temp table for it.
103103
if cte.materialized {
104-
self.m_cte_to_temp_table(cte)?;
104+
self.m_cte_to_temp_table(cte, idx, with.clone())?;
105105
}
106106
bind_context
107107
.cte_context
@@ -180,7 +180,7 @@ impl Binder {
180180
))
181181
}
182182

183-
fn m_cte_to_temp_table(&mut self, cte: &CTE) -> Result<()> {
183+
fn m_cte_to_temp_table(&mut self, cte: &CTE, cte_index: usize, mut with: With) -> Result<()> {
184184
let engine = if self.ctx.get_settings().get_persist_materialized_cte()? {
185185
Engine::Fuse
186186
} else {
@@ -207,6 +207,13 @@ impl Binder {
207207

208208
let expr_replacer = ExprReplacer::new(database.clone(), self.m_cte_table_name.clone());
209209
let mut as_query = cte.query.clone();
210+
with.ctes.truncate(cte_index);
211+
with.ctes.retain(|cte| !cte.materialized);
212+
as_query.with = if !with.ctes.is_empty() {
213+
Some(with)
214+
} else {
215+
None
216+
};
210217
expr_replacer.replace_query(&mut as_query);
211218

212219
let create_table_stmt = CreateTableStmt {

tests/sqllogictests/suites/query/cte/cte.test

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -557,4 +557,18 @@ statement ok
557557
drop table if exists t1;
558558

559559
statement ok
560-
drop table if exists t2;
560+
drop table if exists t2;
561+
562+
query T
563+
with t(tt) as (select number as tt from numbers(10)), t2(tt) AS MATERIALIZED (SELECT tt FROM t) select * from t2;
564+
----
565+
0
566+
1
567+
2
568+
3
569+
4
570+
5
571+
6
572+
7
573+
8
574+
9

0 commit comments

Comments
 (0)