utils.go 20 KB

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