packets.go 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. return mc.handleOkPacket(data)
  294. case iEOF: // someone is using old_passwords
  295. return errOldPassword
  296. default: // Error otherwise
  297. return mc.handleErrorPacket(data)
  298. }
  299. }
  300. return err
  301. }
  302. // Result Set Header Packet
  303. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
  304. func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
  305. data, err := mc.readPacket()
  306. if err == nil {
  307. switch data[0] {
  308. case iOK:
  309. return 0, mc.handleOkPacket(data)
  310. case iERR:
  311. return 0, mc.handleErrorPacket(data)
  312. case iLocalInFile:
  313. return 0, mc.handleInFileRequest(string(data[1:]))
  314. }
  315. // column count
  316. num, _, n := readLengthEncodedInteger(data)
  317. if n-len(data) == 0 {
  318. return int(num), nil
  319. }
  320. return 0, errMalformPkt
  321. }
  322. return 0, err
  323. }
  324. // Error Packet
  325. // http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
  326. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  327. if data[0] != iERR {
  328. return errMalformPkt
  329. }
  330. // 0xff [1 byte]
  331. // Error Number [16 bit uint]
  332. errno := binary.LittleEndian.Uint16(data[1:3])
  333. pos := 3
  334. // SQL State [optional: # + 5bytes string]
  335. //sqlstate := string(data[pos : pos+6])
  336. if data[pos] == 0x23 {
  337. pos = 9
  338. }
  339. // Error Message [string]
  340. return &MySQLError{
  341. Number: errno,
  342. Message: string(data[pos:]),
  343. }
  344. }
  345. // Ok Packet
  346. // http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
  347. func (mc *mysqlConn) handleOkPacket(data []byte) (err error) {
  348. var n, m int
  349. // 0x00 [1 byte]
  350. // Affected rows [Length Coded Binary]
  351. mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
  352. // Insert id [Length Coded Binary]
  353. mc.insertId, _, m = readLengthEncodedInteger(data[1+n:])
  354. // server_status [2 bytes]
  355. // warning count [2 bytes]
  356. if !mc.strict {
  357. return
  358. } else {
  359. pos := 1 + n + m + 2
  360. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  361. err = mc.getWarnings()
  362. }
  363. }
  364. // message [until end of packet]
  365. return
  366. }
  367. // Read Packets as Field Packets until EOF-Packet or an Error appears
  368. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
  369. func (mc *mysqlConn) readColumns(count int) (columns []mysqlField, err error) {
  370. var data []byte
  371. var i, pos, n int
  372. var name []byte
  373. columns = make([]mysqlField, count)
  374. for {
  375. data, err = mc.readPacket()
  376. if err != nil {
  377. return
  378. }
  379. // EOF Packet
  380. if data[0] == iEOF && len(data) == 5 {
  381. if i != count {
  382. err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
  383. }
  384. return
  385. }
  386. // Catalog
  387. pos, err = skipLengthEnodedString(data)
  388. if err != nil {
  389. return
  390. }
  391. // Database [len coded string]
  392. n, err = skipLengthEnodedString(data[pos:])
  393. if err != nil {
  394. return
  395. }
  396. pos += n
  397. // Table [len coded string]
  398. n, err = skipLengthEnodedString(data[pos:])
  399. if err != nil {
  400. return
  401. }
  402. pos += n
  403. // Original table [len coded string]
  404. n, err = skipLengthEnodedString(data[pos:])
  405. if err != nil {
  406. return
  407. }
  408. pos += n
  409. // Name [len coded string]
  410. name, _, n, err = readLengthEnodedString(data[pos:])
  411. if err != nil {
  412. return
  413. }
  414. columns[i].name = string(name)
  415. pos += n
  416. // Original name [len coded string]
  417. n, err = skipLengthEnodedString(data[pos:])
  418. if err != nil {
  419. return
  420. }
  421. // Filler [1 byte]
  422. // Charset [16 bit uint]
  423. // Length [32 bit uint]
  424. pos += n + 1 + 2 + 4
  425. // Field type [byte]
  426. columns[i].fieldType = data[pos]
  427. pos++
  428. // Flags [16 bit uint]
  429. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  430. //pos += 2
  431. // Decimals [8 bit uint]
  432. //pos++
  433. // Default value [len coded binary]
  434. //if pos < len(data) {
  435. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  436. //}
  437. i++
  438. }
  439. return
  440. }
  441. // Read Packets as Field Packets until EOF-Packet or an Error appears
  442. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
  443. func (rows *mysqlRows) readRow(dest []driver.Value) (err error) {
  444. data, err := rows.mc.readPacket()
  445. if err != nil {
  446. return
  447. }
  448. // EOF Packet
  449. if data[0] == iEOF && len(data) == 5 {
  450. return io.EOF
  451. }
  452. // RowSet Packet
  453. var n int
  454. var isNull bool
  455. pos := 0
  456. for i := range dest {
  457. // Read bytes and convert to string
  458. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  459. pos += n
  460. if err == nil {
  461. if !isNull {
  462. if !rows.mc.parseTime {
  463. continue
  464. } else {
  465. switch rows.columns[i].fieldType {
  466. case fieldTypeTimestamp, fieldTypeDateTime,
  467. fieldTypeDate, fieldTypeNewDate:
  468. dest[i], err = parseDateTime(string(dest[i].([]byte)), rows.mc.cfg.loc)
  469. if err == nil {
  470. continue
  471. }
  472. default:
  473. continue
  474. }
  475. }
  476. } else {
  477. dest[i] = nil
  478. continue
  479. }
  480. }
  481. return // err
  482. }
  483. return
  484. }
  485. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  486. func (mc *mysqlConn) readUntilEOF() (err error) {
  487. var data []byte
  488. for {
  489. data, err = mc.readPacket()
  490. // No Err and no EOF Packet
  491. if err == nil && (data[0] != iEOF || len(data) != 5) {
  492. continue
  493. }
  494. return // Err or EOF
  495. }
  496. return
  497. }
  498. /******************************************************************************
  499. * Prepared Statements *
  500. ******************************************************************************/
  501. // Prepare Result Packets
  502. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  503. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  504. data, err := stmt.mc.readPacket()
  505. if err == nil {
  506. // Position
  507. pos := 0
  508. // packet indicator [1 byte]
  509. if data[pos] != iOK {
  510. err = stmt.mc.handleErrorPacket(data)
  511. return
  512. }
  513. pos++
  514. // statement id [4 bytes]
  515. stmt.id = binary.LittleEndian.Uint32(data[pos : pos+4])
  516. pos += 4
  517. // Column count [16 bit uint]
  518. columnCount = binary.LittleEndian.Uint16(data[pos : pos+2])
  519. pos += 2
  520. // Param count [16 bit uint]
  521. stmt.paramCount = int(binary.LittleEndian.Uint16(data[pos : pos+2]))
  522. pos += 2
  523. // Warning count [16 bit uint]
  524. if !stmt.mc.strict {
  525. return
  526. } else {
  527. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  528. err = stmt.mc.getWarnings()
  529. }
  530. }
  531. }
  532. return
  533. }
  534. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-send-long-data
  535. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) (err error) {
  536. maxLen := stmt.mc.maxPacketAllowed - 1
  537. pktLen := maxLen
  538. argLen := len(arg)
  539. data := make([]byte, 4+1+4+2+argLen)
  540. copy(data[4+1+4+2:], arg)
  541. for argLen > 0 {
  542. if 1+4+2+argLen < maxLen {
  543. pktLen = 1 + 4 + 2 + argLen
  544. }
  545. // Add the packet header [24bit length + 1 byte sequence]
  546. data[0] = byte(pktLen)
  547. data[1] = byte(pktLen >> 8)
  548. data[2] = byte(pktLen >> 16)
  549. data[3] = 0x00 // mc.sequence
  550. // Add command byte [1 byte]
  551. data[4] = comStmtSendLongData
  552. // Add stmtID [32 bit]
  553. data[5] = byte(stmt.id)
  554. data[6] = byte(stmt.id >> 8)
  555. data[7] = byte(stmt.id >> 16)
  556. data[8] = byte(stmt.id >> 24)
  557. // Add paramID [16 bit]
  558. data[9] = byte(paramID)
  559. data[10] = byte(paramID >> 8)
  560. // Send CMD packet
  561. err = stmt.mc.writePacket(data[:4+pktLen])
  562. if err == nil {
  563. argLen -= pktLen - (1 + 4 + 2)
  564. data = data[pktLen-(1+4+2):]
  565. continue
  566. }
  567. return err
  568. }
  569. // Reset Packet Sequence
  570. stmt.mc.sequence = 0
  571. return nil
  572. }
  573. // Execute Prepared Statement
  574. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-execute
  575. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  576. if len(args) != stmt.paramCount {
  577. return fmt.Errorf(
  578. "Arguments count mismatch (Got: %d Has: %d",
  579. len(args),
  580. stmt.paramCount)
  581. }
  582. // Reset packet-sequence
  583. stmt.mc.sequence = 0
  584. pktLen := 1 + 4 + 1 + 4 + ((stmt.paramCount + 7) >> 3) + 1 + (stmt.paramCount << 1)
  585. paramValues := make([][]byte, stmt.paramCount)
  586. paramTypes := make([]byte, (stmt.paramCount << 1))
  587. bitMask := uint64(0)
  588. var i int
  589. for i = range args {
  590. // build NULL-bitmap
  591. if args[i] == nil {
  592. bitMask += 1 << uint(i)
  593. paramTypes[i<<1] = fieldTypeNULL
  594. continue
  595. }
  596. // cache types and values
  597. switch v := args[i].(type) {
  598. case int64:
  599. paramTypes[i<<1] = fieldTypeLongLong
  600. paramValues[i] = uint64ToBytes(uint64(v))
  601. pktLen += 8
  602. continue
  603. case float64:
  604. paramTypes[i<<1] = fieldTypeDouble
  605. paramValues[i] = uint64ToBytes(math.Float64bits(v))
  606. pktLen += 8
  607. continue
  608. case bool:
  609. paramTypes[i<<1] = fieldTypeTiny
  610. pktLen++
  611. if v {
  612. paramValues[i] = []byte{0x01}
  613. } else {
  614. paramValues[i] = []byte{0x00}
  615. }
  616. continue
  617. case []byte:
  618. paramTypes[i<<1] = fieldTypeString
  619. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  620. paramValues[i] = append(
  621. lengthEncodedIntegerToBytes(uint64(len(v))),
  622. v...,
  623. )
  624. pktLen += len(paramValues[i])
  625. continue
  626. } else {
  627. err := stmt.writeCommandLongData(i, v)
  628. if err == nil {
  629. continue
  630. }
  631. return err
  632. }
  633. case string:
  634. paramTypes[i<<1] = fieldTypeString
  635. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  636. paramValues[i] = append(
  637. lengthEncodedIntegerToBytes(uint64(len(v))),
  638. []byte(v)...,
  639. )
  640. pktLen += len(paramValues[i])
  641. continue
  642. } else {
  643. err := stmt.writeCommandLongData(i, []byte(v))
  644. if err == nil {
  645. continue
  646. }
  647. return err
  648. }
  649. case time.Time:
  650. paramTypes[i<<1] = fieldTypeString
  651. var val []byte
  652. if v.IsZero() {
  653. val = []byte("0000-00-00")
  654. } else {
  655. val = []byte(v.Format(timeFormat))
  656. }
  657. paramValues[i] = append(
  658. lengthEncodedIntegerToBytes(uint64(len(val))),
  659. val...,
  660. )
  661. pktLen += len(paramValues[i])
  662. continue
  663. default:
  664. return fmt.Errorf("Can't convert type: %T", args[i])
  665. }
  666. }
  667. data := make([]byte, pktLen+4)
  668. // packet header [4 bytes]
  669. data[0] = byte(pktLen)
  670. data[1] = byte(pktLen >> 8)
  671. data[2] = byte(pktLen >> 16)
  672. data[3] = stmt.mc.sequence
  673. // command [1 byte]
  674. data[4] = comStmtExecute
  675. // statement_id [4 bytes]
  676. data[5] = byte(stmt.id)
  677. data[6] = byte(stmt.id >> 8)
  678. data[7] = byte(stmt.id >> 16)
  679. data[8] = byte(stmt.id >> 24)
  680. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  681. //data[9] = 0x00
  682. // iteration_count (uint32(1)) [4 bytes]
  683. data[10] = 0x01
  684. //data[11] = 0x00
  685. //data[12] = 0x00
  686. //data[13] = 0x00
  687. if stmt.paramCount > 0 {
  688. // NULL-bitmap [(param_count+7)/8 bytes]
  689. pos := 14 + ((stmt.paramCount + 7) >> 3)
  690. // Convert bitMask to bytes
  691. for i = 14; i < pos; i++ {
  692. data[i] = byte(bitMask >> uint((i-14)<<3))
  693. }
  694. // newParameterBoundFlag 1 [1 byte]
  695. data[pos] = 0x01
  696. pos++
  697. // type of parameters [param_count*2 bytes]
  698. pos += copy(data[pos:], paramTypes)
  699. // values for the parameters [n bytes]
  700. for i = range paramValues {
  701. pos += copy(data[pos:], paramValues[i])
  702. }
  703. }
  704. return stmt.mc.writePacket(data)
  705. }
  706. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::ResultsetRow
  707. func (rows *mysqlRows) readBinaryRow(dest []driver.Value) (err error) {
  708. data, err := rows.mc.readPacket()
  709. if err != nil {
  710. return
  711. }
  712. // packet indicator [1 byte]
  713. if data[0] != iOK {
  714. // EOF Packet
  715. if data[0] == iEOF && len(data) == 5 {
  716. return io.EOF
  717. } else {
  718. // Error otherwise
  719. return rows.mc.handleErrorPacket(data)
  720. }
  721. }
  722. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  723. pos := 1 + (len(dest)+7+2)>>3
  724. nullBitMap := data[1:pos]
  725. // values [rest]
  726. var n int
  727. var unsigned bool
  728. for i := range dest {
  729. // Field is NULL
  730. // (byte >> bit-pos) % 2 == 1
  731. if ((nullBitMap[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  732. dest[i] = nil
  733. continue
  734. }
  735. unsigned = rows.columns[i].flags&flagUnsigned != 0
  736. // Convert to byte-coded string
  737. switch rows.columns[i].fieldType {
  738. case fieldTypeNULL:
  739. dest[i] = nil
  740. continue
  741. // Numeric Types
  742. case fieldTypeTiny:
  743. if unsigned {
  744. dest[i] = int64(data[pos])
  745. } else {
  746. dest[i] = int64(int8(data[pos]))
  747. }
  748. pos++
  749. continue
  750. case fieldTypeShort, fieldTypeYear:
  751. if unsigned {
  752. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  753. } else {
  754. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  755. }
  756. pos += 2
  757. continue
  758. case fieldTypeInt24, fieldTypeLong:
  759. if unsigned {
  760. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  761. } else {
  762. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  763. }
  764. pos += 4
  765. continue
  766. case fieldTypeLongLong:
  767. if unsigned {
  768. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  769. if val > math.MaxInt64 {
  770. dest[i] = uint64ToString(val)
  771. } else {
  772. dest[i] = int64(val)
  773. }
  774. } else {
  775. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  776. }
  777. pos += 8
  778. continue
  779. case fieldTypeFloat:
  780. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  781. pos += 4
  782. continue
  783. case fieldTypeDouble:
  784. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  785. pos += 8
  786. continue
  787. // Length coded Binary Strings
  788. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  789. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  790. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  791. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  792. var isNull bool
  793. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  794. pos += n
  795. if err == nil {
  796. if !isNull {
  797. continue
  798. } else {
  799. dest[i] = nil
  800. continue
  801. }
  802. }
  803. return // err
  804. // Date YYYY-MM-DD
  805. case fieldTypeDate, fieldTypeNewDate:
  806. var num uint64
  807. var isNull bool
  808. num, isNull, n = readLengthEncodedInteger(data[pos:])
  809. pos += n
  810. if isNull {
  811. dest[i] = nil
  812. continue
  813. }
  814. if rows.mc.parseTime {
  815. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  816. } else {
  817. dest[i], err = formatBinaryDate(num, data[pos:])
  818. }
  819. if err == nil {
  820. pos += int(num)
  821. continue
  822. } else {
  823. return err
  824. }
  825. // Time [-][H]HH:MM:SS[.fractal]
  826. case fieldTypeTime:
  827. var num uint64
  828. var isNull bool
  829. num, isNull, n = readLengthEncodedInteger(data[pos:])
  830. pos += n
  831. if num == 0 {
  832. if isNull {
  833. dest[i] = nil
  834. continue
  835. } else {
  836. dest[i] = []byte("00:00:00")
  837. continue
  838. }
  839. }
  840. var sign byte
  841. if data[pos] == 1 {
  842. sign = byte('-')
  843. }
  844. switch num {
  845. case 8:
  846. dest[i] = []byte(fmt.Sprintf(
  847. "%c%02d:%02d:%02d",
  848. sign,
  849. uint16(data[pos+1])*24+uint16(data[pos+5]),
  850. data[pos+6],
  851. data[pos+7],
  852. ))
  853. pos += 8
  854. continue
  855. case 12:
  856. dest[i] = []byte(fmt.Sprintf(
  857. "%c%02d:%02d:%02d.%06d",
  858. sign,
  859. uint16(data[pos+1])*24+uint16(data[pos+5]),
  860. data[pos+6],
  861. data[pos+7],
  862. binary.LittleEndian.Uint32(data[pos+8:pos+12]),
  863. ))
  864. pos += 12
  865. continue
  866. default:
  867. return fmt.Errorf("Invalid TIME-packet length %d", num)
  868. }
  869. // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  870. case fieldTypeTimestamp, fieldTypeDateTime:
  871. var num uint64
  872. var isNull bool
  873. num, isNull, n = readLengthEncodedInteger(data[pos:])
  874. pos += n
  875. if isNull {
  876. dest[i] = nil
  877. continue
  878. }
  879. if rows.mc.parseTime {
  880. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  881. } else {
  882. dest[i], err = formatBinaryDateTime(num, data[pos:])
  883. }
  884. if err == nil {
  885. pos += int(num)
  886. continue
  887. } else {
  888. return err
  889. }
  890. // Please report if this happens!
  891. default:
  892. return fmt.Errorf("Unknown FieldType %d", rows.columns[i].fieldType)
  893. }
  894. }
  895. return
  896. }