Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/query/sql/src/planner/binder/bind_query/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl Binder {
};
// If the CTE is materialized, we'll construct a temp table for it.
if cte.materialized {
self.m_cte_to_temp_table(cte)?;
self.m_cte_to_temp_table(cte, idx, with.clone())?;
}
bind_context
.cte_context
Expand Down Expand Up @@ -180,7 +180,7 @@ impl Binder {
))
}

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

let expr_replacer = ExprReplacer::new(database.clone(), self.m_cte_table_name.clone());
let mut as_query = cte.query.clone();
with.ctes.truncate(cte_index);
with.ctes.retain(|cte| !cte.materialized);
as_query.with = if !with.ctes.is_empty() {
Some(with)
} else {
None
};
expr_replacer.replace_query(&mut as_query);

let create_table_stmt = CreateTableStmt {
Expand Down
16 changes: 15 additions & 1 deletion tests/sqllogictests/suites/query/cte/cte.test
Original file line number Diff line number Diff line change
Expand Up @@ -557,4 +557,18 @@ statement ok
drop table if exists t1;

statement ok
drop table if exists t2;
drop table if exists t2;

query T
with t(tt) as (select number as tt from numbers(10)), t2(tt) AS MATERIALIZED (SELECT tt FROM t) select * from t2;
----
0
1
2
3
4
5
6
7
8
9
Loading