packets.go 21 KB

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