11package mysql
22
33import (
4+ "bytes"
5+ "encoding/binary"
46 "math"
57 "strconv"
8+ "time"
69
710 "github.com/pingcap/errors"
811 "github.com/siddontang/go/hack"
912)
1013
14+ func toBinaryDateTime (t time.Time ) ([]byte , error ) {
15+ var buf bytes.Buffer
16+
17+ if t .IsZero () {
18+ return nil , nil
19+ }
20+
21+ year , month , day := t .Year (), t .Month (), t .Day ()
22+ hour , min , sec := t .Hour (), t .Minute (), t .Second ()
23+ nanosec := t .Nanosecond ()
24+
25+ if nanosec > 0 {
26+ buf .WriteByte (byte (11 ))
27+ binary .Write (& buf , binary .LittleEndian , uint16 (year ))
28+ buf .WriteByte (byte (month ))
29+ buf .WriteByte (byte (day ))
30+ buf .WriteByte (byte (hour ))
31+ buf .WriteByte (byte (min ))
32+ buf .WriteByte (byte (sec ))
33+ binary .Write (& buf , binary .LittleEndian , uint32 (nanosec / 1000 ))
34+ } else if hour > 0 || min > 0 || sec > 0 {
35+ buf .WriteByte (byte (7 ))
36+ binary .Write (& buf , binary .LittleEndian , uint16 (year ))
37+ buf .WriteByte (byte (month ))
38+ buf .WriteByte (byte (day ))
39+ buf .WriteByte (byte (hour ))
40+ buf .WriteByte (byte (min ))
41+ buf .WriteByte (byte (sec ))
42+ } else {
43+ buf .WriteByte (byte (4 ))
44+ binary .Write (& buf , binary .LittleEndian , uint16 (year ))
45+ buf .WriteByte (byte (month ))
46+ buf .WriteByte (byte (day ))
47+ }
48+
49+ return buf .Bytes (), nil
50+ }
51+
1152func FormatTextValue (value interface {}) ([]byte , error ) {
1253 switch v := value .(type ) {
1354 case int8 :
@@ -38,6 +79,8 @@ func FormatTextValue(value interface{}) ([]byte, error) {
3879 return v , nil
3980 case string :
4081 return hack .Slice (v ), nil
82+ case time.Time :
83+ return hack .Slice (v .Format (time .DateTime )), nil
4184 case nil :
4285 return nil , nil
4386 default :
@@ -75,6 +118,8 @@ func formatBinaryValue(value interface{}) ([]byte, error) {
75118 return v , nil
76119 case string :
77120 return hack .Slice (v ), nil
121+ case time.Time :
122+ return toBinaryDateTime (v )
78123 default :
79124 return nil , errors .Errorf ("invalid type %T" , value )
80125 }
@@ -90,6 +135,8 @@ func fieldType(value interface{}) (typ uint8, err error) {
90135 typ = MYSQL_TYPE_DOUBLE
91136 case string , []byte :
92137 typ = MYSQL_TYPE_VAR_STRING
138+ case time.Time :
139+ typ = MYSQL_TYPE_DATETIME
93140 case nil :
94141 typ = MYSQL_TYPE_NULL
95142 default :
@@ -109,7 +156,7 @@ func formatField(field *Field, value interface{}) error {
109156 case float32 , float64 :
110157 field .Charset = 63
111158 field .Flag = BINARY_FLAG | NOT_NULL_FLAG
112- case string , []byte :
159+ case string , []byte , time. Time :
113160 field .Charset = 33
114161 case nil :
115162 field .Charset = 33
0 commit comments