packets.go 23 KB

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