utils.go 20 KB

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