driver.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package mysql provides a MySQL driver for Go's database/sql package.
  7. //
  8. // The driver should be used via the database/sql package:
  9. //
  10. // import "database/sql"
  11. // import _ "github.com/go-sql-driver/mysql"
  12. //
  13. // db, err := sql.Open("mysql", "user:password@/dbname")
  14. //
  15. // See https://github.com/go-sql-driver/mysql#usage for details
  16. package mysql
  17. import (
  18. "database/sql"
  19. "database/sql/driver"
  20. "net"
  21. "sync"
  22. )
  23. // watcher interface is used for context support (From Go 1.8)
  24. type watcher interface {
  25. startWatcher()
  26. }
  27. // MySQLDriver is exported to make the driver directly accessible.
  28. // In general the driver is used via the database/sql package.
  29. type MySQLDriver struct{}
  30. // DialFunc is a function which can be used to establish the network connection.
  31. // Custom dial functions must be registered with RegisterDial
  32. type DialFunc func(addr string) (net.Conn, error)
  33. var (
  34. dialsLock sync.RWMutex
  35. dials map[string]DialFunc
  36. )
  37. // RegisterDial registers a custom dial function. It can then be used by the
  38. // network address mynet(addr), where mynet is the registered new network.
  39. // addr is passed as a parameter to the dial function.
  40. func RegisterDial(net string, dial DialFunc) {
  41. dialsLock.Lock()
  42. defer dialsLock.Unlock()
  43. if dials == nil {
  44. dials = make(map[string]DialFunc)
  45. }
  46. dials[net] = dial
  47. }
  48. // Open new Connection.
  49. // See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
  50. // the DSN string is formated
  51. func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
  52. var err error
  53. // New mysqlConn
  54. mc := &mysqlConn{
  55. maxAllowedPacket: maxPacketSize,
  56. maxWriteSize: maxPacketSize - 1,
  57. closech: make(chan struct{}),
  58. }
  59. mc.cfg, err = ParseDSN(dsn)
  60. if err != nil {
  61. return nil, err
  62. }
  63. mc.parseTime = mc.cfg.ParseTime
  64. // Connect to Server
  65. dialsLock.RLock()
  66. dial, ok := dials[mc.cfg.Net]
  67. dialsLock.RUnlock()
  68. if ok {
  69. mc.netConn, err = dial(mc.cfg.Addr)
  70. } else {
  71. nd := net.Dialer{Timeout: mc.cfg.Timeout}
  72. mc.netConn, err = nd.Dial(mc.cfg.Net, mc.cfg.Addr)
  73. }
  74. if err != nil {
  75. return nil, err
  76. }
  77. // Enable TCP Keepalives on TCP connections
  78. if tc, ok := mc.netConn.(*net.TCPConn); ok {
  79. if err := tc.SetKeepAlive(true); err != nil {
  80. // Don't send COM_QUIT before handshake.
  81. mc.netConn.Close()
  82. mc.netConn = nil
  83. return nil, err
  84. }
  85. }
  86. // Call startWatcher for context support (From Go 1.8)
  87. if s, ok := interface{}(mc).(watcher); ok {
  88. s.startWatcher()
  89. }
  90. mc.buf = newBuffer(mc.netConn)
  91. // Set I/O timeouts
  92. mc.buf.timeout = mc.cfg.ReadTimeout
  93. mc.writeTimeout = mc.cfg.WriteTimeout
  94. // Reading Handshake Initialization Packet
  95. authData, plugin, err := mc.readHandshakePacket()
  96. if err != nil {
  97. mc.cleanup()
  98. return nil, err
  99. }
  100. // Send Client Authentication Packet
  101. authResp, addNUL, err := mc.auth(authData, plugin)
  102. if err != nil {
  103. // try the default auth plugin, if using the requested plugin failed
  104. errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error())
  105. plugin = defaultAuthPlugin
  106. authResp, addNUL, err = mc.auth(authData, plugin)
  107. if err != nil {
  108. mc.cleanup()
  109. return nil, err
  110. }
  111. }
  112. if err = mc.writeHandshakeResponsePacket(authResp, addNUL, plugin); err != nil {
  113. mc.cleanup()
  114. return nil, err
  115. }
  116. // Handle response to auth packet, switch methods if possible
  117. if err = mc.handleAuthResult(authData, plugin); err != nil {
  118. // Authentication failed and MySQL has already closed the connection
  119. // (https://dev.mysql.com/doc/internals/en/authentication-fails.html).
  120. // Do not send COM_QUIT, just cleanup and return the error.
  121. mc.cleanup()
  122. return nil, err
  123. }
  124. if mc.cfg.MaxAllowedPacket > 0 {
  125. mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket
  126. } else {
  127. // Get max allowed packet size
  128. maxap, err := mc.getSystemVar("max_allowed_packet")
  129. if err != nil {
  130. mc.Close()
  131. return nil, err
  132. }
  133. mc.maxAllowedPacket = stringToInt(maxap) - 1
  134. }
  135. if mc.maxAllowedPacket < maxPacketSize {
  136. mc.maxWriteSize = mc.maxAllowedPacket
  137. }
  138. // Handle DSN Params
  139. err = mc.handleParams()
  140. if err != nil {
  141. mc.Close()
  142. return nil, err
  143. }
  144. return mc, nil
  145. }
  146. func init() {
  147. sql.Register("mysql", &MySQLDriver{})
  148. }