Skip to content

Commit

Permalink
exclude concat_ws from aggresive folding constant
Browse files Browse the repository at this point in the history
Signed-off-by: YangKeao <yangkeao@chunibyo.icu>
  • Loading branch information
YangKeao committed Nov 8, 2022
1 parent 6eb9379 commit ca4899d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion expression/constant_fold.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,12 @@ func foldConstant(expr Expression) (Expression, bool) {
}
}
if !allConstArg {
if !hasNullArg || !sc.InNullRejectCheck || x.FuncName.L == ast.NullEQ {
// try to optimize on the situation when not all arguments are const
// for most functions, if one of the arguments are NULL, the result can be a constant (NULL or something else)
//
// NullEQ and ConcatWS are excluded, because they could have different value when the non-constant value is
// 1 or NULL. For example, concat_ws(NULL, NULL) gives NULL, but concat_ws(1, NULL) gives ''
if !hasNullArg || !sc.InNullRejectCheck || x.FuncName.L == ast.NullEQ || x.FuncName.L == ast.ConcatWS {
return expr, isDeferredConst
}
constArgs := make([]Expression, len(args))
Expand Down
9 changes: 9 additions & 0 deletions expression/constant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,15 @@ func TestConstantFolding(t *testing.T) {
condition: newFunction(ast.LT, newColumn(0), newFunction(ast.Plus, newColumn(1), newFunction(ast.Plus, newLonglong(2), newLonglong(1)))),
result: "lt(Column#0, plus(Column#1, 3))",
},
{
condition: func() Expression {
expr := newFunction(ast.ConcatWS, newColumn(0), NewNull())
function := expr.(*ScalarFunction)
function.GetCtx().GetSessionVars().StmtCtx.InNullRejectCheck = true
return function
}(),
result: "concat_ws(cast(Column#0, var_string(20)), <nil>)",
},
}
for _, tt := range tests {
newConds := FoldConstant(tt.condition)
Expand Down
12 changes: 12 additions & 0 deletions planner/core/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7823,3 +7823,15 @@ func TestNullConditionForPrefixIndex(t *testing.T) {
" └─StreamAgg_9 1.00 cop[tikv] funcs:count(1)->Column#7",
" └─IndexRangeScan_17 99.90 cop[tikv] table:t1, index:idx2(c1, c2) range:[\"0xfff\" -inf,\"0xfff\" +inf], keep order:false, stats:pseudo"))
}

// https://github.com/pingcap/tidb/issues/36888.
func TestIssue36888(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("CREATE TABLE t0(c0 INT);")
tk.MustExec("CREATE TABLE t1(c0 INT);")

tk.MustExec("INSERT INTO t0 VALUES (NULL);")
tk.MustQuery("SELECT t0.c0 FROM t0 LEFT JOIN t1 ON t0.c0>=t1.c0 WHERE (CONCAT_WS(t0.c0, t1.c0) IS NULL);").Check(testkit.Rows("<nil>"))
}

0 comments on commit ca4899d

Please sign in to comment.