From dd2fadb1908573cee11ddc4c7992467a619a6a85 Mon Sep 17 00:00:00 2001 From: HuaiyuXu <391585975@qq.com> Date: Mon, 26 Jul 2021 17:04:16 +0800 Subject: [PATCH] expression, executor: fix type infer for greatest/leastest(datetime) (#26533) --- executor/executor_test.go | 9 +++++++++ expression/builtin_compare.go | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/executor/executor_test.go b/executor/executor_test.go index 06fd438d2a..b4aa4451d9 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -8783,3 +8783,12 @@ func (s *testSuite) TestIssue25506(c *C) { tk.MustExec("insert into tbl_23 values (0xF)") tk.MustQuery("(select col_15 from tbl_23) union all (select col_15 from tbl_3 for update) order by col_15").Check(testkit.Rows("\x00\x00\x0F", "\x00\x00\xFF", "\x00\xFF\xFF")) } + +func (s *testSuite) TestIssue26532(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustQuery("select greatest(cast(\"2020-01-01 01:01:01\" as datetime), cast(\"2019-01-01 01:01:01\" as datetime) )union select null;").Sort().Check(testkit.Rows("2020-01-01 01:01:01", "")) + tk.MustQuery("select least(cast(\"2020-01-01 01:01:01\" as datetime), cast(\"2019-01-01 01:01:01\" as datetime) )union select null;").Sort().Check(testkit.Rows("2019-01-01 01:01:01", "")) + tk.MustQuery("select greatest(\"2020-01-01 01:01:01\" ,\"2019-01-01 01:01:01\" )union select null;").Sort().Check(testkit.Rows("2020-01-01 01:01:01", "")) + tk.MustQuery("select least(\"2020-01-01 01:01:01\" , \"2019-01-01 01:01:01\" )union select null;").Sort().Check(testkit.Rows("2019-01-01 01:01:01", "")) +} diff --git a/expression/builtin_compare.go b/expression/builtin_compare.go index 30de86394d..5c9367004e 100644 --- a/expression/builtin_compare.go +++ b/expression/builtin_compare.go @@ -485,9 +485,23 @@ func (c *greatestFunctionClass) getFunction(ctx sessionctx.Context, args []Expre sig = &builtinGreatestTimeSig{bf} sig.setPbCode(tipb.ScalarFuncSig_GreatestTime) } + sig.getRetTp().Flen, sig.getRetTp().Decimal = fixFlenAndDecimalForGreatestAndLeast(args) return sig, nil } +func fixFlenAndDecimalForGreatestAndLeast(args []Expression) (flen, decimal int) { + for _, arg := range args { + argFlen, argDecimal := arg.GetType().Flen, arg.GetType().Decimal + if argFlen > flen { + flen = argFlen + } + if argDecimal > decimal { + decimal = argDecimal + } + } + return flen, decimal +} + type builtinGreatestIntSig struct { baseBuiltinFunc } @@ -702,6 +716,7 @@ func (c *leastFunctionClass) getFunction(ctx sessionctx.Context, args []Expressi sig = &builtinLeastTimeSig{bf} sig.setPbCode(tipb.ScalarFuncSig_LeastTime) } + sig.getRetTp().Flen, sig.getRetTp().Decimal = fixFlenAndDecimalForGreatestAndLeast(args) return sig, nil }