packets.go 21 KB

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