connection.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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) interpolateParams(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, 'g', -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. if v.Nanosecond() == 0 {
  188. fmt = "'2006-01-02 15:04:05'"
  189. }
  190. parts[pos] = v.In(mc.cfg.loc).Format(fmt)
  191. }
  192. case []byte:
  193. if v == nil {
  194. parts[pos] = "NULL"
  195. } else {
  196. parts[pos] = mc.escapeBytes(v)
  197. }
  198. case string:
  199. parts[pos] = mc.escapeBytes([]byte(v))
  200. default:
  201. return "", driver.ErrSkip
  202. }
  203. }
  204. pktSize := len(query) + 4 // 4 bytes for header.
  205. for _, p := range parts {
  206. pktSize += len(p)
  207. }
  208. if pktSize > mc.maxPacketAllowed {
  209. return "", driver.ErrSkip
  210. }
  211. return strings.Join(parts, ""), nil
  212. }
  213. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  214. if mc.netConn == nil {
  215. errLog.Print(ErrInvalidConn)
  216. return nil, driver.ErrBadConn
  217. }
  218. if len(args) != 0 {
  219. if !mc.cfg.interpolateParams {
  220. return nil, driver.ErrSkip
  221. }
  222. // try client-side prepare to reduce roundtrip
  223. prepared, err := mc.interpolateParams(query, args)
  224. if err != nil {
  225. return nil, err
  226. }
  227. query = prepared
  228. args = nil
  229. }
  230. mc.affectedRows = 0
  231. mc.insertId = 0
  232. err := mc.exec(query)
  233. if err == nil {
  234. return &mysqlResult{
  235. affectedRows: int64(mc.affectedRows),
  236. insertId: int64(mc.insertId),
  237. }, err
  238. }
  239. return nil, err
  240. }
  241. // Internal function to execute commands
  242. func (mc *mysqlConn) exec(query string) error {
  243. // Send command
  244. err := mc.writeCommandPacketStr(comQuery, query)
  245. if err != nil {
  246. return err
  247. }
  248. // Read Result
  249. resLen, err := mc.readResultSetHeaderPacket()
  250. if err == nil && resLen > 0 {
  251. if err = mc.readUntilEOF(); err != nil {
  252. return err
  253. }
  254. err = mc.readUntilEOF()
  255. }
  256. return err
  257. }
  258. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  259. if mc.netConn == nil {
  260. errLog.Print(ErrInvalidConn)
  261. return nil, driver.ErrBadConn
  262. }
  263. if len(args) != 0 {
  264. if !mc.cfg.interpolateParams {
  265. return nil, driver.ErrSkip
  266. }
  267. // try client-side prepare to reduce roundtrip
  268. prepared, err := mc.interpolateParams(query, args)
  269. if err != nil {
  270. return nil, err
  271. }
  272. query = prepared
  273. args = nil
  274. }
  275. // Send command
  276. err := mc.writeCommandPacketStr(comQuery, query)
  277. if err == nil {
  278. // Read Result
  279. var resLen int
  280. resLen, err = mc.readResultSetHeaderPacket()
  281. if err == nil {
  282. rows := new(textRows)
  283. rows.mc = mc
  284. if resLen == 0 {
  285. // no columns, no more data
  286. return emptyRows{}, nil
  287. }
  288. // Columns
  289. rows.columns, err = mc.readColumns(resLen)
  290. return rows, err
  291. }
  292. }
  293. return nil, err
  294. }
  295. // Gets the value of the given MySQL System Variable
  296. // The returned byte slice is only valid until the next read
  297. func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
  298. // Send command
  299. if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil {
  300. return nil, err
  301. }
  302. // Read Result
  303. resLen, err := mc.readResultSetHeaderPacket()
  304. if err == nil {
  305. rows := new(textRows)
  306. rows.mc = mc
  307. if resLen > 0 {
  308. // Columns
  309. if err := mc.readUntilEOF(); err != nil {
  310. return nil, err
  311. }
  312. }
  313. dest := make([]driver.Value, resLen)
  314. if err = rows.readRow(dest); err == nil {
  315. return dest[0].([]byte), mc.readUntilEOF()
  316. }
  317. }
  318. return nil, err
  319. }