diff --git a/util/types/convert.go b/util/types/convert.go index d725015e1774b..00577070a3e80 100644 --- a/util/types/convert.go +++ b/util/types/convert.go @@ -15,6 +15,7 @@ package types import ( "strconv" + "time" "unicode" "github.com/juju/errors" @@ -138,6 +139,29 @@ func Convert(val interface{}, target *FieldType) (v interface{}, err error) { // } // TODO: check Flen return x, nil + case mysql.TypeYear: + var ( + intVal int64 + err error + ) + switch x := val.(type) { + case string: + intVal, err = StrToInt(x) + case mysql.Time: + return int16(x.Year()), nil + case mysql.Duration: + return int16(time.Now().Year()), nil + default: + intVal, err = ToInt64(x) + } + if err != nil { + return InvConv(val, tp) + } + y, err := mysql.AdjustYear(int(intVal)) + if err != nil { + return InvConv(val, tp) + } + return int16(y), nil default: panic("should never happen") } diff --git a/util/types/convert_test.go b/util/types/convert_test.go index d5c69830b28e9..53f5495de1238 100644 --- a/util/types/convert_test.go +++ b/util/types/convert_test.go @@ -15,6 +15,7 @@ package types import ( "math" + "time" . "github.com/pingcap/check" mysql "github.com/pingcap/tidb/mysqldef" @@ -153,6 +154,23 @@ func (s *testTypeConvertSuite) TestConvertType(c *C) { v, err = Convert(3.1415926, ft) c.Assert(err, IsNil) c.Assert(v.(mysql.Decimal).String(), Equals, "3.14159") + + // For TypeYear + ft = NewFieldType(mysql.TypeYear) + v, err = Convert("2015-11-11", ft) + c.Assert(err, IsNil) + c.Assert(v, Equals, int16(2015)) + v, err = Convert(2015, ft) + c.Assert(err, IsNil) + c.Assert(v, Equals, int16(2015)) + v, err = Convert(1800, ft) + c.Assert(err, NotNil) + dt, err := mysql.ParseDate("2015-11-11") + c.Assert(err, IsNil) + v, err = Convert(dt, ft) + c.Assert(v, Equals, int16(2015)) + v, err = Convert(mysql.ZeroDuration, ft) + c.Assert(v, Equals, int16(time.Now().Year())) } func testToInt64(c *C, val interface{}, expect int64) {