From 0b642f63efea94334f81297f3e4214b863fe3391 Mon Sep 17 00:00:00 2001 From: ti-srebot <66930949+ti-srebot@users.noreply.github.com> Date: Thu, 2 Sep 2021 18:28:14 +0800 Subject: [PATCH] expression: fix unexpected constant fold when year compare string (#23281) (#23336) --- expression/builtin_compare.go | 8 ++++---- expression/integration_test.go | 10 ++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/expression/builtin_compare.go b/expression/builtin_compare.go index 5225ddf773337..5d8afe1696916 100644 --- a/expression/builtin_compare.go +++ b/expression/builtin_compare.go @@ -1324,15 +1324,15 @@ func RefineComparedConstant(ctx sessionctx.Context, targetFieldType types.FieldT // We try to convert the string constant to double. // If the double result equals the int result, we can return the int result; // otherwise, the compare function will be false. + // **Notice** + // we can not compare double result to int result directly, because year type will change its value, like + // 2 to 2002, here we just check whether double value equal int(double value). We can assert the int(string) var doubleDatum types.Datum doubleDatum, err = dt.ConvertTo(sc, types.NewFieldType(mysql.TypeDouble)) if err != nil { return con, false } - if c, err = doubleDatum.CompareDatum(sc, &intDatum); err != nil { - return con, false - } - if c != 0 { + if doubleDatum.GetFloat64() != math.Trunc(doubleDatum.GetFloat64()) { return con, true } return &Constant{ diff --git a/expression/integration_test.go b/expression/integration_test.go index 5881820b40d54..62671a1fba58d 100644 --- a/expression/integration_test.go +++ b/expression/integration_test.go @@ -8949,6 +8949,16 @@ func (s *testIntegrationSuite) Test22717(c *C) { tk.MustQuery("select d from t where d").Check(testkit.Rows("0", "1", "0,1")) } +func (s *testIntegrationSuite) Test23262(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t") + tk.MustExec("create table t(a year)") + tk.MustExec("insert into t values(2002)") + tk.MustQuery("select * from t where a=2").Check(testkit.Rows("2002")) + tk.MustQuery("select * from t where a='2'").Check(testkit.Rows("2002")) +} + func (s *testIntegrationSerialSuite) TestPartitionPruningRelaxOP(c *C) { // Discovered while looking at issue 19941 (not completely related) // relaxOP relax the op > to >= and < to <=