From d53524f34e638b88cdc87628af24bbc38d27fd1a Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Wed, 27 Sep 2023 13:52:01 +0800 Subject: [PATCH] fix: materialized cte is defined but not be used (#13046) --- src/query/sql/src/planner/binder/binder.rs | 2 +- .../suites/query/materialized_cte.test | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/query/sql/src/planner/binder/binder.rs b/src/query/sql/src/planner/binder/binder.rs index 2a8dc4f466f4..342d81b6722c 100644 --- a/src/query/sql/src/planner/binder/binder.rs +++ b/src/query/sql/src/planner/binder/binder.rs @@ -181,7 +181,7 @@ impl<'a> Binder { let (mut s_expr, bind_context) = self.bind_query(bind_context, query).await?; // Wrap `LogicalMaterializedCte` to `s_expr` for (_, cte_info) in self.ctes_map.iter().rev() { - if !cte_info.materialized { + if !cte_info.materialized || cte_info.used_count == 0{ continue; } let cte_s_expr = self.m_cte_bound_s_expr.get(&cte_info.cte_idx).unwrap(); diff --git a/tests/sqllogictests/suites/query/materialized_cte.test b/tests/sqllogictests/suites/query/materialized_cte.test index 50c0fd2301ff..7952243cae27 100644 --- a/tests/sqllogictests/suites/query/materialized_cte.test +++ b/tests/sqllogictests/suites/query/materialized_cte.test @@ -189,3 +189,19 @@ with t1 as materialized (select number as a from numbers(10)), t2 as materialize 0 0 0 + +statement ok +create table test (a int, b string); + +statement ok +insert into test values (1, 'a'), (2, 'b'); + +# main query doesn't use materialized cte, but materialized cte is defined +query TT rowsort +WITH tq9v2(cHAx0) AS materialized (SELECT a AS cHAx0 FROM test) SELECT b from test; +---- +a +b + +statement ok +drop table test