utils.go 19 KB

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