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