1 // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
3 // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
5 // This Source Code Form is subject to the terms of the Mozilla Public
6 // License, v. 2.0. If a copy of the MPL was not distributed with this file,
7 // You can obtain one at http://mozilla.org/MPL/2.0/.
26 // Registry for custom tls.Configs
28 tlsConfigLock sync.RWMutex
29 tlsConfigRegistry map[string]*tls.Config
32 // RegisterTLSConfig registers a custom tls.Config to be used with sql.Open.
33 // Use the key as a value in the DSN where tls=value.
35 // Note: The provided tls.Config is exclusively owned by the driver after
38 // rootCertPool := x509.NewCertPool()
39 // pem, err := ioutil.ReadFile("/path/ca-cert.pem")
43 // if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
44 // log.Fatal("Failed to append PEM.")
46 // clientCert := make([]tls.Certificate, 0, 1)
47 // certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem")
51 // clientCert = append(clientCert, certs)
52 // mysql.RegisterTLSConfig("custom", &tls.Config{
53 // RootCAs: rootCertPool,
54 // Certificates: clientCert,
56 // db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom")
58 func RegisterTLSConfig(key string, config *tls.Config) error {
59 if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" {
60 return fmt.Errorf("key '%s' is reserved", key)
64 if tlsConfigRegistry == nil {
65 tlsConfigRegistry = make(map[string]*tls.Config)
68 tlsConfigRegistry[key] = config
69 tlsConfigLock.Unlock()
73 // DeregisterTLSConfig removes the tls.Config associated with key.
74 func DeregisterTLSConfig(key string) {
76 if tlsConfigRegistry != nil {
77 delete(tlsConfigRegistry, key)
79 tlsConfigLock.Unlock()
82 func getTLSConfigClone(key string) (config *tls.Config) {
84 if v, ok := tlsConfigRegistry[key]; ok {
87 tlsConfigLock.RUnlock()
91 // Returns the bool value of the input.
92 // The 2nd return value indicates if the input was a valid bool value
93 func readBool(input string) (value bool, valid bool) {
95 case "1", "true", "TRUE", "True":
97 case "0", "false", "FALSE", "False":
101 // Not a valid bool value
105 /******************************************************************************
106 * Time related utils *
107 ******************************************************************************/
109 // NullTime represents a time.Time that may be NULL.
110 // NullTime implements the Scanner interface so
111 // it can be used as a scan destination:
114 // err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
122 // This NullTime implementation is not driver-specific
123 type NullTime struct {
125 Valid bool // Valid is true if Time is not NULL
128 // Scan implements the Scanner interface.
129 // The value type must be time.Time or string / []byte (formatted time-string),
130 // otherwise Scan fails.
131 func (nt *NullTime) Scan(value interface{}) (err error) {
133 nt.Time, nt.Valid = time.Time{}, false
137 switch v := value.(type) {
139 nt.Time, nt.Valid = v, true
142 nt.Time, err = parseDateTime(string(v), time.UTC)
143 nt.Valid = (err == nil)
146 nt.Time, err = parseDateTime(v, time.UTC)
147 nt.Valid = (err == nil)
152 return fmt.Errorf("Can't convert %T to time.Time", value)
155 // Value implements the driver Valuer interface.
156 func (nt NullTime) Value() (driver.Value, error) {
163 func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
164 base := "0000-00-00 00:00:00.0000000"
166 case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM"
167 if str == base[:len(str)] {
170 t, err = time.Parse(timeFormat[:len(str)], str)
172 err = fmt.Errorf("invalid time string: %s", str)
177 if err == nil && loc != time.UTC {
179 h, mi, s := t.Clock()
180 t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
186 func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
189 return time.Time{}, nil
192 int(binary.LittleEndian.Uint16(data[:2])), // year
193 time.Month(data[2]), // month
200 int(binary.LittleEndian.Uint16(data[:2])), // year
201 time.Month(data[2]), // month
203 int(data[4]), // hour
204 int(data[5]), // minutes
205 int(data[6]), // seconds
211 int(binary.LittleEndian.Uint16(data[:2])), // year
212 time.Month(data[2]), // month
214 int(data[4]), // hour
215 int(data[5]), // minutes
216 int(data[6]), // seconds
217 int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds
221 return nil, fmt.Errorf("invalid DATETIME packet length %d", num)
224 // zeroDateTime is used in formatBinaryDateTime to avoid an allocation
225 // if the DATE or DATETIME has the zero value.
226 // It must never be changed.
227 // The current behavior depends on database/sql copying the result.
228 var zeroDateTime = []byte("0000-00-00 00:00:00.000000")
230 const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
231 const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
233 func appendMicrosecs(dst, src []byte, decimals int) []byte {
238 return append(dst, ".000000"[:decimals+1]...)
241 microsecs := binary.LittleEndian.Uint32(src[:4])
242 p1 := byte(microsecs / 10000)
243 microsecs -= 10000 * uint32(p1)
244 p2 := byte(microsecs / 100)
245 microsecs -= 100 * uint32(p2)
246 p3 := byte(microsecs)
250 return append(dst, '.',
251 digits10[p1], digits01[p1],
252 digits10[p2], digits01[p2],
253 digits10[p3], digits01[p3],
256 return append(dst, '.',
260 return append(dst, '.',
261 digits10[p1], digits01[p1],
264 return append(dst, '.',
265 digits10[p1], digits01[p1],
269 return append(dst, '.',
270 digits10[p1], digits01[p1],
271 digits10[p2], digits01[p2],
274 return append(dst, '.',
275 digits10[p1], digits01[p1],
276 digits10[p2], digits01[p2],
282 func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) {
283 // length expects the deterministic length of the zero value,
284 // negative time and 100+ hours are automatically added if needed
286 return zeroDateTime[:length], nil
288 var dst []byte // return value
289 var p1, p2, p3 byte // current digit pair
292 case 10, 19, 21, 22, 23, 24, 25, 26:
298 return nil, fmt.Errorf("illegal %s length %d", t, length)
307 return nil, fmt.Errorf("illegal %s packet length %d", t, len(src))
309 dst = make([]byte, 0, length)
310 // start with the date
311 year := binary.LittleEndian.Uint16(src[:2])
313 p1 = byte(year - 100*uint16(pt))
314 p2, p3 = src[2], src[3]
316 digits10[pt], digits01[pt],
317 digits10[p1], digits01[p1], '-',
318 digits10[p2], digits01[p2], '-',
319 digits10[p3], digits01[p3],
325 return append(dst, zeroDateTime[10:length]...), nil
327 dst = append(dst, ' ')
331 // p1 is 2-digit hour, src is after hour
332 p2, p3 = src[0], src[1]
334 digits10[p1], digits01[p1], ':',
335 digits10[p2], digits01[p2], ':',
336 digits10[p3], digits01[p3],
338 return appendMicrosecs(dst, src[2:], int(length)-20), nil
341 func formatBinaryTime(src []byte, length uint8) (driver.Value, error) {
342 // length expects the deterministic length of the zero value,
343 // negative time and 100+ hours are automatically added if needed
345 return zeroDateTime[11 : 11+length], nil
347 var dst []byte // return value
351 8, // time (can be up to 10 when negative and 100+ hours)
352 10, 11, 12, 13, 14, 15: // time with fractional seconds
354 return nil, fmt.Errorf("illegal TIME length %d", length)
359 return nil, fmt.Errorf("invalid TIME packet length %d", len(src))
361 // +2 to enable negative time and 100+ hours
362 dst = make([]byte, 0, length+2)
364 dst = append(dst, '-')
366 days := binary.LittleEndian.Uint32(src[1:5])
367 hours := int64(days)*24 + int64(src[5])
370 dst = strconv.AppendInt(dst, hours, 10)
372 dst = append(dst, digits10[hours], digits01[hours])
375 min, sec := src[6], src[7]
376 dst = append(dst, ':',
377 digits10[min], digits01[min], ':',
378 digits10[sec], digits01[sec],
380 return appendMicrosecs(dst, src[8:], int(length)-9), nil
383 /******************************************************************************
384 * Convert from and to bytes *
385 ******************************************************************************/
387 func uint64ToBytes(n uint64) []byte {
400 func uint64ToString(n uint64) []byte {
412 a[i] = uint8(n-q*10) + 0x30
417 a[i] = uint8(n) + 0x30
422 // treats string value as unsigned integer representation
423 func stringToInt(b []byte) int {
427 val += int(b[i] - 0x30)
432 // returns the string read as a bytes slice, wheter the value is NULL,
433 // the number of bytes read and an error, in case the string is longer than
435 func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
437 num, isNull, n := readLengthEncodedInteger(b)
439 return b[n:n], isNull, n, nil
446 return b[n-int(num) : n : n], false, n, nil
448 return nil, false, n, io.EOF
451 // returns the number of bytes skipped and an error, in case the string is
452 // longer than the input slice
453 func skipLengthEncodedString(b []byte) (int, error) {
455 num, _, n := readLengthEncodedInteger(b)
469 // returns the number read, whether the value is NULL and the number of bytes read
470 func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
481 // 252: value of following 2
483 return uint64(b[1]) | uint64(b[2])<<8, false, 3
485 // 253: value of following 3
487 return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
489 // 254: value of following 8
491 return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
492 uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
493 uint64(b[7])<<48 | uint64(b[8])<<56,
497 // 0-250: value of first byte
498 return uint64(b[0]), false, 1
501 // encodes a uint64 value and appends it to the given bytes slice
502 func appendLengthEncodedInteger(b []byte, n uint64) []byte {
505 return append(b, byte(n))
508 return append(b, 0xfc, byte(n), byte(n>>8))
511 return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
513 return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
514 byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
517 // reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize.
518 // If cap(buf) is not enough, reallocate new buffer.
519 func reserveBuffer(buf []byte, appendSize int) []byte {
520 newSize := len(buf) + appendSize
521 if cap(buf) < newSize {
522 // Grow buffer exponentially
523 newBuf := make([]byte, len(buf)*2+appendSize)
530 // escapeBytesBackslash escapes []byte with backslashes (\)
531 // This escapes the contents of a string (provided as []byte) by adding backslashes before special
532 // characters, and turning others into specific escape sequences, such as
533 // turning newlines into \n and null bytes into \0.
534 // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932
535 func escapeBytesBackslash(buf, v []byte) []byte {
537 buf = reserveBuffer(buf, len(v)*2)
539 for _, c := range v {
578 // escapeStringBackslash is similar to escapeBytesBackslash but for string.
579 func escapeStringBackslash(buf []byte, v string) []byte {
581 buf = reserveBuffer(buf, len(v)*2)
583 for i := 0; i < len(v); i++ {
623 // escapeBytesQuotes escapes apostrophes in []byte by doubling them up.
624 // This escapes the contents of a string by doubling up any apostrophes that
625 // it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
626 // effect on the server.
627 // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038
628 func escapeBytesQuotes(buf, v []byte) []byte {
630 buf = reserveBuffer(buf, len(v)*2)
632 for _, c := range v {
646 // escapeStringQuotes is similar to escapeBytesQuotes but for string.
647 func escapeStringQuotes(buf []byte, v string) []byte {
649 buf = reserveBuffer(buf, len(v)*2)
651 for i := 0; i < len(v); i++ {
666 /******************************************************************************
668 ******************************************************************************/
670 // noCopy may be embedded into structs which must not be copied
671 // after the first use.
673 // See https://github.com/golang/go/issues/8005#issuecomment-190753527
677 // Lock is a no-op used by -copylocks checker from `go vet`.
678 func (*noCopy) Lock() {}
680 // atomicBool is a wrapper around uint32 for usage as a boolean value with
682 type atomicBool struct {
687 // IsSet returns wether the current boolean value is true
688 func (ab *atomicBool) IsSet() bool {
689 return atomic.LoadUint32(&ab.value) > 0
692 // Set sets the value of the bool regardless of the previous value
693 func (ab *atomicBool) Set(value bool) {
695 atomic.StoreUint32(&ab.value, 1)
697 atomic.StoreUint32(&ab.value, 0)
701 // TrySet sets the value of the bool and returns wether the value changed
702 func (ab *atomicBool) TrySet(value bool) bool {
704 return atomic.SwapUint32(&ab.value, 1) == 0
706 return atomic.SwapUint32(&ab.value, 0) > 0
709 // atomicError is a wrapper for atomically accessed error values
710 type atomicError struct {
715 // Set sets the error value regardless of the previous value.
716 // The value must not be nil
717 func (ae *atomicError) Set(value error) {
718 ae.value.Store(value)
721 // Value returns the current error value
722 func (ae *atomicError) Value() error {
723 if v := ae.value.Load(); v != nil {
724 // this will panic if the value doesn't implement the error interface
730 func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {
731 dargs := make([]driver.Value, len(named))
732 for n, param := range named {
733 if len(param.Name) > 0 {
734 // TODO: support the use of Named Parameters #561
735 return nil, errors.New("mysql: driver does not support the use of Named Parameters")
737 dargs[n] = param.Value
742 func mapIsolationLevel(level driver.IsolationLevel) (string, error) {
743 switch sql.IsolationLevel(level) {
744 case sql.LevelRepeatableRead:
745 return "REPEATABLE READ", nil
746 case sql.LevelReadCommitted:
747 return "READ COMMITTED", nil
748 case sql.LevelReadUncommitted:
749 return "READ UNCOMMITTED", nil
750 case sql.LevelSerializable:
751 return "SERIALIZABLE", nil
753 return "", fmt.Errorf("mysql: unsupported isolation level: %v", level)