packets.go 23 KB

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