utils.go 17 KB

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