Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expression: set a collation according to the arguments for ifnull in constant folding (#52119) #52131

Merged
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
10 changes: 9 additions & 1 deletion expression/constant_fold.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,15 @@ func ifNullFoldHandler(expr *ScalarFunction) (Expression, bool) {
// evaluated to constArg.Value after foldConstant(args[0]), it's not
// needed to be checked.
if constArg.Value.IsNull() {
return foldConstant(args[1])
foldedExpr, isConstant := foldConstant(args[1])

// See https://github.com/pingcap/tidb/issues/51765. If the first argument can
// be folded into NULL, the collation of IFNULL should be the same as the second
// arguments.
expr.GetType().SetCharset(args[1].GetType().GetCharset())
expr.GetType().SetCollate(args[1].GetType().GetCollate())

return foldedExpr, isConstant
}
return constArg, isDeferred
}
Expand Down
20 changes: 20 additions & 0 deletions expression/integration_test/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8025,3 +8025,23 @@ func TestIssue50850(t *testing.T) {
testkit.Rows("01", "31", "34", "5D", "65", "A5", "A6", "B1", "D5", "FF"))
tk.MustExec("drop table if exists t3;")
}

func TestIssue51765(t *testing.T) {
store := testkit.CreateMockStore(t)

tk := testkit.NewTestKit(t, store)

tk.MustExec("use test")
tk.MustExec("create table t (id varbinary(16))")
tk.MustExec("create table t1(id char(16) charset utf8mb4 collate utf8mb4_general_ci)")
tk.MustExec("insert into t values ()")
tk.MustExec(`insert into t1 values ("Hello World")`)

tk.MustQuery("select collation(ifnull(concat(NULL), '~'))").Check(testkit.Rows("utf8mb4_bin"))
tk.MustQuery("select collation(ifnull(concat(NULL),ifnull(concat(NULL),'~')))").Check(testkit.Rows("utf8mb4_bin"))
tk.MustQuery("select collation(ifnull(concat(id),'~')) from t;").Check(testkit.Rows("binary"))
tk.MustQuery("select collation(ifnull(concat(NULL),ifnull(concat(id),'~'))) from t;").Check(testkit.Rows("binary"))
tk.MustQuery("select collation(ifnull(concat(id),ifnull(concat(id),'~'))) from t;").Check(testkit.Rows("binary"))
tk.MustQuery("select collation(ifnull(concat(NULL),id)) from t1;").Check(testkit.Rows("utf8mb4_general_ci"))
tk.MustQuery("select collation(ifnull(concat(NULL),ifnull(concat(NULL),id))) from t1;").Check(testkit.Rows("utf8mb4_general_ci"))
}