driver.go 4.2 KB

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