packets.go 23 KB

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