connection.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. "github.com/go-sql-driver/mysql/internal/atomic"
  11. "database/sql/driver"
  12. "io"
  13. "net"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. // a copy of context.Context for Go 1.7 and earlier
  19. type mysqlContext interface {
  20. Done() <-chan struct{}
  21. Err() error
  22. // defined in context.Context, but not used in this driver:
  23. // Deadline() (deadline time.Time, ok bool)
  24. // Value(key interface{}) interface{}
  25. }
  26. type mysqlConn struct {
  27. buf buffer
  28. netConn net.Conn
  29. affectedRows uint64
  30. insertId uint64
  31. cfg *Config
  32. maxAllowedPacket int
  33. maxWriteSize int
  34. writeTimeout time.Duration
  35. flags clientFlag
  36. status statusFlag
  37. sequence uint8
  38. parseTime bool
  39. strict bool
  40. // for context support (Go 1.8+)
  41. watching bool
  42. watcher chan<- mysqlContext
  43. closech chan struct{}
  44. finished chan<- struct{}
  45. canceled atomic.Error // set non-nil if conn is canceled
  46. closed atomic.Bool // set when conn is closed, before closech is closed
  47. }
  48. // Handles parameters set in DSN after the connection is established
  49. func (mc *mysqlConn) handleParams() (err error) {
  50. for param, val := range mc.cfg.Params {
  51. switch param {
  52. // Charset
  53. case "charset":
  54. charsets := strings.Split(val, ",")
  55. for i := range charsets {
  56. // ignore errors here - a charset may not exist
  57. err = mc.exec("SET NAMES " + charsets[i])
  58. if err == nil {
  59. break
  60. }
  61. }
  62. if err != nil {
  63. return
  64. }
  65. // System Vars
  66. default:
  67. err = mc.exec("SET " + param + "=" + val + "")
  68. if err != nil {
  69. return
  70. }
  71. }
  72. }
  73. return
  74. }
  75. func (mc *mysqlConn) markBadConn(err error) error {
  76. if mc == nil {
  77. return err
  78. }
  79. if err != errBadConnNoWrite {
  80. return err
  81. }
  82. return driver.ErrBadConn
  83. }
  84. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  85. return mc.begin(false)
  86. }
  87. func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) {
  88. if mc.closed.IsSet() {
  89. errLog.Print(ErrInvalidConn)
  90. return nil, driver.ErrBadConn
  91. }
  92. var q string
  93. if readOnly {
  94. q = "START TRANSACTION READ ONLY"
  95. } else {
  96. q = "START TRANSACTION"
  97. }
  98. err := mc.exec(q)
  99. if err == nil {
  100. return &mysqlTx{mc}, err
  101. }
  102. return nil, mc.markBadConn(err)
  103. }
  104. func (mc *mysqlConn) Close() (err error) {
  105. // Makes Close idempotent
  106. if !mc.closed.IsSet() {
  107. err = mc.writeCommandPacket(comQuit)
  108. }
  109. mc.cleanup()
  110. return
  111. }
  112. // Closes the network connection and unsets internal variables. Do not call this
  113. // function after successfully authentication, call Close instead. This function
  114. // is called before auth or on auth failure because MySQL will have already
  115. // closed the network connection.
  116. func (mc *mysqlConn) cleanup() {
  117. if !mc.closed.TrySet(true) {
  118. return
  119. }
  120. // Makes cleanup idempotent
  121. close(mc.closech)
  122. if mc.netConn == nil {
  123. return
  124. }
  125. if err := mc.netConn.Close(); err != nil {
  126. errLog.Print(err)
  127. }
  128. }
  129. func (mc *mysqlConn) error() error {
  130. if mc.closed.IsSet() {
  131. if err := mc.canceled.Value(); err != nil {
  132. return err
  133. }
  134. return ErrInvalidConn
  135. }
  136. return nil
  137. }
  138. func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
  139. if mc.closed.IsSet() {
  140. errLog.Print(ErrInvalidConn)
  141. return nil, driver.ErrBadConn
  142. }
  143. // Send command
  144. err := mc.writeCommandPacketStr(comStmtPrepare, query)
  145. if err != nil {
  146. return nil, mc.markBadConn(err)
  147. }
  148. stmt := &mysqlStmt{
  149. mc: mc,
  150. }
  151. // Read Result
  152. columnCount, err := stmt.readPrepareResultPacket()
  153. if err == nil {
  154. if stmt.paramCount > 0 {
  155. if err = mc.readUntilEOF(); err != nil {
  156. return nil, err
  157. }
  158. }
  159. if columnCount > 0 {
  160. err = mc.readUntilEOF()
  161. }
  162. }
  163. return stmt, err
  164. }
  165. func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) {
  166. // Number of ? should be same to len(args)
  167. if strings.Count(query, "?") != len(args) {
  168. return "", driver.ErrSkip
  169. }
  170. buf := mc.buf.takeCompleteBuffer()
  171. if buf == nil {
  172. // can not take the buffer. Something must be wrong with the connection
  173. errLog.Print(ErrBusyBuffer)
  174. return "", ErrInvalidConn
  175. }
  176. buf = buf[:0]
  177. argPos := 0
  178. for i := 0; i < len(query); i++ {
  179. q := strings.IndexByte(query[i:], '?')
  180. if q == -1 {
  181. buf = append(buf, query[i:]...)
  182. break
  183. }
  184. buf = append(buf, query[i:i+q]...)
  185. i += q
  186. arg := args[argPos]
  187. argPos++
  188. if arg == nil {
  189. buf = append(buf, "NULL"...)
  190. continue
  191. }
  192. switch v := arg.(type) {
  193. case int64:
  194. buf = strconv.AppendInt(buf, v, 10)
  195. case float64:
  196. buf = strconv.AppendFloat(buf, v, 'g', -1, 64)
  197. case bool:
  198. if v {
  199. buf = append(buf, '1')
  200. } else {
  201. buf = append(buf, '0')
  202. }
  203. case time.Time:
  204. if v.IsZero() {
  205. buf = append(buf, "'0000-00-00'"...)
  206. } else {
  207. v := v.In(mc.cfg.Loc)
  208. v = v.Add(time.Nanosecond * 500) // To round under microsecond
  209. year := v.Year()
  210. year100 := year / 100
  211. year1 := year % 100
  212. month := v.Month()
  213. day := v.Day()
  214. hour := v.Hour()
  215. minute := v.Minute()
  216. second := v.Second()
  217. micro := v.Nanosecond() / 1000
  218. buf = append(buf, []byte{
  219. '\'',
  220. digits10[year100], digits01[year100],
  221. digits10[year1], digits01[year1],
  222. '-',
  223. digits10[month], digits01[month],
  224. '-',
  225. digits10[day], digits01[day],
  226. ' ',
  227. digits10[hour], digits01[hour],
  228. ':',
  229. digits10[minute], digits01[minute],
  230. ':',
  231. digits10[second], digits01[second],
  232. }...)
  233. if micro != 0 {
  234. micro10000 := micro / 10000
  235. micro100 := micro / 100 % 100
  236. micro1 := micro % 100
  237. buf = append(buf, []byte{
  238. '.',
  239. digits10[micro10000], digits01[micro10000],
  240. digits10[micro100], digits01[micro100],
  241. digits10[micro1], digits01[micro1],
  242. }...)
  243. }
  244. buf = append(buf, '\'')
  245. }
  246. case []byte:
  247. if v == nil {
  248. buf = append(buf, "NULL"...)
  249. } else {
  250. buf = append(buf, "_binary'"...)
  251. if mc.status&statusNoBackslashEscapes == 0 {
  252. buf = escapeBytesBackslash(buf, v)
  253. } else {
  254. buf = escapeBytesQuotes(buf, v)
  255. }
  256. buf = append(buf, '\'')
  257. }
  258. case string:
  259. buf = append(buf, '\'')
  260. if mc.status&statusNoBackslashEscapes == 0 {
  261. buf = escapeStringBackslash(buf, v)
  262. } else {
  263. buf = escapeStringQuotes(buf, v)
  264. }
  265. buf = append(buf, '\'')
  266. default:
  267. return "", driver.ErrSkip
  268. }
  269. if len(buf)+4 > mc.maxAllowedPacket {
  270. return "", driver.ErrSkip
  271. }
  272. }
  273. if argPos != len(args) {
  274. return "", driver.ErrSkip
  275. }
  276. return string(buf), nil
  277. }
  278. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  279. if mc.closed.IsSet() {
  280. errLog.Print(ErrInvalidConn)
  281. return nil, driver.ErrBadConn
  282. }
  283. if len(args) != 0 {
  284. if !mc.cfg.InterpolateParams {
  285. return nil, driver.ErrSkip
  286. }
  287. // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement
  288. prepared, err := mc.interpolateParams(query, args)
  289. if err != nil {
  290. return nil, err
  291. }
  292. query = prepared
  293. }
  294. mc.affectedRows = 0
  295. mc.insertId = 0
  296. err := mc.exec(query)
  297. if err == nil {
  298. return &mysqlResult{
  299. affectedRows: int64(mc.affectedRows),
  300. insertId: int64(mc.insertId),
  301. }, err
  302. }
  303. return nil, mc.markBadConn(err)
  304. }
  305. // Internal function to execute commands
  306. func (mc *mysqlConn) exec(query string) error {
  307. // Send command
  308. if err := mc.writeCommandPacketStr(comQuery, query); err != nil {
  309. return mc.markBadConn(err)
  310. }
  311. // Read Result
  312. resLen, err := mc.readResultSetHeaderPacket()
  313. if err != nil {
  314. return err
  315. }
  316. if resLen > 0 {
  317. // columns
  318. if err := mc.readUntilEOF(); err != nil {
  319. return err
  320. }
  321. // rows
  322. if err := mc.readUntilEOF(); err != nil {
  323. return err
  324. }
  325. }
  326. return mc.discardResults()
  327. }
  328. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  329. return mc.query(query, args)
  330. }
  331. func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) {
  332. if mc.closed.IsSet() {
  333. errLog.Print(ErrInvalidConn)
  334. return nil, driver.ErrBadConn
  335. }
  336. if len(args) != 0 {
  337. if !mc.cfg.InterpolateParams {
  338. return nil, driver.ErrSkip
  339. }
  340. // try client-side prepare to reduce roundtrip
  341. prepared, err := mc.interpolateParams(query, args)
  342. if err != nil {
  343. return nil, err
  344. }
  345. query = prepared
  346. }
  347. // Send command
  348. err := mc.writeCommandPacketStr(comQuery, query)
  349. if err == nil {
  350. // Read Result
  351. var resLen int
  352. resLen, err = mc.readResultSetHeaderPacket()
  353. if err == nil {
  354. rows := new(textRows)
  355. rows.mc = mc
  356. if resLen == 0 {
  357. rows.rs.done = true
  358. switch err := rows.NextResultSet(); err {
  359. case nil, io.EOF:
  360. return rows, nil
  361. default:
  362. return nil, err
  363. }
  364. }
  365. // Columns
  366. rows.rs.columns, err = mc.readColumns(resLen)
  367. return rows, err
  368. }
  369. }
  370. return nil, mc.markBadConn(err)
  371. }
  372. // Gets the value of the given MySQL System Variable
  373. // The returned byte slice is only valid until the next read
  374. func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
  375. // Send command
  376. if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil {
  377. return nil, err
  378. }
  379. // Read Result
  380. resLen, err := mc.readResultSetHeaderPacket()
  381. if err == nil {
  382. rows := new(textRows)
  383. rows.mc = mc
  384. rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}}
  385. if resLen > 0 {
  386. // Columns
  387. if err := mc.readUntilEOF(); err != nil {
  388. return nil, err
  389. }
  390. }
  391. dest := make([]driver.Value, resLen)
  392. if err = rows.readRow(dest); err == nil {
  393. return dest[0].([]byte), mc.readUntilEOF()
  394. }
  395. }
  396. return nil, err
  397. }
  398. // finish is called when the query has canceled.
  399. func (mc *mysqlConn) cancel(err error) {
  400. mc.canceled.Set(err)
  401. mc.cleanup()
  402. }
  403. // finish is called when the query has succeeded.
  404. func (mc *mysqlConn) finish() {
  405. if !mc.watching || mc.finished == nil {
  406. return
  407. }
  408. select {
  409. case mc.finished <- struct{}{}:
  410. mc.watching = false
  411. case <-mc.closech:
  412. }
  413. }