utils.go 18 KB

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