connection.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. return &mysqlResult{
  181. affectedRows: int64(mc.affectedRows),
  182. insertId: int64(mc.insertId)},
  183. e
  184. }
  185. // Internal function to execute commands
  186. func (mc *mysqlConn) exec(query string) (e error) {
  187. // Send command
  188. e = mc.writeCommandPacket(COM_QUERY, query)
  189. if e != nil {
  190. return
  191. }
  192. // Read Result
  193. var resLen int
  194. resLen, e = mc.readResultSetHeaderPacket()
  195. if e != nil {
  196. return
  197. }
  198. if resLen > 0 {
  199. _, e = mc.readUntilEOF()
  200. if e != nil {
  201. return
  202. }
  203. mc.affectedRows, e = mc.readUntilEOF()
  204. if e != nil {
  205. return
  206. }
  207. }
  208. return
  209. }
  210. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  211. if len(args) > 0 {
  212. return nil, driver.ErrSkip
  213. }
  214. // Send command
  215. e := mc.writeCommandPacket(COM_QUERY, query)
  216. if e != nil {
  217. return nil, e
  218. }
  219. // Read Result
  220. var resLen int
  221. resLen, e = mc.readResultSetHeaderPacket()
  222. if e != nil {
  223. return nil, e
  224. }
  225. rows := mysqlRows{&rowsContent{mc, false, nil, false}}
  226. if resLen > 0 {
  227. // Columns
  228. rows.content.columns, e = mc.readColumns(resLen)
  229. if e != nil {
  230. return nil, e
  231. }
  232. }
  233. return rows, e
  234. }
  235. // Gets the value of the given MySQL System Variable
  236. func (mc *mysqlConn) getSystemVar(name string) (val string, e error) {
  237. // Send command
  238. e = mc.writeCommandPacket(COM_QUERY, "SELECT @@"+name)
  239. if e != nil {
  240. return
  241. }
  242. // Read Result
  243. resLen, e := mc.readResultSetHeaderPacket()
  244. if e != nil {
  245. return
  246. }
  247. if resLen > 0 {
  248. var n uint64
  249. n, e = mc.readUntilEOF()
  250. if e != nil {
  251. return
  252. }
  253. var row *[]*[]byte
  254. row, e = mc.readRow(int(n))
  255. if e != nil {
  256. return
  257. }
  258. _, e = mc.readUntilEOF()
  259. if e != nil {
  260. return
  261. }
  262. val = string(*(*row)[0])
  263. }
  264. return
  265. }
  266. // *** DEPRECATED ***
  267. // Executes a simple Ping-CMD to test or keepalive the connection
  268. func (mc *mysqlConn) Ping() (e error) {
  269. // Send command
  270. e = mc.writeCommandPacket(COM_PING)
  271. if e != nil {
  272. return
  273. }
  274. // Read Result
  275. e = mc.readResultOK()
  276. return
  277. }