You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

172 lines
4.4 KiB

  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. if plugin == "" {
  101. plugin = defaultAuthPlugin
  102. }
  103. // Send Client Authentication Packet
  104. authResp, err := mc.auth(authData, plugin)
  105. if err != nil {
  106. // try the default auth plugin, if using the requested plugin failed
  107. errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error())
  108. plugin = defaultAuthPlugin
  109. authResp, err = mc.auth(authData, plugin)
  110. if err != nil {
  111. mc.cleanup()
  112. return nil, err
  113. }
  114. }
  115. if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil {
  116. mc.cleanup()
  117. return nil, err
  118. }
  119. // Handle response to auth packet, switch methods if possible
  120. if err = mc.handleAuthResult(authData, plugin); err != nil {
  121. // Authentication failed and MySQL has already closed the connection
  122. // (https://dev.mysql.com/doc/internals/en/authentication-fails.html).
  123. // Do not send COM_QUIT, just cleanup and return the error.
  124. mc.cleanup()
  125. return nil, err
  126. }
  127. if mc.cfg.MaxAllowedPacket > 0 {
  128. mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket
  129. } else {
  130. // Get max allowed packet size
  131. maxap, err := mc.getSystemVar("max_allowed_packet")
  132. if err != nil {
  133. mc.Close()
  134. return nil, err
  135. }
  136. mc.maxAllowedPacket = stringToInt(maxap) - 1
  137. }
  138. if mc.maxAllowedPacket < maxPacketSize {
  139. mc.maxWriteSize = mc.maxAllowedPacket
  140. }
  141. // Handle DSN Params
  142. err = mc.handleParams()
  143. if err != nil {
  144. mc.Close()
  145. return nil, err
  146. }
  147. return mc, nil
  148. }
  149. func init() {
  150. sql.Register("mysql", &MySQLDriver{})
  151. }