From 8f911458934974c895e265950fb1a31ac8fd7940 Mon Sep 17 00:00:00 2001 From: ti-srebot <66930949+ti-srebot@users.noreply.github.com> Date: Thu, 16 Sep 2021 14:26:43 +0800 Subject: [PATCH] expression, executor: fix type infer for greatest/leastest(datetime) (#26533) (#26566) --- 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 b5c75f917f40a..5e3acc586b567 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -8710,3 +8710,12 @@ func (s *testSuite) TestEmptyTableSampleTemporaryTable(c *C) { rs.Check(testkit.Rows()) tk.MustExec("commit") } + +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 30de86394d7f9..5c9367004ec89 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 }