utils.go 18 KB

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