packets.go 24 KB

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