connection.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2012 Julien Schmidt. All rights reserved.
  4. // http://www.julienschmidt.com
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla Public
  7. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  8. // You can obtain one at http://mozilla.org/MPL/2.0/.
  9. package mysql
  10. import (
  11. "bufio"
  12. "database/sql/driver"
  13. "errors"
  14. "net"
  15. "strconv"
  16. "time"
  17. )
  18. type mysqlConn struct {
  19. cfg *config
  20. server *serverSettings
  21. netConn net.Conn
  22. bufReader *bufio.Reader
  23. protocol uint8
  24. sequence uint8
  25. affectedRows uint64
  26. insertId uint64
  27. lastCmdTime time.Time
  28. keepaliveTimer *time.Timer
  29. }
  30. type config struct {
  31. user string
  32. passwd string
  33. net string
  34. addr string
  35. dbname string
  36. params map[string]string
  37. }
  38. type serverSettings struct {
  39. protocol byte
  40. version string
  41. flags ClientFlag
  42. charset uint8
  43. scrambleBuff []byte
  44. threadID uint32
  45. keepalive int64
  46. }
  47. // Handles parameters set in DSN
  48. func (mc *mysqlConn) handleParams() (e error) {
  49. for param, val := range mc.cfg.params {
  50. switch param {
  51. // Charset
  52. case "charset":
  53. e = mc.exec("SET NAMES " + val)
  54. if e != nil {
  55. return
  56. }
  57. // TLS-Encryption
  58. case "tls":
  59. dbgLog.Print("TLS-Encryption not implemented yet")
  60. // Compression
  61. case "compress":
  62. dbgLog.Print("Compression not implemented yet")
  63. // We don't want to set keepalive as system var
  64. case "keepalive":
  65. continue
  66. // System Vars
  67. default:
  68. e = mc.exec("SET " + param + "=" + val + "")
  69. if e != nil {
  70. return
  71. }
  72. }
  73. }
  74. // KeepAlive
  75. if val, param := mc.cfg.params["keepalive"]; param {
  76. mc.server.keepalive, e = strconv.ParseInt(val, 10, 64)
  77. if e != nil {
  78. return errors.New("Invalid keepalive time")
  79. }
  80. // Get keepalive time by MySQL system var wait_timeout
  81. if mc.server.keepalive == 1 {
  82. val, e = mc.getSystemVar("wait_timeout")
  83. mc.server.keepalive, e = strconv.ParseInt(val, 10, 64)
  84. if e != nil {
  85. return errors.New("Error getting wait_timeout")
  86. }
  87. // Trigger 1min BEFORE wait_timeout
  88. if mc.server.keepalive > 60 {
  89. mc.server.keepalive -= 60
  90. }
  91. }
  92. if mc.server.keepalive > 0 {
  93. mc.lastCmdTime = time.Now()
  94. // Ping-Timer to avoid timeout
  95. mc.keepaliveTimer = time.AfterFunc(
  96. time.Duration(mc.server.keepalive)*time.Second, func() {
  97. var diff time.Duration
  98. for {
  99. // Fires only if diff > keepalive. Makes it collision safe
  100. for mc.netConn != nil &&
  101. mc.lastCmdTime.Unix()+mc.server.keepalive > time.Now().Unix() {
  102. diff = mc.lastCmdTime.Sub(time.Unix(time.Now().Unix()-mc.server.keepalive, 0))
  103. time.Sleep(diff)
  104. }
  105. if mc.netConn != nil {
  106. if e := mc.Ping(); e != nil {
  107. break
  108. }
  109. } else {
  110. return
  111. }
  112. }
  113. })
  114. }
  115. }
  116. return
  117. }
  118. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  119. e := mc.exec("START TRANSACTION")
  120. if e != nil {
  121. return nil, e
  122. }
  123. return &mysqlTx{mc}, e
  124. }
  125. func (mc *mysqlConn) Close() (e error) {
  126. if mc.server.keepalive > 0 {
  127. mc.keepaliveTimer.Stop()
  128. }
  129. mc.writeCommandPacket(COM_QUIT)
  130. mc.bufReader = nil
  131. mc.netConn.Close()
  132. mc.netConn = nil
  133. return
  134. }
  135. func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
  136. // Send command
  137. e := mc.writeCommandPacket(COM_STMT_PREPARE, query)
  138. if e != nil {
  139. return nil, e
  140. }
  141. stmt := mysqlStmt{new(stmtContent)}
  142. stmt.mc = mc
  143. // Read Result
  144. var columnCount uint16
  145. columnCount, e = stmt.readPrepareResultPacket()
  146. if e != nil {
  147. return nil, e
  148. }
  149. if stmt.paramCount > 0 {
  150. stmt.params, e = stmt.mc.readColumns(stmt.paramCount)
  151. if e != nil {
  152. return nil, e
  153. }
  154. }
  155. if columnCount > 0 {
  156. _, e = stmt.mc.readUntilEOF()
  157. if e != nil {
  158. return nil, e
  159. }
  160. }
  161. return stmt, e
  162. }
  163. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  164. if len(args) > 0 {
  165. return nil, driver.ErrSkip
  166. }
  167. mc.affectedRows = 0
  168. mc.insertId = 0
  169. e := mc.exec(query)
  170. if e != nil {
  171. return nil, e
  172. }
  173. if mc.affectedRows == 0 && mc.insertId == 0 {
  174. return driver.ResultNoRows, e
  175. }
  176. return &mysqlResult{
  177. affectedRows: int64(mc.affectedRows),
  178. insertId: int64(mc.insertId)},
  179. e
  180. }
  181. // Internal function to execute statements
  182. func (mc *mysqlConn) exec(query string) (e error) {
  183. // Send command
  184. e = mc.writeCommandPacket(COM_QUERY, query)
  185. if e != nil {
  186. return
  187. }
  188. // Read Result
  189. resLen, e := mc.readResultSetHeaderPacket()
  190. if e != nil {
  191. return
  192. }
  193. if resLen > 0 {
  194. _, e = mc.readUntilEOF()
  195. if e != nil {
  196. return
  197. }
  198. mc.affectedRows, e = mc.readUntilEOF()
  199. if e != nil {
  200. return
  201. }
  202. }
  203. return
  204. }
  205. // Gets the value of the given MySQL System Variable
  206. func (mc *mysqlConn) getSystemVar(name string) (val string, e error) {
  207. // Send command
  208. e = mc.writeCommandPacket(COM_QUERY, "SELECT @@"+name)
  209. if e != nil {
  210. return
  211. }
  212. // Read Result
  213. resLen, e := mc.readResultSetHeaderPacket()
  214. if e != nil {
  215. return
  216. }
  217. if resLen > 0 {
  218. var n uint64
  219. n, e = mc.readUntilEOF()
  220. if e != nil {
  221. return
  222. }
  223. var rows []*[]*[]byte
  224. rows, e = mc.readRows(int(n))
  225. if e != nil {
  226. return
  227. }
  228. val = string(*(*rows[0])[0])
  229. }
  230. return
  231. }
  232. // *** DEPRECATED ***
  233. // Executes a simple Ping-CMD to test or keepalive the connection
  234. func (mc *mysqlConn) Ping() (e error) {
  235. // Send command
  236. e = mc.writeCommandPacket(COM_PING)
  237. if e != nil {
  238. return
  239. }
  240. // Read Result
  241. e = mc.readResultOK()
  242. return
  243. }