Skip to content

Commit b444c5b

Browse files
authored
fix: The update in MERGE INTO was mistakenly optimized as a delete (#17571)
* fix: The update in MERGE INTO was mistakenly optimized as a delete * fix and add logic test
1 parent fd15140 commit b444c5b

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

โ€Žsrc/query/sql/src/planner/optimizer/optimizer.rs

+16-7
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ use crate::optimizer::RuleID;
4747
use crate::optimizer::SExpr;
4848
use crate::optimizer::DEFAULT_REWRITE_RULES;
4949
use crate::planner::query_executor::QueryExecutor;
50+
use crate::plans::ConstantTableScan;
5051
use crate::plans::CopyIntoLocationPlan;
5152
use crate::plans::Join;
5253
use crate::plans::JoinType;
@@ -558,20 +559,28 @@ async fn optimize_mutation(mut opt_ctx: OptimizerContext, s_expr: SExpr) -> Resu
558559
if !mutation.matched_evaluators.is_empty() {
559560
match inner_rel_op {
560561
RelOp::ConstantTableScan => {
561-
mutation.no_effect = true;
562+
let constant_table_scan = ConstantTableScan::try_from(input_s_expr.plan().clone())?;
563+
if constant_table_scan.num_rows == 0 {
564+
mutation.no_effect = true;
565+
}
562566
}
563567
RelOp::Join => {
564-
let right_child = input_s_expr.child(1)?;
568+
let mut right_child = input_s_expr.child(1)?;
565569
let mut right_child_rel = right_child.plan.rel_op();
566570
if right_child_rel == RelOp::Exchange {
567571
right_child_rel = right_child.child(0)?.plan.rel_op();
572+
right_child = right_child.child(0)?;
568573
}
569574
if right_child_rel == RelOp::ConstantTableScan {
570-
mutation.matched_evaluators = vec![MatchedEvaluator {
571-
condition: None,
572-
update: None,
573-
}];
574-
mutation.can_try_update_column_only = false;
575+
let constant_table_scan =
576+
ConstantTableScan::try_from(right_child.plan().clone())?;
577+
if constant_table_scan.num_rows == 0 {
578+
mutation.matched_evaluators = vec![MatchedEvaluator {
579+
condition: None,
580+
update: None,
581+
}];
582+
mutation.can_try_update_column_only = false;
583+
}
575584
}
576585
}
577586
_ => (),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
statement ok
2+
create or replace table test_merge(col1 varchar,col2 varchar,col3 varchar);
3+
4+
statement ok
5+
insert into test_merge values(2,'abc',2),(3,'abc',3),(4,'abc',4);
6+
7+
query II
8+
merge into test_merge as tba using (select * from (values('1','add','11'),('4','add','44'))) as tbb("col1","col2","col3") on tba.col1=tbb.col1 WHEN MATCHED THEN update set tba.col1=tbb.col1 ,tba.col2='update',tba.col3=tbb.col3;
9+
----
10+
1
11+
12+
query ITI
13+
select * from test_merge;
14+
----
15+
2 abc 2
16+
3 abc 3
17+
4 update 44
18+

0 commit comments

Comments
ย (0)