utils.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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"
  12. "database/sql/driver"
  13. "encoding/binary"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. )
  23. // Registry for custom tls.Configs
  24. var (
  25. tlsConfigLock sync.RWMutex
  26. tlsConfigRegistry map[string]*tls.Config
  27. )
  28. // RegisterTLSConfig registers a custom tls.Config to be used with sql.Open.
  29. // Use the key as a value in the DSN where tls=value.
  30. //
  31. // Note: The provided tls.Config is exclusively owned by the driver after
  32. // registering it.
  33. //
  34. // rootCertPool := x509.NewCertPool()
  35. // pem, err := ioutil.ReadFile("/path/ca-cert.pem")
  36. // if err != nil {
  37. // log.Fatal(err)
  38. // }
  39. // if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
  40. // log.Fatal("Failed to append PEM.")
  41. // }
  42. // clientCert := make([]tls.Certificate, 0, 1)
  43. // certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem")
  44. // if err != nil {
  45. // log.Fatal(err)
  46. // }
  47. // clientCert = append(clientCert, certs)
  48. // mysql.RegisterTLSConfig("custom", &tls.Config{
  49. // RootCAs: rootCertPool,
  50. // Certificates: clientCert,
  51. // })
  52. // db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom")
  53. //
  54. func RegisterTLSConfig(key string, config *tls.Config) error {
  55. if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" {
  56. return fmt.Errorf("key '%s' is reserved", key)
  57. }
  58. tlsConfigLock.Lock()
  59. if tlsConfigRegistry == nil {
  60. tlsConfigRegistry = make(map[string]*tls.Config)
  61. }
  62. tlsConfigRegistry[key] = config
  63. tlsConfigLock.Unlock()
  64. return nil
  65. }
  66. // DeregisterTLSConfig removes the tls.Config associated with key.
  67. func DeregisterTLSConfig(key string) {
  68. tlsConfigLock.Lock()
  69. if tlsConfigRegistry != nil {
  70. delete(tlsConfigRegistry, key)
  71. }
  72. tlsConfigLock.Unlock()
  73. }
  74. func getTLSConfigClone(key string) (config *tls.Config) {
  75. tlsConfigLock.RLock()
  76. if v, ok := tlsConfigRegistry[key]; ok {
  77. config = v.Clone()
  78. }
  79. tlsConfigLock.RUnlock()
  80. return
  81. }
  82. // Returns the bool value of the input.
  83. // The 2nd return value indicates if the input was a valid bool value
  84. func readBool(input string) (value bool, valid bool) {
  85. switch input {
  86. case "1", "true", "TRUE", "True":
  87. return true, true
  88. case "0", "false", "FALSE", "False":
  89. return false, true
  90. }
  91. // Not a valid bool value
  92. return
  93. }
  94. /******************************************************************************
  95. * Time related utils *
  96. ******************************************************************************/
  97. // NullTime represents a time.Time that may be NULL.
  98. // NullTime implements the Scanner interface so
  99. // it can be used as a scan destination:
  100. //
  101. // var nt NullTime
  102. // err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
  103. // ...
  104. // if nt.Valid {
  105. // // use nt.Time
  106. // } else {
  107. // // NULL value
  108. // }
  109. //
  110. // This NullTime implementation is not driver-specific
  111. type NullTime struct {
  112. Time time.Time
  113. Valid bool // Valid is true if Time is not NULL
  114. }
  115. // Scan implements the Scanner interface.
  116. // The value type must be time.Time or string / []byte (formatted time-string),
  117. // otherwise Scan fails.
  118. func (nt *NullTime) Scan(value interface{}) (err error) {
  119. if value == nil {
  120. nt.Time, nt.Valid = time.Time{}, false
  121. return
  122. }
  123. switch v := value.(type) {
  124. case time.Time:
  125. nt.Time, nt.Valid = v, true
  126. return
  127. case []byte:
  128. nt.Time, err = parseDateTime(string(v), time.UTC)
  129. nt.Valid = (err == nil)
  130. return
  131. case string:
  132. nt.Time, err = parseDateTime(v, time.UTC)
  133. nt.Valid = (err == nil)
  134. return
  135. }
  136. nt.Valid = false
  137. return fmt.Errorf("Can't convert %T to time.Time", value)
  138. }
  139. // Value implements the driver Valuer interface.
  140. func (nt NullTime) Value() (driver.Value, error) {
  141. if !nt.Valid {
  142. return nil, nil
  143. }
  144. return nt.Time, nil
  145. }
  146. func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
  147. base := "0000-00-00 00:00:00.0000000"
  148. switch len(str) {
  149. case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM"
  150. if str == base[:len(str)] {
  151. return
  152. }
  153. t, err = time.Parse(timeFormat[:len(str)], str)
  154. default:
  155. err = fmt.Errorf("invalid time string: %s", str)
  156. return
  157. }
  158. // Adjust location
  159. if err == nil && loc != time.UTC {
  160. y, mo, d := t.Date()
  161. h, mi, s := t.Clock()
  162. t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
  163. }
  164. return
  165. }
  166. func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
  167. switch num {
  168. case 0:
  169. return time.Time{}, nil
  170. case 4:
  171. return time.Date(
  172. int(binary.LittleEndian.Uint16(data[:2])), // year
  173. time.Month(data[2]), // month
  174. int(data[3]), // day
  175. 0, 0, 0, 0,
  176. loc,
  177. ), nil
  178. case 7:
  179. return time.Date(
  180. int(binary.LittleEndian.Uint16(data[:2])), // year
  181. time.Month(data[2]), // month
  182. int(data[3]), // day
  183. int(data[4]), // hour
  184. int(data[5]), // minutes
  185. int(data[6]), // seconds
  186. 0,
  187. loc,
  188. ), nil
  189. case 11:
  190. return time.Date(
  191. int(binary.LittleEndian.Uint16(data[:2])), // year
  192. time.Month(data[2]), // month
  193. int(data[3]), // day
  194. int(data[4]), // hour
  195. int(data[5]), // minutes
  196. int(data[6]), // seconds
  197. int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds
  198. loc,
  199. ), nil
  200. }
  201. return nil, fmt.Errorf("invalid DATETIME packet length %d", num)
  202. }
  203. // zeroDateTime is used in formatBinaryDateTime to avoid an allocation
  204. // if the DATE or DATETIME has the zero value.
  205. // It must never be changed.
  206. // The current behavior depends on database/sql copying the result.
  207. var zeroDateTime = []byte("0000-00-00 00:00:00.000000")
  208. const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
  209. const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
  210. func appendMicrosecs(dst, src []byte, decimals int) []byte {
  211. if decimals <= 0 {
  212. return dst
  213. }
  214. if len(src) == 0 {
  215. return append(dst, ".000000"[:decimals+1]...)
  216. }
  217. microsecs := binary.LittleEndian.Uint32(src[:4])
  218. p1 := byte(microsecs / 10000)
  219. microsecs -= 10000 * uint32(p1)
  220. p2 := byte(microsecs / 100)
  221. microsecs -= 100 * uint32(p2)
  222. p3 := byte(microsecs)
  223. switch decimals {
  224. default:
  225. return append(dst, '.',
  226. digits10[p1], digits01[p1],
  227. digits10[p2], digits01[p2],
  228. digits10[p3], digits01[p3],
  229. )
  230. case 1:
  231. return append(dst, '.',
  232. digits10[p1],
  233. )
  234. case 2:
  235. return append(dst, '.',
  236. digits10[p1], digits01[p1],
  237. )
  238. case 3:
  239. return append(dst, '.',
  240. digits10[p1], digits01[p1],
  241. digits10[p2],
  242. )
  243. case 4:
  244. return append(dst, '.',
  245. digits10[p1], digits01[p1],
  246. digits10[p2], digits01[p2],
  247. )
  248. case 5:
  249. return append(dst, '.',
  250. digits10[p1], digits01[p1],
  251. digits10[p2], digits01[p2],
  252. digits10[p3],
  253. )
  254. }
  255. }
  256. func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) {
  257. // length expects the deterministic length of the zero value,
  258. // negative time and 100+ hours are automatically added if needed
  259. if len(src) == 0 {
  260. return zeroDateTime[:length], nil
  261. }
  262. var dst []byte // return value
  263. var p1, p2, p3 byte // current digit pair
  264. switch length {
  265. case 10, 19, 21, 22, 23, 24, 25, 26:
  266. default:
  267. t := "DATE"
  268. if length > 10 {
  269. t += "TIME"
  270. }
  271. return nil, fmt.Errorf("illegal %s length %d", t, length)
  272. }
  273. switch len(src) {
  274. case 4, 7, 11:
  275. default:
  276. t := "DATE"
  277. if length > 10 {
  278. t += "TIME"
  279. }
  280. return nil, fmt.Errorf("illegal %s packet length %d", t, len(src))
  281. }
  282. dst = make([]byte, 0, length)
  283. // start with the date
  284. year := binary.LittleEndian.Uint16(src[:2])
  285. pt := year / 100
  286. p1 = byte(year - 100*uint16(pt))
  287. p2, p3 = src[2], src[3]
  288. dst = append(dst,
  289. digits10[pt], digits01[pt],
  290. digits10[p1], digits01[p1], '-',
  291. digits10[p2], digits01[p2], '-',
  292. digits10[p3], digits01[p3],
  293. )
  294. if length == 10 {
  295. return dst, nil
  296. }
  297. if len(src) == 4 {
  298. return append(dst, zeroDateTime[10:length]...), nil
  299. }
  300. dst = append(dst, ' ')
  301. p1 = src[4] // hour
  302. src = src[5:]
  303. // p1 is 2-digit hour, src is after hour
  304. p2, p3 = src[0], src[1]
  305. dst = append(dst,
  306. digits10[p1], digits01[p1], ':',
  307. digits10[p2], digits01[p2], ':',
  308. digits10[p3], digits01[p3],
  309. )
  310. return appendMicrosecs(dst, src[2:], int(length)-20), nil
  311. }
  312. func formatBinaryTime(src []byte, length uint8) (driver.Value, error) {
  313. // length expects the deterministic length of the zero value,
  314. // negative time and 100+ hours are automatically added if needed
  315. if len(src) == 0 {
  316. return zeroDateTime[11 : 11+length], nil
  317. }
  318. var dst []byte // return value
  319. switch length {
  320. case
  321. 8, // time (can be up to 10 when negative and 100+ hours)
  322. 10, 11, 12, 13, 14, 15: // time with fractional seconds
  323. default:
  324. return nil, fmt.Errorf("illegal TIME length %d", length)
  325. }
  326. switch len(src) {
  327. case 8, 12:
  328. default:
  329. return nil, fmt.Errorf("invalid TIME packet length %d", len(src))
  330. }
  331. // +2 to enable negative time and 100+ hours
  332. dst = make([]byte, 0, length+2)
  333. if src[0] == 1 {
  334. dst = append(dst, '-')
  335. }
  336. days := binary.LittleEndian.Uint32(src[1:5])
  337. hours := int64(days)*24 + int64(src[5])
  338. if hours >= 100 {
  339. dst = strconv.AppendInt(dst, hours, 10)
  340. } else {
  341. dst = append(dst, digits10[hours], digits01[hours])
  342. }
  343. min, sec := src[6], src[7]
  344. dst = append(dst, ':',
  345. digits10[min], digits01[min], ':',
  346. digits10[sec], digits01[sec],
  347. )
  348. return appendMicrosecs(dst, src[8:], int(length)-9), nil
  349. }
  350. /******************************************************************************
  351. * Convert from and to bytes *
  352. ******************************************************************************/
  353. func uint64ToBytes(n uint64) []byte {
  354. return []byte{
  355. byte(n),
  356. byte(n >> 8),
  357. byte(n >> 16),
  358. byte(n >> 24),
  359. byte(n >> 32),
  360. byte(n >> 40),
  361. byte(n >> 48),
  362. byte(n >> 56),
  363. }
  364. }
  365. func uint64ToString(n uint64) []byte {
  366. var a [20]byte
  367. i := 20
  368. // U+0030 = 0
  369. // ...
  370. // U+0039 = 9
  371. var q uint64
  372. for n >= 10 {
  373. i--
  374. q = n / 10
  375. a[i] = uint8(n-q*10) + 0x30
  376. n = q
  377. }
  378. i--
  379. a[i] = uint8(n) + 0x30
  380. return a[i:]
  381. }
  382. // treats string value as unsigned integer representation
  383. func stringToInt(b []byte) int {
  384. val := 0
  385. for i := range b {
  386. val *= 10
  387. val += int(b[i] - 0x30)
  388. }
  389. return val
  390. }
  391. // returns the string read as a bytes slice, wheter the value is NULL,
  392. // the number of bytes read and an error, in case the string is longer than
  393. // the input slice
  394. func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  395. // Get length
  396. num, isNull, n := readLengthEncodedInteger(b)
  397. if num < 1 {
  398. return b[n:n], isNull, n, nil
  399. }
  400. n += int(num)
  401. // Check data length
  402. if len(b) >= n {
  403. return b[n-int(num) : n : n], false, n, nil
  404. }
  405. return nil, false, n, io.EOF
  406. }
  407. // returns the number of bytes skipped and an error, in case the string is
  408. // longer than the input slice
  409. func skipLengthEncodedString(b []byte) (int, error) {
  410. // Get length
  411. num, _, n := readLengthEncodedInteger(b)
  412. if num < 1 {
  413. return n, nil
  414. }
  415. n += int(num)
  416. // Check data length
  417. if len(b) >= n {
  418. return n, nil
  419. }
  420. return n, io.EOF
  421. }
  422. // returns the number read, whether the value is NULL and the number of bytes read
  423. func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  424. // See issue #349
  425. if len(b) == 0 {
  426. return 0, true, 1
  427. }
  428. switch b[0] {
  429. // 251: NULL
  430. case 0xfb:
  431. return 0, true, 1
  432. // 252: value of following 2
  433. case 0xfc:
  434. return uint64(b[1]) | uint64(b[2])<<8, false, 3
  435. // 253: value of following 3
  436. case 0xfd:
  437. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
  438. // 254: value of following 8
  439. case 0xfe:
  440. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  441. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  442. uint64(b[7])<<48 | uint64(b[8])<<56,
  443. false, 9
  444. }
  445. // 0-250: value of first byte
  446. return uint64(b[0]), false, 1
  447. }
  448. // encodes a uint64 value and appends it to the given bytes slice
  449. func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  450. switch {
  451. case n <= 250:
  452. return append(b, byte(n))
  453. case n <= 0xffff:
  454. return append(b, 0xfc, byte(n), byte(n>>8))
  455. case n <= 0xffffff:
  456. return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
  457. }
  458. return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
  459. byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
  460. }
  461. // reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize.
  462. // If cap(buf) is not enough, reallocate new buffer.
  463. func reserveBuffer(buf []byte, appendSize int) []byte {
  464. newSize := len(buf) + appendSize
  465. if cap(buf) < newSize {
  466. // Grow buffer exponentially
  467. newBuf := make([]byte, len(buf)*2+appendSize)
  468. copy(newBuf, buf)
  469. buf = newBuf
  470. }
  471. return buf[:newSize]
  472. }
  473. // escapeBytesBackslash escapes []byte with backslashes (\)
  474. // This escapes the contents of a string (provided as []byte) by adding backslashes before special
  475. // characters, and turning others into specific escape sequences, such as
  476. // turning newlines into \n and null bytes into \0.
  477. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932
  478. func escapeBytesBackslash(buf, v []byte) []byte {
  479. pos := len(buf)
  480. buf = reserveBuffer(buf, len(v)*2)
  481. for _, c := range v {
  482. switch c {
  483. case '\x00':
  484. buf[pos] = '\\'
  485. buf[pos+1] = '0'
  486. pos += 2
  487. case '\n':
  488. buf[pos] = '\\'
  489. buf[pos+1] = 'n'
  490. pos += 2
  491. case '\r':
  492. buf[pos] = '\\'
  493. buf[pos+1] = 'r'
  494. pos += 2
  495. case '\x1a':
  496. buf[pos] = '\\'
  497. buf[pos+1] = 'Z'
  498. pos += 2
  499. case '\'':
  500. buf[pos] = '\\'
  501. buf[pos+1] = '\''
  502. pos += 2
  503. case '"':
  504. buf[pos] = '\\'
  505. buf[pos+1] = '"'
  506. pos += 2
  507. case '\\':
  508. buf[pos] = '\\'
  509. buf[pos+1] = '\\'
  510. pos += 2
  511. default:
  512. buf[pos] = c
  513. pos++
  514. }
  515. }
  516. return buf[:pos]
  517. }
  518. // escapeStringBackslash is similar to escapeBytesBackslash but for string.
  519. func escapeStringBackslash(buf []byte, v string) []byte {
  520. pos := len(buf)
  521. buf = reserveBuffer(buf, len(v)*2)
  522. for i := 0; i < len(v); i++ {
  523. c := v[i]
  524. switch c {
  525. case '\x00':
  526. buf[pos] = '\\'
  527. buf[pos+1] = '0'
  528. pos += 2
  529. case '\n':
  530. buf[pos] = '\\'
  531. buf[pos+1] = 'n'
  532. pos += 2
  533. case '\r':
  534. buf[pos] = '\\'
  535. buf[pos+1] = 'r'
  536. pos += 2
  537. case '\x1a':
  538. buf[pos] = '\\'
  539. buf[pos+1] = 'Z'
  540. pos += 2
  541. case '\'':
  542. buf[pos] = '\\'
  543. buf[pos+1] = '\''
  544. pos += 2
  545. case '"':
  546. buf[pos] = '\\'
  547. buf[pos+1] = '"'
  548. pos += 2
  549. case '\\':
  550. buf[pos] = '\\'
  551. buf[pos+1] = '\\'
  552. pos += 2
  553. default:
  554. buf[pos] = c
  555. pos++
  556. }
  557. }
  558. return buf[:pos]
  559. }
  560. // escapeBytesQuotes escapes apostrophes in []byte by doubling them up.
  561. // This escapes the contents of a string by doubling up any apostrophes that
  562. // it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
  563. // effect on the server.
  564. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038
  565. func escapeBytesQuotes(buf, v []byte) []byte {
  566. pos := len(buf)
  567. buf = reserveBuffer(buf, len(v)*2)
  568. for _, c := range v {
  569. if c == '\'' {
  570. buf[pos] = '\''
  571. buf[pos+1] = '\''
  572. pos += 2
  573. } else {
  574. buf[pos] = c
  575. pos++
  576. }
  577. }
  578. return buf[:pos]
  579. }
  580. // escapeStringQuotes is similar to escapeBytesQuotes but for string.
  581. func escapeStringQuotes(buf []byte, v string) []byte {
  582. pos := len(buf)
  583. buf = reserveBuffer(buf, len(v)*2)
  584. for i := 0; i < len(v); i++ {
  585. c := v[i]
  586. if c == '\'' {
  587. buf[pos] = '\''
  588. buf[pos+1] = '\''
  589. pos += 2
  590. } else {
  591. buf[pos] = c
  592. pos++
  593. }
  594. }
  595. return buf[:pos]
  596. }
  597. /******************************************************************************
  598. * Sync utils *
  599. ******************************************************************************/
  600. // noCopy may be embedded into structs which must not be copied
  601. // after the first use.
  602. //
  603. // See https://github.com/golang/go/issues/8005#issuecomment-190753527
  604. // for details.
  605. type noCopy struct{}
  606. // Lock is a no-op used by -copylocks checker from `go vet`.
  607. func (*noCopy) Lock() {}
  608. // atomicBool is a wrapper around uint32 for usage as a boolean value with
  609. // atomic access.
  610. type atomicBool struct {
  611. _noCopy noCopy
  612. value uint32
  613. }
  614. // IsSet returns wether the current boolean value is true
  615. func (ab *atomicBool) IsSet() bool {
  616. return atomic.LoadUint32(&ab.value) > 0
  617. }
  618. // Set sets the value of the bool regardless of the previous value
  619. func (ab *atomicBool) Set(value bool) {
  620. if value {
  621. atomic.StoreUint32(&ab.value, 1)
  622. } else {
  623. atomic.StoreUint32(&ab.value, 0)
  624. }
  625. }
  626. // TrySet sets the value of the bool and returns wether the value changed
  627. func (ab *atomicBool) TrySet(value bool) bool {
  628. if value {
  629. return atomic.SwapUint32(&ab.value, 1) == 0
  630. }
  631. return atomic.SwapUint32(&ab.value, 0) > 0
  632. }
  633. // atomicError is a wrapper for atomically accessed error values
  634. type atomicError struct {
  635. _noCopy noCopy
  636. value atomic.Value
  637. }
  638. // Set sets the error value regardless of the previous value.
  639. // The value must not be nil
  640. func (ae *atomicError) Set(value error) {
  641. ae.value.Store(value)
  642. }
  643. // Value returns the current error value
  644. func (ae *atomicError) Value() error {
  645. if v := ae.value.Load(); v != nil {
  646. // this will panic if the value doesn't implement the error interface
  647. return v.(error)
  648. }
  649. return nil
  650. }
  651. func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {
  652. dargs := make([]driver.Value, len(named))
  653. for n, param := range named {
  654. if len(param.Name) > 0 {
  655. // TODO: support the use of Named Parameters #561
  656. return nil, errors.New("mysql: driver does not support the use of Named Parameters")
  657. }
  658. dargs[n] = param.Value
  659. }
  660. return dargs, nil
  661. }
  662. func mapIsolationLevel(level driver.IsolationLevel) (string, error) {
  663. switch sql.IsolationLevel(level) {
  664. case sql.LevelRepeatableRead:
  665. return "REPEATABLE READ", nil
  666. case sql.LevelReadCommitted:
  667. return "READ COMMITTED", nil
  668. case sql.LevelReadUncommitted:
  669. return "READ UNCOMMITTED", nil
  670. case sql.LevelSerializable:
  671. return "SERIALIZABLE", nil
  672. default:
  673. return "", fmt.Errorf("mysql: unsupported isolation level: %v", level)
  674. }
  675. }