packets.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2012 Julien Schmidt. All rights reserved.
  4. // http://www.julienschmidt.com
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla Public
  7. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  8. // You can obtain one at http://mozilla.org/MPL/2.0/.
  9. package mysql
  10. import (
  11. "bytes"
  12. "crypto/tls"
  13. "database/sql/driver"
  14. "encoding/binary"
  15. "fmt"
  16. "io"
  17. "math"
  18. "time"
  19. )
  20. // Packets documentation:
  21. // http://dev.mysql.com/doc/internals/en/client-server-protocol.html
  22. // Read packet to buffer 'data'
  23. func (mc *mysqlConn) readPacket() (data []byte, err error) {
  24. // Read packet header
  25. data, err = mc.buf.readNext(4)
  26. if err != nil {
  27. errLog.Print(err.Error())
  28. mc.Close()
  29. return nil, driver.ErrBadConn
  30. }
  31. // Packet Length [24 bit]
  32. pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16)
  33. if pktLen < 1 {
  34. errLog.Print(errMalformPkt.Error())
  35. mc.Close()
  36. return nil, driver.ErrBadConn
  37. }
  38. // Check Packet Sync [8 bit]
  39. if data[3] != mc.sequence {
  40. if data[3] > mc.sequence {
  41. return nil, errPktSyncMul
  42. } else {
  43. return nil, errPktSync
  44. }
  45. }
  46. mc.sequence++
  47. // Read packet body [pktLen bytes]
  48. if data, err = mc.buf.readNext(pktLen); err == nil {
  49. if pktLen < maxPacketSize {
  50. return data, nil
  51. }
  52. var buf []byte
  53. buf = append(buf, data...)
  54. // More data
  55. data, err = mc.readPacket()
  56. if err == nil {
  57. return append(buf, data...), nil
  58. }
  59. }
  60. // err case
  61. mc.Close()
  62. errLog.Print(err.Error())
  63. return nil, driver.ErrBadConn
  64. }
  65. // Write packet buffer 'data'
  66. // The packet header must be already included
  67. func (mc *mysqlConn) writePacket(data []byte) error {
  68. if len(data)-4 <= mc.maxWriteSize { // Can send data at once
  69. // Write packet
  70. n, err := mc.netConn.Write(data)
  71. if err == nil && n == len(data) {
  72. mc.sequence++
  73. return nil
  74. }
  75. // Handle error
  76. if err == nil { // n != len(data)
  77. errLog.Print(errMalformPkt.Error())
  78. } else {
  79. errLog.Print(err.Error())
  80. }
  81. return driver.ErrBadConn
  82. }
  83. // Must split packet
  84. return mc.splitPacket(data)
  85. }
  86. func (mc *mysqlConn) splitPacket(data []byte) (err error) {
  87. pktLen := len(data) - 4
  88. if pktLen > mc.maxPacketAllowed {
  89. return errPktTooLarge
  90. }
  91. for pktLen >= maxPacketSize {
  92. data[0] = 0xff
  93. data[1] = 0xff
  94. data[2] = 0xff
  95. data[3] = mc.sequence
  96. // Write packet
  97. n, err := mc.netConn.Write(data[:4+maxPacketSize])
  98. if err == nil && n == 4+maxPacketSize {
  99. mc.sequence++
  100. data = data[maxPacketSize:]
  101. pktLen -= maxPacketSize
  102. continue
  103. }
  104. // Handle error
  105. if err == nil { // n != len(data)
  106. errLog.Print(errMalformPkt.Error())
  107. } else {
  108. errLog.Print(err.Error())
  109. }
  110. return driver.ErrBadConn
  111. }
  112. data[0] = byte(pktLen)
  113. data[1] = byte(pktLen >> 8)
  114. data[2] = byte(pktLen >> 16)
  115. data[3] = mc.sequence
  116. return mc.writePacket(data)
  117. }
  118. /******************************************************************************
  119. * Initialisation Process *
  120. ******************************************************************************/
  121. // Handshake Initialization Packet
  122. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
  123. func (mc *mysqlConn) readInitPacket() (err error) {
  124. data, err := mc.readPacket()
  125. if err != nil {
  126. return
  127. }
  128. if data[0] == iERR {
  129. return mc.handleErrorPacket(data)
  130. }
  131. // protocol version [1 byte]
  132. if data[0] < minProtocolVersion {
  133. err = fmt.Errorf(
  134. "Unsupported MySQL Protocol Version %d. Protocol Version %d or higher is required",
  135. data[0],
  136. minProtocolVersion)
  137. }
  138. // server version [null terminated string]
  139. // connection id [4 bytes]
  140. pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4
  141. // first part of the password cipher [8 bytes]
  142. mc.cipher = append(mc.cipher, data[pos:pos+8]...)
  143. // (filler) always 0x00 [1 byte]
  144. pos += 8 + 1
  145. // capability flags (lower 2 bytes) [2 bytes]
  146. mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  147. if mc.flags&clientProtocol41 == 0 {
  148. err = errOldProtocol
  149. }
  150. if mc.flags&clientSSL == 0 && mc.cfg.tls != nil {
  151. return errNoTLS
  152. }
  153. pos += 2
  154. if len(data) > pos {
  155. // character set [1 byte]
  156. // status flags [2 bytes]
  157. // capability flags (upper 2 bytes) [2 bytes]
  158. // length of auth-plugin-data [1 byte]
  159. // reserved (all [00]) [10 bytes]
  160. pos += 1 + 2 + 2 + 1 + 10
  161. // second part of the password cipher [12? bytes]
  162. // The documentation is ambiguous about the length.
  163. // The official Python library uses the fixed length 12
  164. // which is not documented but seems to work.
  165. mc.cipher = append(mc.cipher, data[pos:pos+12]...)
  166. // TODO: Verify string termination
  167. // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2)
  168. // \NUL otherwise
  169. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
  170. //
  171. //if data[len(data)-1] == 0 {
  172. // return
  173. //}
  174. //return errMalformPkt
  175. }
  176. return
  177. }
  178. // Client Authentication Packet
  179. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::HandshakeResponse
  180. func (mc *mysqlConn) writeAuthPacket() error {
  181. // Adjust client flags based on server support
  182. clientFlags := clientProtocol41 |
  183. clientSecureConn |
  184. clientLongPassword |
  185. clientTransactions |
  186. clientLocalFiles |
  187. mc.flags&clientLongFlag
  188. if mc.cfg.clientFoundRows {
  189. clientFlags |= clientFoundRows
  190. }
  191. // To enable TLS / SSL
  192. if mc.cfg.tls != nil {
  193. clientFlags |= clientSSL
  194. }
  195. // User Password
  196. scrambleBuff := scramblePassword(mc.cipher, []byte(mc.cfg.passwd))
  197. mc.cipher = nil
  198. pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff)
  199. // To specify a db name
  200. if n := len(mc.cfg.dbname); n > 0 {
  201. clientFlags |= clientConnectWithDB
  202. pktLen += n + 1
  203. }
  204. // Calculate packet length and make buffer with that size
  205. data := make([]byte, pktLen+4)
  206. // ClientFlags [32 bit]
  207. data[4] = byte(clientFlags)
  208. data[5] = byte(clientFlags >> 8)
  209. data[6] = byte(clientFlags >> 16)
  210. data[7] = byte(clientFlags >> 24)
  211. // MaxPacketSize [32 bit] (none)
  212. //data[8] = 0x00
  213. //data[9] = 0x00
  214. //data[10] = 0x00
  215. //data[11] = 0x00
  216. // Charset [1 byte]
  217. data[12] = collation_utf8_general_ci
  218. // SSL Connection Request Packet
  219. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::SSLRequest
  220. if mc.cfg.tls != nil {
  221. // Packet header [24bit length + 1 byte sequence]
  222. data[0] = byte((4 + 4 + 1 + 23))
  223. data[1] = byte((4 + 4 + 1 + 23) >> 8)
  224. data[2] = byte((4 + 4 + 1 + 23) >> 16)
  225. data[3] = mc.sequence
  226. // Send TLS / SSL request packet
  227. if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil {
  228. return err
  229. }
  230. // Switch to TLS
  231. tlsConn := tls.Client(mc.netConn, mc.cfg.tls)
  232. if err := tlsConn.Handshake(); err != nil {
  233. return err
  234. }
  235. mc.netConn = tlsConn
  236. mc.buf.rd = tlsConn
  237. }
  238. // Add the packet header [24bit length + 1 byte sequence]
  239. data[0] = byte(pktLen)
  240. data[1] = byte(pktLen >> 8)
  241. data[2] = byte(pktLen >> 16)
  242. data[3] = mc.sequence
  243. // Filler [23 bytes] (all 0x00)
  244. pos := 13 + 23
  245. // User [null terminated string]
  246. if len(mc.cfg.user) > 0 {
  247. pos += copy(data[pos:], mc.cfg.user)
  248. }
  249. //data[pos] = 0x00
  250. pos++
  251. // ScrambleBuffer [length encoded integer]
  252. data[pos] = byte(len(scrambleBuff))
  253. pos += 1 + copy(data[pos+1:], scrambleBuff)
  254. // Databasename [null terminated string]
  255. if len(mc.cfg.dbname) > 0 {
  256. pos += copy(data[pos:], mc.cfg.dbname)
  257. //data[pos] = 0x00
  258. }
  259. // Send Auth packet
  260. return mc.writePacket(data)
  261. }
  262. /******************************************************************************
  263. * Command Packets *
  264. ******************************************************************************/
  265. func (mc *mysqlConn) writeCommandPacket(command byte) error {
  266. // Reset Packet Sequence
  267. mc.sequence = 0
  268. // Send CMD packet
  269. return mc.writePacket([]byte{
  270. // Add the packet header [24bit length + 1 byte sequence]
  271. 0x01, // 1 byte long
  272. 0x00,
  273. 0x00,
  274. 0x00, // mc.sequence
  275. // Add command byte
  276. command,
  277. })
  278. }
  279. func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error {
  280. // Reset Packet Sequence
  281. mc.sequence = 0
  282. pktLen := 1 + len(arg)
  283. data := make([]byte, pktLen+4)
  284. // Add the packet header [24bit length + 1 byte sequence]
  285. data[0] = byte(pktLen)
  286. data[1] = byte(pktLen >> 8)
  287. data[2] = byte(pktLen >> 16)
  288. //data[3] = mc.sequence
  289. // Add command byte
  290. data[4] = command
  291. // Add arg
  292. copy(data[5:], arg)
  293. // Send CMD packet
  294. return mc.writePacket(data)
  295. }
  296. func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error {
  297. // Reset Packet Sequence
  298. mc.sequence = 0
  299. // Send CMD packet
  300. return mc.writePacket([]byte{
  301. // Add the packet header [24bit length + 1 byte sequence]
  302. 0x05, // 5 bytes long
  303. 0x00,
  304. 0x00,
  305. 0x00, // mc.sequence
  306. // Add command byte
  307. command,
  308. // Add arg [32 bit]
  309. byte(arg),
  310. byte(arg >> 8),
  311. byte(arg >> 16),
  312. byte(arg >> 24),
  313. })
  314. }
  315. /******************************************************************************
  316. * Result Packets *
  317. ******************************************************************************/
  318. // Returns error if Packet is not an 'Result OK'-Packet
  319. func (mc *mysqlConn) readResultOK() error {
  320. data, err := mc.readPacket()
  321. if err == nil {
  322. // packet indicator
  323. switch data[0] {
  324. case iOK:
  325. return mc.handleOkPacket(data)
  326. case iEOF: // someone is using old_passwords
  327. return errOldPassword
  328. default: // Error otherwise
  329. return mc.handleErrorPacket(data)
  330. }
  331. }
  332. return err
  333. }
  334. // Result Set Header Packet
  335. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
  336. func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
  337. data, err := mc.readPacket()
  338. if err == nil {
  339. switch data[0] {
  340. case iOK:
  341. return 0, mc.handleOkPacket(data)
  342. case iERR:
  343. return 0, mc.handleErrorPacket(data)
  344. case iLocalInFile:
  345. return 0, mc.handleInFileRequest(string(data[1:]))
  346. }
  347. // column count
  348. num, _, n := readLengthEncodedInteger(data)
  349. if n-len(data) == 0 {
  350. return int(num), nil
  351. }
  352. return 0, errMalformPkt
  353. }
  354. return 0, err
  355. }
  356. // Error Packet
  357. // http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
  358. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  359. if data[0] != iERR {
  360. return errMalformPkt
  361. }
  362. // 0xff [1 byte]
  363. // Error Number [16 bit uint]
  364. errno := binary.LittleEndian.Uint16(data[1:3])
  365. pos := 3
  366. // SQL State [optional: # + 5bytes string]
  367. //sqlstate := string(data[pos : pos+6])
  368. if data[pos] == 0x23 {
  369. pos = 9
  370. }
  371. // Error Message [string]
  372. return &MySQLError{
  373. Number: errno,
  374. Message: string(data[pos:]),
  375. }
  376. }
  377. // Ok Packet
  378. // http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
  379. func (mc *mysqlConn) handleOkPacket(data []byte) (err error) {
  380. var n, m int
  381. // 0x00 [1 byte]
  382. // Affected rows [Length Coded Binary]
  383. mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
  384. // Insert id [Length Coded Binary]
  385. mc.insertId, _, m = readLengthEncodedInteger(data[1+n:])
  386. // server_status [2 bytes]
  387. // warning count [2 bytes]
  388. if !mc.strict {
  389. return
  390. } else {
  391. pos := 1 + n + m + 2
  392. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  393. err = mc.getWarnings()
  394. }
  395. }
  396. // message [until end of packet]
  397. return
  398. }
  399. // Read Packets as Field Packets until EOF-Packet or an Error appears
  400. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
  401. func (mc *mysqlConn) readColumns(count int) (columns []mysqlField, err error) {
  402. var data []byte
  403. var i, pos, n int
  404. var name []byte
  405. columns = make([]mysqlField, count)
  406. for {
  407. data, err = mc.readPacket()
  408. if err != nil {
  409. return
  410. }
  411. // EOF Packet
  412. if data[0] == iEOF && (len(data) == 5 || len(data) == 1) {
  413. if i != count {
  414. err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
  415. }
  416. return
  417. }
  418. // Catalog
  419. pos, err = skipLengthEnodedString(data)
  420. if err != nil {
  421. return
  422. }
  423. // Database [len coded string]
  424. n, err = skipLengthEnodedString(data[pos:])
  425. if err != nil {
  426. return
  427. }
  428. pos += n
  429. // Table [len coded string]
  430. n, err = skipLengthEnodedString(data[pos:])
  431. if err != nil {
  432. return
  433. }
  434. pos += n
  435. // Original table [len coded string]
  436. n, err = skipLengthEnodedString(data[pos:])
  437. if err != nil {
  438. return
  439. }
  440. pos += n
  441. // Name [len coded string]
  442. name, _, n, err = readLengthEnodedString(data[pos:])
  443. if err != nil {
  444. return
  445. }
  446. columns[i].name = string(name)
  447. pos += n
  448. // Original name [len coded string]
  449. n, err = skipLengthEnodedString(data[pos:])
  450. if err != nil {
  451. return
  452. }
  453. // Filler [1 byte]
  454. // Charset [16 bit uint]
  455. // Length [32 bit uint]
  456. pos += n + 1 + 2 + 4
  457. // Field type [byte]
  458. columns[i].fieldType = data[pos]
  459. pos++
  460. // Flags [16 bit uint]
  461. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  462. //pos += 2
  463. // Decimals [8 bit uint]
  464. //pos++
  465. // Default value [len coded binary]
  466. //if pos < len(data) {
  467. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  468. //}
  469. i++
  470. }
  471. }
  472. // Read Packets as Field Packets until EOF-Packet or an Error appears
  473. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
  474. func (rows *mysqlRows) readRow(dest []driver.Value) (err error) {
  475. data, err := rows.mc.readPacket()
  476. if err != nil {
  477. return
  478. }
  479. // EOF Packet
  480. if data[0] == iEOF && len(data) == 5 {
  481. return io.EOF
  482. }
  483. // RowSet Packet
  484. var n int
  485. var isNull bool
  486. pos := 0
  487. for i := range dest {
  488. // Read bytes and convert to string
  489. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  490. pos += n
  491. if err == nil {
  492. if !isNull {
  493. if !rows.mc.parseTime {
  494. continue
  495. } else {
  496. switch rows.columns[i].fieldType {
  497. case fieldTypeTimestamp, fieldTypeDateTime,
  498. fieldTypeDate, fieldTypeNewDate:
  499. dest[i], err = parseDateTime(string(dest[i].([]byte)), rows.mc.cfg.loc)
  500. if err == nil {
  501. continue
  502. }
  503. default:
  504. continue
  505. }
  506. }
  507. } else {
  508. dest[i] = nil
  509. continue
  510. }
  511. }
  512. return // err
  513. }
  514. return
  515. }
  516. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  517. func (mc *mysqlConn) readUntilEOF() (err error) {
  518. var data []byte
  519. for {
  520. data, err = mc.readPacket()
  521. // No Err and no EOF Packet
  522. if err == nil && data[0] != iEOF {
  523. continue
  524. }
  525. return // Err or EOF
  526. }
  527. }
  528. /******************************************************************************
  529. * Prepared Statements *
  530. ******************************************************************************/
  531. // Prepare Result Packets
  532. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  533. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  534. data, err := stmt.mc.readPacket()
  535. if err == nil {
  536. // Position
  537. pos := 0
  538. // packet indicator [1 byte]
  539. if data[pos] != iOK {
  540. err = stmt.mc.handleErrorPacket(data)
  541. return
  542. }
  543. pos++
  544. // statement id [4 bytes]
  545. stmt.id = binary.LittleEndian.Uint32(data[pos : pos+4])
  546. pos += 4
  547. // Column count [16 bit uint]
  548. columnCount = binary.LittleEndian.Uint16(data[pos : pos+2])
  549. pos += 2
  550. // Param count [16 bit uint]
  551. stmt.paramCount = int(binary.LittleEndian.Uint16(data[pos : pos+2]))
  552. pos += 2
  553. // Reserved [8 bit]
  554. pos++
  555. // Warning count [16 bit uint]
  556. if !stmt.mc.strict {
  557. return
  558. } else {
  559. // Check for warnings count > 0, only available in MySQL > 4.1
  560. if len(data) >= 12 && binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  561. err = stmt.mc.getWarnings()
  562. }
  563. }
  564. }
  565. return
  566. }
  567. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-send-long-data
  568. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) (err error) {
  569. maxLen := stmt.mc.maxPacketAllowed - 1
  570. pktLen := maxLen
  571. argLen := len(arg)
  572. data := make([]byte, 4+1+4+2+argLen)
  573. copy(data[4+1+4+2:], arg)
  574. for argLen > 0 {
  575. if 1+4+2+argLen < maxLen {
  576. pktLen = 1 + 4 + 2 + argLen
  577. }
  578. // Add the packet header [24bit length + 1 byte sequence]
  579. data[0] = byte(pktLen)
  580. data[1] = byte(pktLen >> 8)
  581. data[2] = byte(pktLen >> 16)
  582. data[3] = 0x00 // mc.sequence
  583. // Add command byte [1 byte]
  584. data[4] = comStmtSendLongData
  585. // Add stmtID [32 bit]
  586. data[5] = byte(stmt.id)
  587. data[6] = byte(stmt.id >> 8)
  588. data[7] = byte(stmt.id >> 16)
  589. data[8] = byte(stmt.id >> 24)
  590. // Add paramID [16 bit]
  591. data[9] = byte(paramID)
  592. data[10] = byte(paramID >> 8)
  593. // Send CMD packet
  594. err = stmt.mc.writePacket(data[:4+pktLen])
  595. if err == nil {
  596. argLen -= pktLen - (1 + 4 + 2)
  597. data = data[pktLen-(1+4+2):]
  598. continue
  599. }
  600. return err
  601. }
  602. // Reset Packet Sequence
  603. stmt.mc.sequence = 0
  604. return nil
  605. }
  606. // Execute Prepared Statement
  607. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-execute
  608. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  609. if len(args) != stmt.paramCount {
  610. return fmt.Errorf(
  611. "Arguments count mismatch (Got: %d Has: %d)",
  612. len(args),
  613. stmt.paramCount)
  614. }
  615. // Reset packet-sequence
  616. stmt.mc.sequence = 0
  617. pktLen := 1 + 4 + 1 + 4 + ((stmt.paramCount + 7) >> 3) + 1 + (stmt.paramCount << 1)
  618. paramValues := make([][]byte, stmt.paramCount)
  619. paramTypes := make([]byte, (stmt.paramCount << 1))
  620. bitMask := uint64(0)
  621. var i int
  622. for i = range args {
  623. // build NULL-bitmap
  624. if args[i] == nil {
  625. bitMask += 1 << uint(i)
  626. paramTypes[i<<1] = fieldTypeNULL
  627. continue
  628. }
  629. // cache types and values
  630. switch v := args[i].(type) {
  631. case int64:
  632. paramTypes[i<<1] = fieldTypeLongLong
  633. paramValues[i] = uint64ToBytes(uint64(v))
  634. pktLen += 8
  635. continue
  636. case float64:
  637. paramTypes[i<<1] = fieldTypeDouble
  638. paramValues[i] = uint64ToBytes(math.Float64bits(v))
  639. pktLen += 8
  640. continue
  641. case bool:
  642. paramTypes[i<<1] = fieldTypeTiny
  643. pktLen++
  644. if v {
  645. paramValues[i] = []byte{0x01}
  646. } else {
  647. paramValues[i] = []byte{0x00}
  648. }
  649. continue
  650. case []byte:
  651. paramTypes[i<<1] = fieldTypeString
  652. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  653. paramValues[i] = append(
  654. lengthEncodedIntegerToBytes(uint64(len(v))),
  655. v...,
  656. )
  657. pktLen += len(paramValues[i])
  658. continue
  659. } else {
  660. err := stmt.writeCommandLongData(i, v)
  661. if err == nil {
  662. continue
  663. }
  664. return err
  665. }
  666. case string:
  667. paramTypes[i<<1] = fieldTypeString
  668. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  669. paramValues[i] = append(
  670. lengthEncodedIntegerToBytes(uint64(len(v))),
  671. []byte(v)...,
  672. )
  673. pktLen += len(paramValues[i])
  674. continue
  675. } else {
  676. err := stmt.writeCommandLongData(i, []byte(v))
  677. if err == nil {
  678. continue
  679. }
  680. return err
  681. }
  682. case time.Time:
  683. paramTypes[i<<1] = fieldTypeString
  684. var val []byte
  685. if v.IsZero() {
  686. val = []byte("0000-00-00")
  687. } else {
  688. val = []byte(v.In(stmt.mc.cfg.loc).Format(timeFormat))
  689. }
  690. paramValues[i] = append(
  691. lengthEncodedIntegerToBytes(uint64(len(val))),
  692. val...,
  693. )
  694. pktLen += len(paramValues[i])
  695. continue
  696. default:
  697. return fmt.Errorf("Can't convert type: %T", args[i])
  698. }
  699. }
  700. data := make([]byte, pktLen+4)
  701. // packet header [4 bytes]
  702. data[0] = byte(pktLen)
  703. data[1] = byte(pktLen >> 8)
  704. data[2] = byte(pktLen >> 16)
  705. data[3] = stmt.mc.sequence
  706. // command [1 byte]
  707. data[4] = comStmtExecute
  708. // statement_id [4 bytes]
  709. data[5] = byte(stmt.id)
  710. data[6] = byte(stmt.id >> 8)
  711. data[7] = byte(stmt.id >> 16)
  712. data[8] = byte(stmt.id >> 24)
  713. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  714. //data[9] = 0x00
  715. // iteration_count (uint32(1)) [4 bytes]
  716. data[10] = 0x01
  717. //data[11] = 0x00
  718. //data[12] = 0x00
  719. //data[13] = 0x00
  720. if stmt.paramCount > 0 {
  721. // NULL-bitmap [(param_count+7)/8 bytes]
  722. pos := 14 + ((stmt.paramCount + 7) >> 3)
  723. // Convert bitMask to bytes
  724. for i = 14; i < pos; i++ {
  725. data[i] = byte(bitMask >> uint((i-14)<<3))
  726. }
  727. // newParameterBoundFlag 1 [1 byte]
  728. data[pos] = 0x01
  729. pos++
  730. // type of parameters [param_count*2 bytes]
  731. pos += copy(data[pos:], paramTypes)
  732. // values for the parameters [n bytes]
  733. for i = range paramValues {
  734. pos += copy(data[pos:], paramValues[i])
  735. }
  736. }
  737. return stmt.mc.writePacket(data)
  738. }
  739. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::ResultsetRow
  740. func (rows *mysqlRows) readBinaryRow(dest []driver.Value) (err error) {
  741. data, err := rows.mc.readPacket()
  742. if err != nil {
  743. return
  744. }
  745. // packet indicator [1 byte]
  746. if data[0] != iOK {
  747. // EOF Packet
  748. if data[0] == iEOF && len(data) == 5 {
  749. return io.EOF
  750. } else {
  751. // Error otherwise
  752. return rows.mc.handleErrorPacket(data)
  753. }
  754. }
  755. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  756. pos := 1 + (len(dest)+7+2)>>3
  757. nullBitMap := data[1:pos]
  758. // values [rest]
  759. var n int
  760. var unsigned bool
  761. for i := range dest {
  762. // Field is NULL
  763. // (byte >> bit-pos) % 2 == 1
  764. if ((nullBitMap[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  765. dest[i] = nil
  766. continue
  767. }
  768. unsigned = rows.columns[i].flags&flagUnsigned != 0
  769. // Convert to byte-coded string
  770. switch rows.columns[i].fieldType {
  771. case fieldTypeNULL:
  772. dest[i] = nil
  773. continue
  774. // Numeric Types
  775. case fieldTypeTiny:
  776. if unsigned {
  777. dest[i] = int64(data[pos])
  778. } else {
  779. dest[i] = int64(int8(data[pos]))
  780. }
  781. pos++
  782. continue
  783. case fieldTypeShort, fieldTypeYear:
  784. if unsigned {
  785. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  786. } else {
  787. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  788. }
  789. pos += 2
  790. continue
  791. case fieldTypeInt24, fieldTypeLong:
  792. if unsigned {
  793. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  794. } else {
  795. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  796. }
  797. pos += 4
  798. continue
  799. case fieldTypeLongLong:
  800. if unsigned {
  801. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  802. if val > math.MaxInt64 {
  803. dest[i] = uint64ToString(val)
  804. } else {
  805. dest[i] = int64(val)
  806. }
  807. } else {
  808. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  809. }
  810. pos += 8
  811. continue
  812. case fieldTypeFloat:
  813. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  814. pos += 4
  815. continue
  816. case fieldTypeDouble:
  817. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  818. pos += 8
  819. continue
  820. // Length coded Binary Strings
  821. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  822. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  823. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  824. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  825. var isNull bool
  826. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  827. pos += n
  828. if err == nil {
  829. if !isNull {
  830. continue
  831. } else {
  832. dest[i] = nil
  833. continue
  834. }
  835. }
  836. return // err
  837. // Date YYYY-MM-DD
  838. case fieldTypeDate, fieldTypeNewDate:
  839. var num uint64
  840. var isNull bool
  841. num, isNull, n = readLengthEncodedInteger(data[pos:])
  842. pos += n
  843. if isNull {
  844. dest[i] = nil
  845. continue
  846. }
  847. if rows.mc.parseTime {
  848. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  849. } else {
  850. dest[i], err = formatBinaryDate(num, data[pos:])
  851. }
  852. if err == nil {
  853. pos += int(num)
  854. continue
  855. } else {
  856. return err
  857. }
  858. // Time [-][H]HH:MM:SS[.fractal]
  859. case fieldTypeTime:
  860. var num uint64
  861. var isNull bool
  862. num, isNull, n = readLengthEncodedInteger(data[pos:])
  863. pos += n
  864. if num == 0 {
  865. if isNull {
  866. dest[i] = nil
  867. continue
  868. } else {
  869. dest[i] = []byte("00:00:00")
  870. continue
  871. }
  872. }
  873. var sign byte
  874. if data[pos] == 1 {
  875. sign = byte('-')
  876. }
  877. switch num {
  878. case 8:
  879. dest[i] = []byte(fmt.Sprintf(
  880. "%c%02d:%02d:%02d",
  881. sign,
  882. uint16(data[pos+1])*24+uint16(data[pos+5]),
  883. data[pos+6],
  884. data[pos+7],
  885. ))
  886. pos += 8
  887. continue
  888. case 12:
  889. dest[i] = []byte(fmt.Sprintf(
  890. "%c%02d:%02d:%02d.%06d",
  891. sign,
  892. uint16(data[pos+1])*24+uint16(data[pos+5]),
  893. data[pos+6],
  894. data[pos+7],
  895. binary.LittleEndian.Uint32(data[pos+8:pos+12]),
  896. ))
  897. pos += 12
  898. continue
  899. default:
  900. return fmt.Errorf("Invalid TIME-packet length %d", num)
  901. }
  902. // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  903. case fieldTypeTimestamp, fieldTypeDateTime:
  904. var num uint64
  905. var isNull bool
  906. num, isNull, n = readLengthEncodedInteger(data[pos:])
  907. pos += n
  908. if isNull {
  909. dest[i] = nil
  910. continue
  911. }
  912. if rows.mc.parseTime {
  913. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  914. } else {
  915. dest[i], err = formatBinaryDateTime(num, data[pos:])
  916. }
  917. if err == nil {
  918. pos += int(num)
  919. continue
  920. } else {
  921. return err
  922. }
  923. // Please report if this happens!
  924. default:
  925. return fmt.Errorf("Unknown FieldType %d", rows.columns[i].fieldType)
  926. }
  927. }
  928. return
  929. }