utils.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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 := os.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, timeTruncate time.Duration) ([]byte, error) {
  242. if timeTruncate > 0 {
  243. t = t.Truncate(timeTruncate)
  244. }
  245. year, month, day := t.Date()
  246. hour, min, sec := t.Clock()
  247. nsec := t.Nanosecond()
  248. if year < 1 || year > 9999 {
  249. 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
  250. }
  251. year100 := year / 100
  252. year1 := year % 100
  253. var localBuf [len("2006-01-02T15:04:05.999999999")]byte // does not escape
  254. localBuf[0], localBuf[1], localBuf[2], localBuf[3] = digits10[year100], digits01[year100], digits10[year1], digits01[year1]
  255. localBuf[4] = '-'
  256. localBuf[5], localBuf[6] = digits10[month], digits01[month]
  257. localBuf[7] = '-'
  258. localBuf[8], localBuf[9] = digits10[day], digits01[day]
  259. if hour == 0 && min == 0 && sec == 0 && nsec == 0 {
  260. return append(buf, localBuf[:10]...), nil
  261. }
  262. localBuf[10] = ' '
  263. localBuf[11], localBuf[12] = digits10[hour], digits01[hour]
  264. localBuf[13] = ':'
  265. localBuf[14], localBuf[15] = digits10[min], digits01[min]
  266. localBuf[16] = ':'
  267. localBuf[17], localBuf[18] = digits10[sec], digits01[sec]
  268. if nsec == 0 {
  269. return append(buf, localBuf[:19]...), nil
  270. }
  271. nsec100000000 := nsec / 100000000
  272. nsec1000000 := (nsec / 1000000) % 100
  273. nsec10000 := (nsec / 10000) % 100
  274. nsec100 := (nsec / 100) % 100
  275. nsec1 := nsec % 100
  276. localBuf[19] = '.'
  277. // milli second
  278. localBuf[20], localBuf[21], localBuf[22] =
  279. digits01[nsec100000000], digits10[nsec1000000], digits01[nsec1000000]
  280. // micro second
  281. localBuf[23], localBuf[24], localBuf[25] =
  282. digits10[nsec10000], digits01[nsec10000], digits10[nsec100]
  283. // nano second
  284. localBuf[26], localBuf[27], localBuf[28] =
  285. digits01[nsec100], digits10[nsec1], digits01[nsec1]
  286. // trim trailing zeros
  287. n := len(localBuf)
  288. for n > 0 && localBuf[n-1] == '0' {
  289. n--
  290. }
  291. return append(buf, localBuf[:n]...), nil
  292. }
  293. // zeroDateTime is used in formatBinaryDateTime to avoid an allocation
  294. // if the DATE or DATETIME has the zero value.
  295. // It must never be changed.
  296. // The current behavior depends on database/sql copying the result.
  297. var zeroDateTime = []byte("0000-00-00 00:00:00.000000")
  298. const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
  299. const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
  300. func appendMicrosecs(dst, src []byte, decimals int) []byte {
  301. if decimals <= 0 {
  302. return dst
  303. }
  304. if len(src) == 0 {
  305. return append(dst, ".000000"[:decimals+1]...)
  306. }
  307. microsecs := binary.LittleEndian.Uint32(src[:4])
  308. p1 := byte(microsecs / 10000)
  309. microsecs -= 10000 * uint32(p1)
  310. p2 := byte(microsecs / 100)
  311. microsecs -= 100 * uint32(p2)
  312. p3 := byte(microsecs)
  313. switch decimals {
  314. default:
  315. return append(dst, '.',
  316. digits10[p1], digits01[p1],
  317. digits10[p2], digits01[p2],
  318. digits10[p3], digits01[p3],
  319. )
  320. case 1:
  321. return append(dst, '.',
  322. digits10[p1],
  323. )
  324. case 2:
  325. return append(dst, '.',
  326. digits10[p1], digits01[p1],
  327. )
  328. case 3:
  329. return append(dst, '.',
  330. digits10[p1], digits01[p1],
  331. digits10[p2],
  332. )
  333. case 4:
  334. return append(dst, '.',
  335. digits10[p1], digits01[p1],
  336. digits10[p2], digits01[p2],
  337. )
  338. case 5:
  339. return append(dst, '.',
  340. digits10[p1], digits01[p1],
  341. digits10[p2], digits01[p2],
  342. digits10[p3],
  343. )
  344. }
  345. }
  346. func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) {
  347. // length expects the deterministic length of the zero value,
  348. // negative time and 100+ hours are automatically added if needed
  349. if len(src) == 0 {
  350. return zeroDateTime[:length], nil
  351. }
  352. var dst []byte // return value
  353. var p1, p2, p3 byte // current digit pair
  354. switch length {
  355. case 10, 19, 21, 22, 23, 24, 25, 26:
  356. default:
  357. t := "DATE"
  358. if length > 10 {
  359. t += "TIME"
  360. }
  361. return nil, fmt.Errorf("illegal %s length %d", t, length)
  362. }
  363. switch len(src) {
  364. case 4, 7, 11:
  365. default:
  366. t := "DATE"
  367. if length > 10 {
  368. t += "TIME"
  369. }
  370. return nil, fmt.Errorf("illegal %s packet length %d", t, len(src))
  371. }
  372. dst = make([]byte, 0, length)
  373. // start with the date
  374. year := binary.LittleEndian.Uint16(src[:2])
  375. pt := year / 100
  376. p1 = byte(year - 100*uint16(pt))
  377. p2, p3 = src[2], src[3]
  378. dst = append(dst,
  379. digits10[pt], digits01[pt],
  380. digits10[p1], digits01[p1], '-',
  381. digits10[p2], digits01[p2], '-',
  382. digits10[p3], digits01[p3],
  383. )
  384. if length == 10 {
  385. return dst, nil
  386. }
  387. if len(src) == 4 {
  388. return append(dst, zeroDateTime[10:length]...), nil
  389. }
  390. dst = append(dst, ' ')
  391. p1 = src[4] // hour
  392. src = src[5:]
  393. // p1 is 2-digit hour, src is after hour
  394. p2, p3 = src[0], src[1]
  395. dst = append(dst,
  396. digits10[p1], digits01[p1], ':',
  397. digits10[p2], digits01[p2], ':',
  398. digits10[p3], digits01[p3],
  399. )
  400. return appendMicrosecs(dst, src[2:], int(length)-20), nil
  401. }
  402. func formatBinaryTime(src []byte, length uint8) (driver.Value, error) {
  403. // length expects the deterministic length of the zero value,
  404. // negative time and 100+ hours are automatically added if needed
  405. if len(src) == 0 {
  406. return zeroDateTime[11 : 11+length], nil
  407. }
  408. var dst []byte // return value
  409. switch length {
  410. case
  411. 8, // time (can be up to 10 when negative and 100+ hours)
  412. 10, 11, 12, 13, 14, 15: // time with fractional seconds
  413. default:
  414. return nil, fmt.Errorf("illegal TIME length %d", length)
  415. }
  416. switch len(src) {
  417. case 8, 12:
  418. default:
  419. return nil, fmt.Errorf("invalid TIME packet length %d", len(src))
  420. }
  421. // +2 to enable negative time and 100+ hours
  422. dst = make([]byte, 0, length+2)
  423. if src[0] == 1 {
  424. dst = append(dst, '-')
  425. }
  426. days := binary.LittleEndian.Uint32(src[1:5])
  427. hours := int64(days)*24 + int64(src[5])
  428. if hours >= 100 {
  429. dst = strconv.AppendInt(dst, hours, 10)
  430. } else {
  431. dst = append(dst, digits10[hours], digits01[hours])
  432. }
  433. min, sec := src[6], src[7]
  434. dst = append(dst, ':',
  435. digits10[min], digits01[min], ':',
  436. digits10[sec], digits01[sec],
  437. )
  438. return appendMicrosecs(dst, src[8:], int(length)-9), nil
  439. }
  440. /******************************************************************************
  441. * Convert from and to bytes *
  442. ******************************************************************************/
  443. func uint64ToBytes(n uint64) []byte {
  444. return []byte{
  445. byte(n),
  446. byte(n >> 8),
  447. byte(n >> 16),
  448. byte(n >> 24),
  449. byte(n >> 32),
  450. byte(n >> 40),
  451. byte(n >> 48),
  452. byte(n >> 56),
  453. }
  454. }
  455. func uint64ToString(n uint64) []byte {
  456. var a [20]byte
  457. i := 20
  458. // U+0030 = 0
  459. // ...
  460. // U+0039 = 9
  461. var q uint64
  462. for n >= 10 {
  463. i--
  464. q = n / 10
  465. a[i] = uint8(n-q*10) + 0x30
  466. n = q
  467. }
  468. i--
  469. a[i] = uint8(n) + 0x30
  470. return a[i:]
  471. }
  472. // treats string value as unsigned integer representation
  473. func stringToInt(b []byte) int {
  474. val := 0
  475. for i := range b {
  476. val *= 10
  477. val += int(b[i] - 0x30)
  478. }
  479. return val
  480. }
  481. // returns the string read as a bytes slice, whether the value is NULL,
  482. // the number of bytes read and an error, in case the string is longer than
  483. // the input slice
  484. func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  485. // Get length
  486. num, isNull, n := readLengthEncodedInteger(b)
  487. if num < 1 {
  488. return b[n:n], isNull, n, nil
  489. }
  490. n += int(num)
  491. // Check data length
  492. if len(b) >= n {
  493. return b[n-int(num) : n : n], false, n, nil
  494. }
  495. return nil, false, n, io.EOF
  496. }
  497. // returns the number of bytes skipped and an error, in case the string is
  498. // longer than the input slice
  499. func skipLengthEncodedString(b []byte) (int, error) {
  500. // Get length
  501. num, _, n := readLengthEncodedInteger(b)
  502. if num < 1 {
  503. return n, nil
  504. }
  505. n += int(num)
  506. // Check data length
  507. if len(b) >= n {
  508. return n, nil
  509. }
  510. return n, io.EOF
  511. }
  512. // returns the number read, whether the value is NULL and the number of bytes read
  513. func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  514. // See issue #349
  515. if len(b) == 0 {
  516. return 0, true, 1
  517. }
  518. switch b[0] {
  519. // 251: NULL
  520. case 0xfb:
  521. return 0, true, 1
  522. // 252: value of following 2
  523. case 0xfc:
  524. return uint64(b[1]) | uint64(b[2])<<8, false, 3
  525. // 253: value of following 3
  526. case 0xfd:
  527. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
  528. // 254: value of following 8
  529. case 0xfe:
  530. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  531. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  532. uint64(b[7])<<48 | uint64(b[8])<<56,
  533. false, 9
  534. }
  535. // 0-250: value of first byte
  536. return uint64(b[0]), false, 1
  537. }
  538. // encodes a uint64 value and appends it to the given bytes slice
  539. func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  540. switch {
  541. case n <= 250:
  542. return append(b, byte(n))
  543. case n <= 0xffff:
  544. return append(b, 0xfc, byte(n), byte(n>>8))
  545. case n <= 0xffffff:
  546. return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
  547. }
  548. return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
  549. byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
  550. }
  551. func appendLengthEncodedString(b []byte, s string) []byte {
  552. b = appendLengthEncodedInteger(b, uint64(len(s)))
  553. return append(b, s...)
  554. }
  555. // reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize.
  556. // If cap(buf) is not enough, reallocate new buffer.
  557. func reserveBuffer(buf []byte, appendSize int) []byte {
  558. newSize := len(buf) + appendSize
  559. if cap(buf) < newSize {
  560. // Grow buffer exponentially
  561. newBuf := make([]byte, len(buf)*2+appendSize)
  562. copy(newBuf, buf)
  563. buf = newBuf
  564. }
  565. return buf[:newSize]
  566. }
  567. // escapeBytesBackslash escapes []byte with backslashes (\)
  568. // This escapes the contents of a string (provided as []byte) by adding backslashes before special
  569. // characters, and turning others into specific escape sequences, such as
  570. // turning newlines into \n and null bytes into \0.
  571. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932
  572. func escapeBytesBackslash(buf, v []byte) []byte {
  573. pos := len(buf)
  574. buf = reserveBuffer(buf, len(v)*2)
  575. for _, c := range v {
  576. switch c {
  577. case '\x00':
  578. buf[pos+1] = '0'
  579. buf[pos] = '\\'
  580. pos += 2
  581. case '\n':
  582. buf[pos+1] = 'n'
  583. buf[pos] = '\\'
  584. pos += 2
  585. case '\r':
  586. buf[pos+1] = 'r'
  587. buf[pos] = '\\'
  588. pos += 2
  589. case '\x1a':
  590. buf[pos+1] = 'Z'
  591. buf[pos] = '\\'
  592. pos += 2
  593. case '\'':
  594. buf[pos+1] = '\''
  595. buf[pos] = '\\'
  596. pos += 2
  597. case '"':
  598. buf[pos+1] = '"'
  599. buf[pos] = '\\'
  600. pos += 2
  601. case '\\':
  602. buf[pos+1] = '\\'
  603. buf[pos] = '\\'
  604. pos += 2
  605. default:
  606. buf[pos] = c
  607. pos++
  608. }
  609. }
  610. return buf[:pos]
  611. }
  612. // escapeStringBackslash is similar to escapeBytesBackslash but for string.
  613. func escapeStringBackslash(buf []byte, v string) []byte {
  614. pos := len(buf)
  615. buf = reserveBuffer(buf, len(v)*2)
  616. for i := 0; i < len(v); i++ {
  617. c := v[i]
  618. switch c {
  619. case '\x00':
  620. buf[pos+1] = '0'
  621. buf[pos] = '\\'
  622. pos += 2
  623. case '\n':
  624. buf[pos+1] = 'n'
  625. buf[pos] = '\\'
  626. pos += 2
  627. case '\r':
  628. buf[pos+1] = 'r'
  629. buf[pos] = '\\'
  630. pos += 2
  631. case '\x1a':
  632. buf[pos+1] = 'Z'
  633. buf[pos] = '\\'
  634. pos += 2
  635. case '\'':
  636. buf[pos+1] = '\''
  637. buf[pos] = '\\'
  638. pos += 2
  639. case '"':
  640. buf[pos+1] = '"'
  641. buf[pos] = '\\'
  642. pos += 2
  643. case '\\':
  644. buf[pos+1] = '\\'
  645. buf[pos] = '\\'
  646. pos += 2
  647. default:
  648. buf[pos] = c
  649. pos++
  650. }
  651. }
  652. return buf[:pos]
  653. }
  654. // escapeBytesQuotes escapes apostrophes in []byte by doubling them up.
  655. // This escapes the contents of a string by doubling up any apostrophes that
  656. // it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
  657. // effect on the server.
  658. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038
  659. func escapeBytesQuotes(buf, v []byte) []byte {
  660. pos := len(buf)
  661. buf = reserveBuffer(buf, len(v)*2)
  662. for _, c := range v {
  663. if c == '\'' {
  664. buf[pos+1] = '\''
  665. buf[pos] = '\''
  666. pos += 2
  667. } else {
  668. buf[pos] = c
  669. pos++
  670. }
  671. }
  672. return buf[:pos]
  673. }
  674. // escapeStringQuotes is similar to escapeBytesQuotes but for string.
  675. func escapeStringQuotes(buf []byte, v string) []byte {
  676. pos := len(buf)
  677. buf = reserveBuffer(buf, len(v)*2)
  678. for i := 0; i < len(v); i++ {
  679. c := v[i]
  680. if c == '\'' {
  681. buf[pos+1] = '\''
  682. buf[pos] = '\''
  683. pos += 2
  684. } else {
  685. buf[pos] = c
  686. pos++
  687. }
  688. }
  689. return buf[:pos]
  690. }
  691. /******************************************************************************
  692. * Sync utils *
  693. ******************************************************************************/
  694. // noCopy may be embedded into structs which must not be copied
  695. // after the first use.
  696. //
  697. // See https://github.com/golang/go/issues/8005#issuecomment-190753527
  698. // for details.
  699. type noCopy struct{}
  700. // Lock is a no-op used by -copylocks checker from `go vet`.
  701. func (*noCopy) Lock() {}
  702. // Unlock is a no-op used by -copylocks checker from `go vet`.
  703. // noCopy should implement sync.Locker from Go 1.11
  704. // https://github.com/golang/go/commit/c2eba53e7f80df21d51285879d51ab81bcfbf6bc
  705. // https://github.com/golang/go/issues/26165
  706. func (*noCopy) Unlock() {}
  707. // atomicError is a wrapper for atomically accessed error values
  708. type atomicError struct {
  709. _ noCopy
  710. value atomic.Value
  711. }
  712. // Set sets the error value regardless of the previous value.
  713. // The value must not be nil
  714. func (ae *atomicError) Set(value error) {
  715. ae.value.Store(value)
  716. }
  717. // Value returns the current error value
  718. func (ae *atomicError) Value() error {
  719. if v := ae.value.Load(); v != nil {
  720. // this will panic if the value doesn't implement the error interface
  721. return v.(error)
  722. }
  723. return nil
  724. }
  725. func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {
  726. dargs := make([]driver.Value, len(named))
  727. for n, param := range named {
  728. if len(param.Name) > 0 {
  729. // TODO: support the use of Named Parameters #561
  730. return nil, errors.New("mysql: driver does not support the use of Named Parameters")
  731. }
  732. dargs[n] = param.Value
  733. }
  734. return dargs, nil
  735. }
  736. func mapIsolationLevel(level driver.IsolationLevel) (string, error) {
  737. switch sql.IsolationLevel(level) {
  738. case sql.LevelRepeatableRead:
  739. return "REPEATABLE READ", nil
  740. case sql.LevelReadCommitted:
  741. return "READ COMMITTED", nil
  742. case sql.LevelReadUncommitted:
  743. return "READ UNCOMMITTED", nil
  744. case sql.LevelSerializable:
  745. return "SERIALIZABLE", nil
  746. default:
  747. return "", fmt.Errorf("mysql: unsupported isolation level: %v", level)
  748. }
  749. }