packets.go 24 KB

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