packets.go 24 KB

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