connection.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. "strings"
  17. "time"
  18. )
  19. type mysqlConn struct {
  20. cfg *config
  21. server *serverSettings
  22. netConn net.Conn
  23. bufReader *bufio.Reader
  24. protocol uint8
  25. sequence uint8
  26. affectedRows uint64
  27. insertId uint64
  28. lastCmdTime time.Time
  29. keepaliveTimer *time.Timer
  30. }
  31. type config struct {
  32. user string
  33. passwd string
  34. net string
  35. addr string
  36. dbname string
  37. params map[string]string
  38. }
  39. type serverSettings struct {
  40. protocol byte
  41. version string
  42. flags ClientFlag
  43. charset uint8
  44. scrambleBuff []byte
  45. threadID uint32
  46. keepalive int64
  47. }
  48. // Handles parameters set in DSN
  49. func (mc *mysqlConn) handleParams() (e error) {
  50. for param, val := range mc.cfg.params {
  51. switch param {
  52. // Charset
  53. case "charset":
  54. charsets := strings.Split(val, ",")
  55. for _, charset := range charsets {
  56. e = mc.exec("SET NAMES " + charset)
  57. if e == nil {
  58. break
  59. }
  60. }
  61. if e != nil {
  62. return
  63. }
  64. // TLS-Encryption
  65. case "tls":
  66. dbgLog.Print("TLS-Encryption not implemented yet")
  67. // Compression
  68. case "compress":
  69. dbgLog.Print("Compression not implemented yet")
  70. // We don't want to set keepalive as system var
  71. case "keepalive":
  72. continue
  73. // System Vars
  74. default:
  75. e = mc.exec("SET " + param + "=" + val + "")
  76. if e != nil {
  77. return
  78. }
  79. }
  80. }
  81. // KeepAlive
  82. if val, param := mc.cfg.params["keepalive"]; param {
  83. mc.server.keepalive, e = strconv.ParseInt(val, 10, 64)
  84. if e != nil {
  85. return errors.New("Invalid keepalive time")
  86. }
  87. // Get keepalive time by MySQL system var wait_timeout
  88. if mc.server.keepalive == 1 {
  89. val, e = mc.getSystemVar("wait_timeout")
  90. mc.server.keepalive, e = strconv.ParseInt(val, 10, 64)
  91. if e != nil {
  92. return errors.New("Error getting wait_timeout")
  93. }
  94. // Trigger 1min BEFORE wait_timeout
  95. if mc.server.keepalive > 60 {
  96. mc.server.keepalive -= 60
  97. }
  98. }
  99. if mc.server.keepalive > 0 {
  100. mc.lastCmdTime = time.Now()
  101. // Ping-Timer to avoid timeout
  102. mc.keepaliveTimer = time.AfterFunc(
  103. time.Duration(mc.server.keepalive)*time.Second, func() {
  104. var diff time.Duration
  105. for {
  106. // Fires only if diff > keepalive. Makes it collision safe
  107. for mc.netConn != nil &&
  108. mc.lastCmdTime.Unix()+mc.server.keepalive > time.Now().Unix() {
  109. diff = mc.lastCmdTime.Sub(time.Unix(time.Now().Unix()-mc.server.keepalive, 0))
  110. time.Sleep(diff)
  111. }
  112. if mc.netConn != nil {
  113. if e := mc.Ping(); e != nil {
  114. break
  115. }
  116. } else {
  117. return
  118. }
  119. }
  120. })
  121. }
  122. }
  123. return
  124. }
  125. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  126. e := mc.exec("START TRANSACTION")
  127. if e != nil {
  128. return nil, e
  129. }
  130. return &mysqlTx{mc}, e
  131. }
  132. func (mc *mysqlConn) Close() (e error) {
  133. if mc.server.keepalive > 0 {
  134. mc.keepaliveTimer.Stop()
  135. }
  136. mc.writeCommandPacket(COM_QUIT)
  137. mc.bufReader = nil
  138. mc.netConn.Close()
  139. mc.netConn = nil
  140. return
  141. }
  142. func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
  143. // Send command
  144. e := mc.writeCommandPacket(COM_STMT_PREPARE, query)
  145. if e != nil {
  146. return nil, e
  147. }
  148. stmt := mysqlStmt{new(stmtContent)}
  149. stmt.mc = mc
  150. // Read Result
  151. var columnCount uint16
  152. columnCount, e = stmt.readPrepareResultPacket()
  153. if e != nil {
  154. return nil, e
  155. }
  156. if stmt.paramCount > 0 {
  157. stmt.params, e = stmt.mc.readColumns(stmt.paramCount)
  158. if e != nil {
  159. return nil, e
  160. }
  161. }
  162. if columnCount > 0 {
  163. _, e = stmt.mc.readUntilEOF()
  164. if e != nil {
  165. return nil, e
  166. }
  167. }
  168. return stmt, e
  169. }
  170. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  171. if len(args) > 0 {
  172. return nil, driver.ErrSkip
  173. }
  174. mc.affectedRows = 0
  175. mc.insertId = 0
  176. e := mc.exec(query)
  177. if e != nil {
  178. return nil, e
  179. }
  180. if mc.affectedRows == 0 && mc.insertId == 0 {
  181. return driver.ResultNoRows, e
  182. }
  183. return &mysqlResult{
  184. affectedRows: int64(mc.affectedRows),
  185. insertId: int64(mc.insertId)},
  186. e
  187. }
  188. // Internal function to execute commands
  189. func (mc *mysqlConn) exec(query string) (e error) {
  190. // Send command
  191. e = mc.writeCommandPacket(COM_QUERY, query)
  192. if e != nil {
  193. return
  194. }
  195. // Read Result
  196. var resLen int
  197. resLen, e = mc.readResultSetHeaderPacket()
  198. if e != nil {
  199. return
  200. }
  201. if resLen > 0 {
  202. _, e = mc.readUntilEOF()
  203. if e != nil {
  204. return
  205. }
  206. mc.affectedRows, e = mc.readUntilEOF()
  207. if e != nil {
  208. return
  209. }
  210. }
  211. return
  212. }
  213. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  214. if len(args) > 0 {
  215. return nil, driver.ErrSkip
  216. }
  217. // Send command
  218. e := mc.writeCommandPacket(COM_QUERY, query)
  219. if e != nil {
  220. return nil, e
  221. }
  222. // Read Result
  223. var resLen int
  224. resLen, e = mc.readResultSetHeaderPacket()
  225. if e != nil {
  226. return nil, e
  227. }
  228. rows := mysqlRows{&rowsContent{mc, false, nil, false}}
  229. if resLen > 0 {
  230. // Columns
  231. rows.content.columns, e = mc.readColumns(resLen)
  232. if e != nil {
  233. return nil, e
  234. }
  235. }
  236. return rows, e
  237. }
  238. // Gets the value of the given MySQL System Variable
  239. func (mc *mysqlConn) getSystemVar(name string) (val string, e error) {
  240. // Send command
  241. e = mc.writeCommandPacket(COM_QUERY, "SELECT @@"+name)
  242. if e != nil {
  243. return
  244. }
  245. // Read Result
  246. resLen, e := mc.readResultSetHeaderPacket()
  247. if e != nil {
  248. return
  249. }
  250. if resLen > 0 {
  251. var n uint64
  252. n, e = mc.readUntilEOF()
  253. if e != nil {
  254. return
  255. }
  256. var row *[]*[]byte
  257. row, e = mc.readRow(int(n))
  258. if e != nil {
  259. return
  260. }
  261. _, e = mc.readUntilEOF()
  262. if e != nil {
  263. return
  264. }
  265. val = string(*(*row)[0])
  266. }
  267. return
  268. }
  269. // *** DEPRECATED ***
  270. // Executes a simple Ping-CMD to test or keepalive the connection
  271. func (mc *mysqlConn) Ping() (e error) {
  272. // Send command
  273. e = mc.writeCommandPacket(COM_PING)
  274. if e != nil {
  275. return
  276. }
  277. // Read Result
  278. e = mc.readResultOK()
  279. return
  280. }