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. "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. debug("TLS-Encryption not implemented yet")
  58. // Compression
  59. case "compress":
  60. debug("TLS-Encryption 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, paramCount uint16
  141. stmt.id, columnCount, paramCount, e = mc.readPrepareResultPacket()
  142. if e != nil {
  143. return
  144. }
  145. if paramCount > 0 {
  146. stmt.params, e = stmt.mc.readColumns(int(paramCount))
  147. if e != nil {
  148. return
  149. }
  150. }
  151. stmt.paramCount = int(paramCount)
  152. if columnCount > 0 {
  153. _, e = stmt.mc.readColumns(int(columnCount))
  154. if e != nil {
  155. return
  156. }
  157. }
  158. stmt.query = query
  159. ds = stmt
  160. return
  161. }
  162. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  163. if len(args) > 0 {
  164. return nil, driver.ErrSkip
  165. }
  166. mc.affectedRows = 0
  167. mc.insertId = 0
  168. e := mc.exec(query)
  169. if e != nil {
  170. return nil, e
  171. }
  172. if mc.affectedRows == 0 {
  173. return driver.ResultNoRows, e
  174. }
  175. return &mysqlResult{
  176. affectedRows: int64(mc.affectedRows),
  177. insertId: int64(mc.insertId)},
  178. e
  179. }
  180. // Internal function to execute statements
  181. func (mc *mysqlConn) exec(query string) (e error) {
  182. // Send command
  183. e = mc.writeCommandPacket(COM_QUERY, query)
  184. if e != nil {
  185. return
  186. }
  187. // Read Result
  188. resLen, e := mc.readResultSetHeaderPacket()
  189. if e != nil {
  190. return
  191. }
  192. mc.affectedRows = 0
  193. mc.insertId = 0
  194. if resLen > 0 {
  195. _, e = mc.readUntilEOF()
  196. if e != nil {
  197. return
  198. }
  199. mc.affectedRows, e = mc.readUntilEOF()
  200. if e != nil {
  201. return
  202. }
  203. }
  204. return
  205. }
  206. // Gets the value of the given MySQL System Variable
  207. func (mc *mysqlConn) getSystemVar(name string) (val string, e error) {
  208. // Send command
  209. e = mc.writeCommandPacket(COM_QUERY, "SELECT @@"+name)
  210. if e != nil {
  211. return
  212. }
  213. // Read Result
  214. resLen, e := mc.readResultSetHeaderPacket()
  215. if e != nil {
  216. return
  217. }
  218. if resLen > 0 {
  219. var n uint64
  220. n, e = mc.readUntilEOF()
  221. if e != nil {
  222. return
  223. }
  224. var rows []*[]*[]byte
  225. rows, e = mc.readRows(int(n))
  226. if e != nil {
  227. return
  228. }
  229. val = string(*(*rows[0])[0])
  230. }
  231. return
  232. }
  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. }