connection.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "database/sql/driver"
  11. "net"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. type mysqlConn struct {
  17. buf buffer
  18. netConn net.Conn
  19. affectedRows uint64
  20. insertId uint64
  21. cfg *Config
  22. maxPacketAllowed int
  23. maxWriteSize int
  24. writeTimeout time.Duration
  25. flags clientFlag
  26. status statusFlag
  27. sequence uint8
  28. parseTime bool
  29. strict bool
  30. }
  31. // Handles parameters set in DSN after the connection is established
  32. func (mc *mysqlConn) handleParams() (err error) {
  33. for param, val := range mc.cfg.Params {
  34. switch param {
  35. // Charset
  36. case "charset":
  37. charsets := strings.Split(val, ",")
  38. for i := range charsets {
  39. // ignore errors here - a charset may not exist
  40. err = mc.exec("SET NAMES " + charsets[i])
  41. if err == nil {
  42. break
  43. }
  44. }
  45. if err != nil {
  46. return
  47. }
  48. // System Vars
  49. default:
  50. err = mc.exec("SET " + param + "=" + val + "")
  51. if err != nil {
  52. return
  53. }
  54. }
  55. }
  56. return
  57. }
  58. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  59. if mc.netConn == nil {
  60. errLog.Print(ErrInvalidConn)
  61. return nil, driver.ErrBadConn
  62. }
  63. err := mc.exec("START TRANSACTION")
  64. if err == nil {
  65. return &mysqlTx{mc}, err
  66. }
  67. return nil, err
  68. }
  69. func (mc *mysqlConn) Close() (err error) {
  70. // Makes Close idempotent
  71. if mc.netConn != nil {
  72. err = mc.writeCommandPacket(comQuit)
  73. }
  74. mc.cleanup()
  75. return
  76. }
  77. // Closes the network connection and unsets internal variables. Do not call this
  78. // function after successfully authentication, call Close instead. This function
  79. // is called before auth or on auth failure because MySQL will have already
  80. // closed the network connection.
  81. func (mc *mysqlConn) cleanup() {
  82. // Makes cleanup idempotent
  83. if mc.netConn != nil {
  84. if err := mc.netConn.Close(); err != nil {
  85. errLog.Print(err)
  86. }
  87. mc.netConn = nil
  88. }
  89. mc.cfg = nil
  90. mc.buf.nc = nil
  91. }
  92. func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
  93. if mc.netConn == nil {
  94. errLog.Print(ErrInvalidConn)
  95. return nil, driver.ErrBadConn
  96. }
  97. // Send command
  98. err := mc.writeCommandPacketStr(comStmtPrepare, query)
  99. if err != nil {
  100. return nil, err
  101. }
  102. stmt := &mysqlStmt{
  103. mc: mc,
  104. }
  105. // Read Result
  106. columnCount, err := stmt.readPrepareResultPacket()
  107. if err == nil {
  108. if stmt.paramCount > 0 {
  109. if err = mc.readUntilEOF(); err != nil {
  110. return nil, err
  111. }
  112. }
  113. if columnCount > 0 {
  114. err = mc.readUntilEOF()
  115. }
  116. }
  117. return stmt, err
  118. }
  119. func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) {
  120. buf := mc.buf.takeCompleteBuffer()
  121. if buf == nil {
  122. // can not take the buffer. Something must be wrong with the connection
  123. errLog.Print(ErrBusyBuffer)
  124. return "", driver.ErrBadConn
  125. }
  126. buf = buf[:0]
  127. argPos := 0
  128. for i := 0; i < len(query); i++ {
  129. q := strings.IndexByte(query[i:], '?')
  130. if q == -1 {
  131. buf = append(buf, query[i:]...)
  132. break
  133. }
  134. buf = append(buf, query[i:i+q]...)
  135. i += q
  136. arg := args[argPos]
  137. argPos++
  138. if arg == nil {
  139. buf = append(buf, "NULL"...)
  140. continue
  141. }
  142. switch v := arg.(type) {
  143. case int64:
  144. buf = strconv.AppendInt(buf, v, 10)
  145. case float64:
  146. buf = strconv.AppendFloat(buf, v, 'g', -1, 64)
  147. case bool:
  148. if v {
  149. buf = append(buf, '1')
  150. } else {
  151. buf = append(buf, '0')
  152. }
  153. case time.Time:
  154. if v.IsZero() {
  155. buf = append(buf, "'0000-00-00'"...)
  156. } else {
  157. v := v.In(mc.cfg.Loc)
  158. v = v.Add(time.Nanosecond * 500) // To round under microsecond
  159. year := v.Year()
  160. year100 := year / 100
  161. year1 := year % 100
  162. month := v.Month()
  163. day := v.Day()
  164. hour := v.Hour()
  165. minute := v.Minute()
  166. second := v.Second()
  167. micro := v.Nanosecond() / 1000
  168. buf = append(buf, []byte{
  169. '\'',
  170. digits10[year100], digits01[year100],
  171. digits10[year1], digits01[year1],
  172. '-',
  173. digits10[month], digits01[month],
  174. '-',
  175. digits10[day], digits01[day],
  176. ' ',
  177. digits10[hour], digits01[hour],
  178. ':',
  179. digits10[minute], digits01[minute],
  180. ':',
  181. digits10[second], digits01[second],
  182. }...)
  183. if micro != 0 {
  184. micro10000 := micro / 10000
  185. micro100 := micro / 100 % 100
  186. micro1 := micro % 100
  187. buf = append(buf, []byte{
  188. '.',
  189. digits10[micro10000], digits01[micro10000],
  190. digits10[micro100], digits01[micro100],
  191. digits10[micro1], digits01[micro1],
  192. }...)
  193. }
  194. buf = append(buf, '\'')
  195. }
  196. case []byte:
  197. if v == nil {
  198. buf = append(buf, "NULL"...)
  199. } else {
  200. buf = append(buf, "_binary'"...)
  201. if mc.status&statusNoBackslashEscapes == 0 {
  202. buf = escapeBytesBackslash(buf, v)
  203. } else {
  204. buf = escapeBytesQuotes(buf, v)
  205. }
  206. buf = append(buf, '\'')
  207. }
  208. case string:
  209. buf = append(buf, '\'')
  210. if mc.status&statusNoBackslashEscapes == 0 {
  211. buf = escapeStringBackslash(buf, v)
  212. } else {
  213. buf = escapeStringQuotes(buf, v)
  214. }
  215. buf = append(buf, '\'')
  216. default:
  217. return "", driver.ErrSkip
  218. }
  219. if len(buf)+4 > mc.maxPacketAllowed {
  220. return "", driver.ErrSkip
  221. }
  222. }
  223. if argPos != len(args) {
  224. return "", driver.ErrSkip
  225. }
  226. return string(buf), nil
  227. }
  228. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  229. if mc.netConn == nil {
  230. errLog.Print(ErrInvalidConn)
  231. return nil, driver.ErrBadConn
  232. }
  233. if len(args) != 0 {
  234. if !mc.cfg.InterpolateParams {
  235. return nil, driver.ErrSkip
  236. }
  237. // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement
  238. prepared, err := mc.interpolateParams(query, args)
  239. if err != nil {
  240. return nil, err
  241. }
  242. query = prepared
  243. args = nil
  244. }
  245. mc.affectedRows = 0
  246. mc.insertId = 0
  247. err := mc.exec(query)
  248. if err == nil {
  249. return &mysqlResult{
  250. affectedRows: int64(mc.affectedRows),
  251. insertId: int64(mc.insertId),
  252. }, err
  253. }
  254. return nil, err
  255. }
  256. // Internal function to execute commands
  257. func (mc *mysqlConn) exec(query string) error {
  258. // Send command
  259. err := mc.writeCommandPacketStr(comQuery, query)
  260. if err != nil {
  261. return err
  262. }
  263. // Read Result
  264. resLen, err := mc.readResultSetHeaderPacket()
  265. if err == nil && resLen > 0 {
  266. if err = mc.readUntilEOF(); err != nil {
  267. return err
  268. }
  269. err = mc.readUntilEOF()
  270. }
  271. return err
  272. }
  273. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  274. if mc.netConn == nil {
  275. errLog.Print(ErrInvalidConn)
  276. return nil, driver.ErrBadConn
  277. }
  278. if len(args) != 0 {
  279. if !mc.cfg.InterpolateParams {
  280. return nil, driver.ErrSkip
  281. }
  282. // try client-side prepare to reduce roundtrip
  283. prepared, err := mc.interpolateParams(query, args)
  284. if err != nil {
  285. return nil, err
  286. }
  287. query = prepared
  288. args = nil
  289. }
  290. // Send command
  291. err := mc.writeCommandPacketStr(comQuery, query)
  292. if err == nil {
  293. // Read Result
  294. var resLen int
  295. resLen, err = mc.readResultSetHeaderPacket()
  296. if err == nil {
  297. rows := new(textRows)
  298. rows.mc = mc
  299. if resLen == 0 {
  300. // no columns, no more data
  301. return emptyRows{}, nil
  302. }
  303. // Columns
  304. rows.columns, err = mc.readColumns(resLen)
  305. return rows, err
  306. }
  307. }
  308. return nil, err
  309. }
  310. // Gets the value of the given MySQL System Variable
  311. // The returned byte slice is only valid until the next read
  312. func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
  313. // Send command
  314. if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil {
  315. return nil, err
  316. }
  317. // Read Result
  318. resLen, err := mc.readResultSetHeaderPacket()
  319. if err == nil {
  320. rows := new(textRows)
  321. rows.mc = mc
  322. rows.columns = []mysqlField{{fieldType: fieldTypeVarChar}}
  323. if resLen > 0 {
  324. // Columns
  325. if err := mc.readUntilEOF(); err != nil {
  326. return nil, err
  327. }
  328. }
  329. dest := make([]driver.Value, resLen)
  330. if err = rows.readRow(dest); err == nil {
  331. return dest[0].([]byte), mc.readUntilEOF()
  332. }
  333. }
  334. return nil, err
  335. }