Skip to content

Commit

Permalink
expression, planner: exclude concat_ws from aggresive folding constant (
Browse files Browse the repository at this point in the history
#38383)

close #36888
  • Loading branch information
YangKeao committed Jan 10, 2023
1 parent 46e67d2 commit 02332b2
Show file tree
Hide file tree
Showing 3 changed files with 28 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
13 changes: 13 additions & 0 deletions planner/core/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8309,6 +8309,19 @@ func TestAutoIncrementCheckWithCheckConstraint(t *testing.T) {
)`)
}

// 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>"))
}

// https://github.com/pingcap/tidb/issues/40285.
func TestIssue40285(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
Expand Down

0 comments on commit 02332b2

Please sign in to comment.