connection.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. "database/sql/driver"
  12. "errors"
  13. "net"
  14. "strconv"
  15. "time"
  16. )
  17. type mysqlConn struct {
  18. cfg *config
  19. server *serverSettings
  20. netConn net.Conn
  21. protocol uint8
  22. sequence uint8
  23. affectedRows uint64
  24. insertId uint64
  25. lastCmdTime time.Time
  26. keepaliveTimer *time.Timer
  27. }
  28. type config struct {
  29. user string
  30. passwd string
  31. net string
  32. addr string
  33. dbname string
  34. params map[string]string
  35. }
  36. type serverSettings struct {
  37. protocol byte
  38. version string
  39. flags ClientFlag
  40. charset uint8
  41. scrambleBuff []byte
  42. threadID uint32
  43. keepalive int64
  44. }
  45. // Handles parameters set in DSN
  46. func (mc *mysqlConn) handleParams() (e error) {
  47. for param, val := range mc.cfg.params {
  48. switch param {
  49. // Charset
  50. case "charset":
  51. e = mc.exec("SET NAMES " + val)
  52. if e != nil {
  53. return
  54. }
  55. // TLS-Encryption
  56. case "tls":
  57. dbgLog.Print("TLS-Encryption not implemented yet")
  58. // Compression
  59. case "compress":
  60. dbgLog.Print("Compression not implemented yet")
  61. // We don't want to set keepalive as system var
  62. case "keepalive":
  63. continue
  64. // System Vars
  65. default:
  66. e = mc.exec("SET " + param + "=" + val + "")
  67. if e != nil {
  68. return
  69. }
  70. }
  71. }
  72. // KeepAlive
  73. if val, param := mc.cfg.params["keepalive"]; param {
  74. mc.server.keepalive, e = strconv.ParseInt(val, 10, 64)
  75. if e != nil {
  76. return errors.New("Invalid keepalive time")
  77. }
  78. // Get keepalive time by MySQL system var wait_timeout
  79. if mc.server.keepalive == 1 {
  80. val, e = mc.getSystemVar("wait_timeout")
  81. mc.server.keepalive, e = strconv.ParseInt(val, 10, 64)
  82. if e != nil {
  83. return errors.New("Error getting wait_timeout")
  84. }
  85. // Trigger 1min BEFORE wait_timeout
  86. if mc.server.keepalive > 60 {
  87. mc.server.keepalive -= 60
  88. }
  89. }
  90. if mc.server.keepalive > 0 {
  91. mc.lastCmdTime = time.Now()
  92. // Ping-Timer to avoid timeout
  93. mc.keepaliveTimer = time.AfterFunc(
  94. time.Duration(mc.server.keepalive)*time.Second, func() {
  95. var diff time.Duration
  96. for {
  97. // Fires only if diff > keepalive. Makes it collision safe
  98. for mc.netConn != nil &&
  99. mc.lastCmdTime.Unix()+mc.server.keepalive > time.Now().Unix() {
  100. diff = mc.lastCmdTime.Sub(time.Unix(time.Now().Unix()-mc.server.keepalive, 0))
  101. time.Sleep(diff)
  102. }
  103. if mc.netConn != nil {
  104. if e := mc.Ping(); e != nil {
  105. break
  106. }
  107. } else {
  108. return
  109. }
  110. }
  111. })
  112. }
  113. }
  114. return
  115. }
  116. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  117. e := mc.exec("START TRANSACTION")
  118. if e != nil {
  119. return nil, e
  120. }
  121. return &mysqlTx{mc}, e
  122. }
  123. func (mc *mysqlConn) Close() (e error) {
  124. if mc.server.keepalive > 0 {
  125. mc.keepaliveTimer.Stop()
  126. }
  127. mc.writeCommandPacket(COM_QUIT)
  128. mc.netConn = nil
  129. return
  130. }
  131. func (mc *mysqlConn) Prepare(query string) (ds driver.Stmt, e error) {
  132. // Send command
  133. e = mc.writeCommandPacket(COM_STMT_PREPARE, query)
  134. if e != nil {
  135. return
  136. }
  137. stmt := mysqlStmt{new(stmtContent)}
  138. stmt.mc = mc
  139. // Read Result
  140. var columnCount uint16
  141. columnCount, e = stmt.readPrepareResultPacket()
  142. if e != nil {
  143. return
  144. }
  145. if stmt.paramCount > 0 {
  146. stmt.params, e = stmt.mc.readColumns(stmt.paramCount)
  147. if e != nil {
  148. return
  149. }
  150. }
  151. if columnCount > 0 {
  152. _, e = stmt.mc.readColumns(int(columnCount))
  153. if e != nil {
  154. return
  155. }
  156. }
  157. stmt.query = query
  158. ds = stmt
  159. return
  160. }
  161. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  162. if len(args) > 0 {
  163. return nil, driver.ErrSkip
  164. }
  165. mc.affectedRows = 0
  166. mc.insertId = 0
  167. e := mc.exec(query)
  168. if e != nil {
  169. return nil, e
  170. }
  171. if mc.affectedRows == 0 {
  172. return driver.ResultNoRows, e
  173. }
  174. return &mysqlResult{
  175. affectedRows: int64(mc.affectedRows),
  176. insertId: int64(mc.insertId)},
  177. e
  178. }
  179. // Internal function to execute statements
  180. func (mc *mysqlConn) exec(query string) (e error) {
  181. // Send command
  182. e = mc.writeCommandPacket(COM_QUERY, query)
  183. if e != nil {
  184. return
  185. }
  186. // Read Result
  187. resLen, e := mc.readResultSetHeaderPacket()
  188. if e != nil {
  189. return
  190. }
  191. mc.affectedRows = 0
  192. mc.insertId = 0
  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. // Executes a simple Ping-CMD to test or keepalive the connection
  233. func (mc *mysqlConn) Ping() (e error) {
  234. // Send command
  235. e = mc.writeCommandPacket(COM_PING)
  236. if e != nil {
  237. return
  238. }
  239. // Read Result
  240. e = mc.readResultOK()
  241. return
  242. }