connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. "context"
  11. "database/sql"
  12. "database/sql/driver"
  13. "io"
  14. "net"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. type mysqlConn struct {
  20. buf buffer
  21. netConn net.Conn
  22. rawConn net.Conn // underlying connection when netConn is TLS connection.
  23. affectedRows uint64
  24. insertId uint64
  25. cfg *Config
  26. maxAllowedPacket int
  27. maxWriteSize int
  28. writeTimeout time.Duration
  29. flags clientFlag
  30. status statusFlag
  31. sequence uint8
  32. parseTime bool
  33. reset bool // set when the Go SQL package calls ResetSession
  34. // for context support (Go 1.8+)
  35. watching bool
  36. watcher chan<- context.Context
  37. closech chan struct{}
  38. finished chan<- struct{}
  39. canceled atomicError // set non-nil if conn is canceled
  40. closed atomicBool // set when conn is closed, before closech is closed
  41. }
  42. // Handles parameters set in DSN after the connection is established
  43. func (mc *mysqlConn) handleParams() (err error) {
  44. for param, val := range mc.cfg.Params {
  45. switch param {
  46. // Charset
  47. case "charset":
  48. charsets := strings.Split(val, ",")
  49. for i := range charsets {
  50. // ignore errors here - a charset may not exist
  51. err = mc.exec("SET NAMES " + charsets[i])
  52. if err == nil {
  53. break
  54. }
  55. }
  56. if err != nil {
  57. return
  58. }
  59. // System Vars
  60. default:
  61. err = mc.exec("SET " + param + "=" + val + "")
  62. if err != nil {
  63. return
  64. }
  65. }
  66. }
  67. return
  68. }
  69. func (mc *mysqlConn) markBadConn(err error) error {
  70. if mc == nil {
  71. return err
  72. }
  73. if err != errBadConnNoWrite {
  74. return err
  75. }
  76. return driver.ErrBadConn
  77. }
  78. func (mc *mysqlConn) Begin() (driver.Tx, error) {
  79. return mc.begin(false)
  80. }
  81. func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) {
  82. if mc.closed.IsSet() {
  83. errLog.Print(ErrInvalidConn)
  84. return nil, driver.ErrBadConn
  85. }
  86. var q string
  87. if readOnly {
  88. q = "START TRANSACTION READ ONLY"
  89. } else {
  90. q = "START TRANSACTION"
  91. }
  92. err := mc.exec(q)
  93. if err == nil {
  94. return &mysqlTx{mc}, err
  95. }
  96. return nil, mc.markBadConn(err)
  97. }
  98. func (mc *mysqlConn) Close() (err error) {
  99. // Makes Close idempotent
  100. if !mc.closed.IsSet() {
  101. err = mc.writeCommandPacket(comQuit)
  102. }
  103. mc.cleanup()
  104. return
  105. }
  106. // Closes the network connection and unsets internal variables. Do not call this
  107. // function after successfully authentication, call Close instead. This function
  108. // is called before auth or on auth failure because MySQL will have already
  109. // closed the network connection.
  110. func (mc *mysqlConn) cleanup() {
  111. if !mc.closed.TrySet(true) {
  112. return
  113. }
  114. // Makes cleanup idempotent
  115. close(mc.closech)
  116. if mc.netConn == nil {
  117. return
  118. }
  119. if err := mc.netConn.Close(); err != nil {
  120. errLog.Print(err)
  121. }
  122. }
  123. func (mc *mysqlConn) error() error {
  124. if mc.closed.IsSet() {
  125. if err := mc.canceled.Value(); err != nil {
  126. return err
  127. }
  128. return ErrInvalidConn
  129. }
  130. return nil
  131. }
  132. func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
  133. if mc.closed.IsSet() {
  134. errLog.Print(ErrInvalidConn)
  135. return nil, driver.ErrBadConn
  136. }
  137. // Send command
  138. err := mc.writeCommandPacketStr(comStmtPrepare, query)
  139. if err != nil {
  140. return nil, mc.markBadConn(err)
  141. }
  142. stmt := &mysqlStmt{
  143. mc: mc,
  144. }
  145. // Read Result
  146. columnCount, err := stmt.readPrepareResultPacket()
  147. if err == nil {
  148. if stmt.paramCount > 0 {
  149. if err = mc.readUntilEOF(); err != nil {
  150. return nil, err
  151. }
  152. }
  153. if columnCount > 0 {
  154. err = mc.readUntilEOF()
  155. }
  156. }
  157. return stmt, err
  158. }
  159. func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) {
  160. // Number of ? should be same to len(args)
  161. if strings.Count(query, "?") != len(args) {
  162. return "", driver.ErrSkip
  163. }
  164. buf, err := mc.buf.takeCompleteBuffer()
  165. if err != nil {
  166. // can not take the buffer. Something must be wrong with the connection
  167. errLog.Print(err)
  168. return "", ErrInvalidConn
  169. }
  170. buf = buf[:0]
  171. argPos := 0
  172. for i := 0; i < len(query); i++ {
  173. q := strings.IndexByte(query[i:], '?')
  174. if q == -1 {
  175. buf = append(buf, query[i:]...)
  176. break
  177. }
  178. buf = append(buf, query[i:i+q]...)
  179. i += q
  180. arg := args[argPos]
  181. argPos++
  182. if arg == nil {
  183. buf = append(buf, "NULL"...)
  184. continue
  185. }
  186. switch v := arg.(type) {
  187. case int64:
  188. buf = strconv.AppendInt(buf, v, 10)
  189. case uint64:
  190. // Handle uint64 explicitly because our custom ConvertValue emits unsigned values
  191. buf = strconv.AppendUint(buf, v, 10)
  192. case float64:
  193. buf = strconv.AppendFloat(buf, v, 'g', -1, 64)
  194. case bool:
  195. if v {
  196. buf = append(buf, '1')
  197. } else {
  198. buf = append(buf, '0')
  199. }
  200. case time.Time:
  201. if v.IsZero() {
  202. buf = append(buf, "'0000-00-00'"...)
  203. } else {
  204. v := v.In(mc.cfg.Loc)
  205. v = v.Add(time.Nanosecond * 500) // To round under microsecond
  206. year := v.Year()
  207. year100 := year / 100
  208. year1 := year % 100
  209. month := v.Month()
  210. day := v.Day()
  211. hour := v.Hour()
  212. minute := v.Minute()
  213. second := v.Second()
  214. micro := v.Nanosecond() / 1000
  215. buf = append(buf, []byte{
  216. '\'',
  217. digits10[year100], digits01[year100],
  218. digits10[year1], digits01[year1],
  219. '-',
  220. digits10[month], digits01[month],
  221. '-',
  222. digits10[day], digits01[day],
  223. ' ',
  224. digits10[hour], digits01[hour],
  225. ':',
  226. digits10[minute], digits01[minute],
  227. ':',
  228. digits10[second], digits01[second],
  229. }...)
  230. if micro != 0 {
  231. micro10000 := micro / 10000
  232. micro100 := micro / 100 % 100
  233. micro1 := micro % 100
  234. buf = append(buf, []byte{
  235. '.',
  236. digits10[micro10000], digits01[micro10000],
  237. digits10[micro100], digits01[micro100],
  238. digits10[micro1], digits01[micro1],
  239. }...)
  240. }
  241. buf = append(buf, '\'')
  242. }
  243. case []byte:
  244. if v == nil {
  245. buf = append(buf, "NULL"...)
  246. } else {
  247. buf = append(buf, "_binary'"...)
  248. if mc.status&statusNoBackslashEscapes == 0 {
  249. buf = escapeBytesBackslash(buf, v)
  250. } else {
  251. buf = escapeBytesQuotes(buf, v)
  252. }
  253. buf = append(buf, '\'')
  254. }
  255. case string:
  256. buf = append(buf, '\'')
  257. if mc.status&statusNoBackslashEscapes == 0 {
  258. buf = escapeStringBackslash(buf, v)
  259. } else {
  260. buf = escapeStringQuotes(buf, v)
  261. }
  262. buf = append(buf, '\'')
  263. default:
  264. return "", driver.ErrSkip
  265. }
  266. if len(buf)+4 > mc.maxAllowedPacket {
  267. return "", driver.ErrSkip
  268. }
  269. }
  270. if argPos != len(args) {
  271. return "", driver.ErrSkip
  272. }
  273. return string(buf), nil
  274. }
  275. func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  276. if mc.closed.IsSet() {
  277. errLog.Print(ErrInvalidConn)
  278. return nil, driver.ErrBadConn
  279. }
  280. if len(args) != 0 {
  281. if !mc.cfg.InterpolateParams {
  282. return nil, driver.ErrSkip
  283. }
  284. // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement
  285. prepared, err := mc.interpolateParams(query, args)
  286. if err != nil {
  287. return nil, err
  288. }
  289. query = prepared
  290. }
  291. mc.affectedRows = 0
  292. mc.insertId = 0
  293. err := mc.exec(query)
  294. if err == nil {
  295. return &mysqlResult{
  296. affectedRows: int64(mc.affectedRows),
  297. insertId: int64(mc.insertId),
  298. }, err
  299. }
  300. return nil, mc.markBadConn(err)
  301. }
  302. // Internal function to execute commands
  303. func (mc *mysqlConn) exec(query string) error {
  304. // Send command
  305. if err := mc.writeCommandPacketStr(comQuery, query); err != nil {
  306. return mc.markBadConn(err)
  307. }
  308. // Read Result
  309. resLen, err := mc.readResultSetHeaderPacket()
  310. if err != nil {
  311. return err
  312. }
  313. if resLen > 0 {
  314. // columns
  315. if err := mc.readUntilEOF(); err != nil {
  316. return err
  317. }
  318. // rows
  319. if err := mc.readUntilEOF(); err != nil {
  320. return err
  321. }
  322. }
  323. return mc.discardResults()
  324. }
  325. func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  326. return mc.query(query, args)
  327. }
  328. func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) {
  329. if mc.closed.IsSet() {
  330. errLog.Print(ErrInvalidConn)
  331. return nil, driver.ErrBadConn
  332. }
  333. if len(args) != 0 {
  334. if !mc.cfg.InterpolateParams {
  335. return nil, driver.ErrSkip
  336. }
  337. // try client-side prepare to reduce roundtrip
  338. prepared, err := mc.interpolateParams(query, args)
  339. if err != nil {
  340. return nil, err
  341. }
  342. query = prepared
  343. }
  344. // Send command
  345. err := mc.writeCommandPacketStr(comQuery, query)
  346. if err == nil {
  347. // Read Result
  348. var resLen int
  349. resLen, err = mc.readResultSetHeaderPacket()
  350. if err == nil {
  351. rows := new(textRows)
  352. rows.mc = mc
  353. if resLen == 0 {
  354. rows.rs.done = true
  355. switch err := rows.NextResultSet(); err {
  356. case nil, io.EOF:
  357. return rows, nil
  358. default:
  359. return nil, err
  360. }
  361. }
  362. // Columns
  363. rows.rs.columns, err = mc.readColumns(resLen)
  364. return rows, err
  365. }
  366. }
  367. return nil, mc.markBadConn(err)
  368. }
  369. // Gets the value of the given MySQL System Variable
  370. // The returned byte slice is only valid until the next read
  371. func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
  372. // Send command
  373. if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil {
  374. return nil, err
  375. }
  376. // Read Result
  377. resLen, err := mc.readResultSetHeaderPacket()
  378. if err == nil {
  379. rows := new(textRows)
  380. rows.mc = mc
  381. rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}}
  382. if resLen > 0 {
  383. // Columns
  384. if err := mc.readUntilEOF(); err != nil {
  385. return nil, err
  386. }
  387. }
  388. dest := make([]driver.Value, resLen)
  389. if err = rows.readRow(dest); err == nil {
  390. return dest[0].([]byte), mc.readUntilEOF()
  391. }
  392. }
  393. return nil, err
  394. }
  395. // finish is called when the query has canceled.
  396. func (mc *mysqlConn) cancel(err error) {
  397. mc.canceled.Set(err)
  398. mc.cleanup()
  399. }
  400. // finish is called when the query has succeeded.
  401. func (mc *mysqlConn) finish() {
  402. if !mc.watching || mc.finished == nil {
  403. return
  404. }
  405. select {
  406. case mc.finished <- struct{}{}:
  407. mc.watching = false
  408. case <-mc.closech:
  409. }
  410. }
  411. // Ping implements driver.Pinger interface
  412. func (mc *mysqlConn) Ping(ctx context.Context) (err error) {
  413. if mc.closed.IsSet() {
  414. errLog.Print(ErrInvalidConn)
  415. return driver.ErrBadConn
  416. }
  417. if err = mc.watchCancel(ctx); err != nil {
  418. return
  419. }
  420. defer mc.finish()
  421. if err = mc.writeCommandPacket(comPing); err != nil {
  422. return mc.markBadConn(err)
  423. }
  424. return mc.readResultOK()
  425. }
  426. // BeginTx implements driver.ConnBeginTx interface
  427. func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
  428. if err := mc.watchCancel(ctx); err != nil {
  429. return nil, err
  430. }
  431. defer mc.finish()
  432. if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault {
  433. level, err := mapIsolationLevel(opts.Isolation)
  434. if err != nil {
  435. return nil, err
  436. }
  437. err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level)
  438. if err != nil {
  439. return nil, err
  440. }
  441. }
  442. return mc.begin(opts.ReadOnly)
  443. }
  444. func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
  445. dargs, err := namedValueToValue(args)
  446. if err != nil {
  447. return nil, err
  448. }
  449. if err := mc.watchCancel(ctx); err != nil {
  450. return nil, err
  451. }
  452. rows, err := mc.query(query, dargs)
  453. if err != nil {
  454. mc.finish()
  455. return nil, err
  456. }
  457. rows.finish = mc.finish
  458. return rows, err
  459. }
  460. func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
  461. dargs, err := namedValueToValue(args)
  462. if err != nil {
  463. return nil, err
  464. }
  465. if err := mc.watchCancel(ctx); err != nil {
  466. return nil, err
  467. }
  468. defer mc.finish()
  469. return mc.Exec(query, dargs)
  470. }
  471. func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
  472. if err := mc.watchCancel(ctx); err != nil {
  473. return nil, err
  474. }
  475. stmt, err := mc.Prepare(query)
  476. mc.finish()
  477. if err != nil {
  478. return nil, err
  479. }
  480. select {
  481. default:
  482. case <-ctx.Done():
  483. stmt.Close()
  484. return nil, ctx.Err()
  485. }
  486. return stmt, nil
  487. }
  488. func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
  489. dargs, err := namedValueToValue(args)
  490. if err != nil {
  491. return nil, err
  492. }
  493. if err := stmt.mc.watchCancel(ctx); err != nil {
  494. return nil, err
  495. }
  496. rows, err := stmt.query(dargs)
  497. if err != nil {
  498. stmt.mc.finish()
  499. return nil, err
  500. }
  501. rows.finish = stmt.mc.finish
  502. return rows, err
  503. }
  504. func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
  505. dargs, err := namedValueToValue(args)
  506. if err != nil {
  507. return nil, err
  508. }
  509. if err := stmt.mc.watchCancel(ctx); err != nil {
  510. return nil, err
  511. }
  512. defer stmt.mc.finish()
  513. return stmt.Exec(dargs)
  514. }
  515. func (mc *mysqlConn) watchCancel(ctx context.Context) error {
  516. if mc.watching {
  517. // Reach here if canceled,
  518. // so the connection is already invalid
  519. mc.cleanup()
  520. return nil
  521. }
  522. // When ctx is already cancelled, don't watch it.
  523. if err := ctx.Err(); err != nil {
  524. return err
  525. }
  526. // When ctx is not cancellable, don't watch it.
  527. if ctx.Done() == nil {
  528. return nil
  529. }
  530. // When watcher is not alive, can't watch it.
  531. if mc.watcher == nil {
  532. return nil
  533. }
  534. mc.watching = true
  535. mc.watcher <- ctx
  536. return nil
  537. }
  538. func (mc *mysqlConn) startWatcher() {
  539. watcher := make(chan context.Context, 1)
  540. mc.watcher = watcher
  541. finished := make(chan struct{})
  542. mc.finished = finished
  543. go func() {
  544. for {
  545. var ctx context.Context
  546. select {
  547. case ctx = <-watcher:
  548. case <-mc.closech:
  549. return
  550. }
  551. select {
  552. case <-ctx.Done():
  553. mc.cancel(ctx.Err())
  554. case <-finished:
  555. case <-mc.closech:
  556. return
  557. }
  558. }
  559. }()
  560. }
  561. func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) {
  562. nv.Value, err = converter{}.ConvertValue(nv.Value)
  563. return
  564. }
  565. // ResetSession implements driver.SessionResetter.
  566. // (From Go 1.10)
  567. func (mc *mysqlConn) ResetSession(ctx context.Context) error {
  568. if mc.closed.IsSet() {
  569. return driver.ErrBadConn
  570. }
  571. mc.reset = true
  572. return nil
  573. }