connection.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. "crypto/tls"
  11. "database/sql/driver"
  12. "errors"
  13. "net"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. type mysqlConn struct {
  19. buf buffer
  20. netConn net.Conn
  21. affectedRows uint64
  22. insertId uint64
  23. cfg *config
  24. maxPacketAllowed int
  25. maxWriteSize int
  26. flags clientFlag
  27. status statusFlag
  28. sequence uint8
  29. parseTime bool
  30. strict bool
  31. }
  32. type config struct {
  33. user string
  34. passwd string
  35. net string
  36. addr string
  37. dbname string
  38. params map[string]string
  39. loc *time.Location
  40. tls *tls.Config
  41. timeout time.Duration
  42. collation uint8
  43. allowAllFiles bool
  44. allowOldPasswords bool
  45. clientFoundRows bool
  46. columnsWithAlias bool
  47. interpolateParams bool
  48. }
  49. // Handles parameters set in DSN after the connection is established
  50. func (mc *mysqlConn) handleParams() (err error) {
  51. for param, val := range mc.cfg.params {
  52. switch param {
  53. // Charset
  54. case "charset":
  55. charsets := strings.Split(val, ",")
  56. for i := range charsets {
  57. // ignore errors here - a charset may not exist
  58. err = mc.exec("SET NAMES " + charsets[i])
  59. if err == nil {
  60. break
  61. }
  62. }
  63. if err != nil {
  64. return
  65. }
  66. // time.Time parsing
  67. case "parseTime":
  68. var isBool bool
  69. mc.parseTime, isBool = readBool(val)
  70. if !isBool {
  71. return errors.New("Invalid Bool value: " + val)
  72. }
  73. // Strict mode
  74. case "strict":
  75. var isBool bool
  76. mc.strict, isBool = readBool(val)
  77. if !isBool {
  78. return errors.New("Invalid Bool value: " + val)
  79. }
  80. // Compression
  81. case "compress":
  82. err = errors.New("Compression not implemented yet")
  83. return
  84. // System Vars
  85. default:
  86. err = mc.exec("SET " + param + "=" + val + "")
  87. if err != nil {
  88. return
  89. }
  90. }
  91. }
  92. return
  93. }
  94. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  95. if mc.netConn == nil {
  96. errLog.Print(ErrInvalidConn)
  97. return nil, driver.ErrBadConn
  98. }
  99. err := mc.exec("START TRANSACTION")
  100. if err == nil {
  101. return &mysqlTx{mc}, err
  102. }
  103. return nil, err
  104. }
  105. func (mc *mysqlConn) Close() (err error) {
  106. // Makes Close idempotent
  107. if mc.netConn != nil {
  108. err = mc.writeCommandPacket(comQuit)
  109. if err == nil {
  110. err = mc.netConn.Close()
  111. } else {
  112. mc.netConn.Close()
  113. }
  114. mc.netConn = nil
  115. }
  116. mc.cfg = nil
  117. mc.buf.rd = nil
  118. return
  119. }
  120. func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
  121. if mc.netConn == nil {
  122. errLog.Print(ErrInvalidConn)
  123. return nil, driver.ErrBadConn
  124. }
  125. // Send command
  126. err := mc.writeCommandPacketStr(comStmtPrepare, query)
  127. if err != nil {
  128. return nil, err
  129. }
  130. stmt := &mysqlStmt{
  131. mc: mc,
  132. }
  133. // Read Result
  134. columnCount, err := stmt.readPrepareResultPacket()
  135. if err == nil {
  136. if stmt.paramCount > 0 {
  137. if err = mc.readUntilEOF(); err != nil {
  138. return nil, err
  139. }
  140. }
  141. if columnCount > 0 {
  142. err = mc.readUntilEOF()
  143. }
  144. }
  145. return stmt, err
  146. }
  147. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/libmysql/libmysql.c#L1150-L1156
  148. func (mc *mysqlConn) escapeBytes(v []byte) string {
  149. var escape func([]byte) []byte
  150. if mc.status&statusNoBackslashEscapes == 0 {
  151. escape = EscapeString
  152. } else {
  153. escape = EscapeQuotes
  154. }
  155. return "'" + string(escape(v)) + "'"
  156. }
  157. func (mc *mysqlConn) buildQuery(query string, args []driver.Value) (string, error) {
  158. chunks := strings.Split(query, "?")
  159. if len(chunks) != len(args)+1 {
  160. return "", driver.ErrSkip
  161. }
  162. parts := make([]string, len(chunks)+len(args))
  163. parts[0] = chunks[0]
  164. for i, arg := range args {
  165. pos := i*2 + 1
  166. parts[pos+1] = chunks[i+1]
  167. if arg == nil {
  168. parts[pos] = "NULL"
  169. continue
  170. }
  171. switch v := arg.(type) {
  172. case int64:
  173. parts[pos] = strconv.FormatInt(v, 10)
  174. case float64:
  175. parts[pos] = strconv.FormatFloat(v, 'f', -1, 64)
  176. case bool:
  177. if v {
  178. parts[pos] = "1"
  179. } else {
  180. parts[pos] = "0"
  181. }
  182. case time.Time:
  183. if v.IsZero() {
  184. parts[pos] = "'0000-00-00'"
  185. } else {
  186. fmt := "'2006-01-02 15:04:05.999999'"
  187. parts[pos] = v.In(mc.cfg.loc).Format(fmt)
  188. }
  189. case []byte:
  190. if v == nil {
  191. parts[pos] = "NULL"
  192. } else {
  193. parts[pos] = mc.escapeBytes(v)
  194. }
  195. case string:
  196. parts[pos] = mc.escapeBytes([]byte(v))
  197. default:
  198. return "", driver.ErrSkip
  199. }
  200. }
  201. pktSize := len(query) + 4 // 4 bytes for header.
  202. for _, p := range parts {
  203. pktSize += len(p)
  204. }
  205. if pktSize > mc.maxPacketAllowed {
  206. return "", driver.ErrSkip
  207. }
  208. return strings.Join(parts, ""), nil
  209. }
  210. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  211. if mc.netConn == nil {
  212. errLog.Print(ErrInvalidConn)
  213. return nil, driver.ErrBadConn
  214. }
  215. if len(args) != 0 {
  216. if !mc.cfg.interpolateParams {
  217. return nil, driver.ErrSkip
  218. }
  219. // try client-side prepare to reduce roundtrip
  220. prepared, err := mc.buildQuery(query, args)
  221. if err != nil {
  222. return nil, err
  223. }
  224. query = prepared
  225. args = nil
  226. }
  227. mc.affectedRows = 0
  228. mc.insertId = 0
  229. err := mc.exec(query)
  230. if err == nil {
  231. return &mysqlResult{
  232. affectedRows: int64(mc.affectedRows),
  233. insertId: int64(mc.insertId),
  234. }, err
  235. }
  236. return nil, err
  237. }
  238. // Internal function to execute commands
  239. func (mc *mysqlConn) exec(query string) error {
  240. // Send command
  241. err := mc.writeCommandPacketStr(comQuery, query)
  242. if err != nil {
  243. return err
  244. }
  245. // Read Result
  246. resLen, err := mc.readResultSetHeaderPacket()
  247. if err == nil && resLen > 0 {
  248. if err = mc.readUntilEOF(); err != nil {
  249. return err
  250. }
  251. err = mc.readUntilEOF()
  252. }
  253. return err
  254. }
  255. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  256. if mc.netConn == nil {
  257. errLog.Print(ErrInvalidConn)
  258. return nil, driver.ErrBadConn
  259. }
  260. if len(args) != 0 {
  261. if !mc.cfg.interpolateParams {
  262. return nil, driver.ErrSkip
  263. }
  264. // try client-side prepare to reduce roundtrip
  265. prepared, err := mc.buildQuery(query, args)
  266. if err != nil {
  267. return nil, err
  268. }
  269. query = prepared
  270. args = nil
  271. }
  272. // Send command
  273. err := mc.writeCommandPacketStr(comQuery, query)
  274. if err == nil {
  275. // Read Result
  276. var resLen int
  277. resLen, err = mc.readResultSetHeaderPacket()
  278. if err == nil {
  279. rows := new(textRows)
  280. rows.mc = mc
  281. if resLen == 0 {
  282. // no columns, no more data
  283. return emptyRows{}, nil
  284. }
  285. // Columns
  286. rows.columns, err = mc.readColumns(resLen)
  287. return rows, err
  288. }
  289. }
  290. return nil, err
  291. }
  292. // Gets the value of the given MySQL System Variable
  293. // The returned byte slice is only valid until the next read
  294. func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
  295. // Send command
  296. if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil {
  297. return nil, err
  298. }
  299. // Read Result
  300. resLen, err := mc.readResultSetHeaderPacket()
  301. if err == nil {
  302. rows := new(textRows)
  303. rows.mc = mc
  304. if resLen > 0 {
  305. // Columns
  306. if err := mc.readUntilEOF(); err != nil {
  307. return nil, err
  308. }
  309. }
  310. dest := make([]driver.Value, resLen)
  311. if err = rows.readRow(dest); err == nil {
  312. return dest[0].([]byte), mc.readUntilEOF()
  313. }
  314. }
  315. return nil, err
  316. }