packets.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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] == iERR {
  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. // packet indicator
  245. switch data[0] {
  246. case iOK:
  247. mc.handleOkPacket(data)
  248. return nil
  249. case iEOF: // someone is using old_passwords
  250. return errOldPassword
  251. default: // ERROR otherwise
  252. return mc.handleErrorPacket(data)
  253. }
  254. }
  255. return err
  256. }
  257. // Result Set Header Packet
  258. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
  259. func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
  260. data, err := mc.readPacket()
  261. if err == nil {
  262. if data[0] == iOK {
  263. mc.handleOkPacket(data)
  264. return 0, nil
  265. } else if data[0] == iERR {
  266. return 0, mc.handleErrorPacket(data)
  267. }
  268. // column count
  269. num, _, n := readLengthEncodedInteger(data)
  270. if n-len(data) == 0 {
  271. return int(num), nil
  272. }
  273. return 0, errMalformPkt
  274. }
  275. return 0, err
  276. }
  277. // Error Packet
  278. // http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
  279. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  280. if data[0] != iERR {
  281. return errMalformPkt
  282. }
  283. // 0xff [1 byte]
  284. // Error Number [16 bit uint]
  285. errno := binary.LittleEndian.Uint16(data[1:3])
  286. pos := 3
  287. // SQL State [optional: # + 5bytes string]
  288. //sqlstate := string(data[pos : pos+6])
  289. if data[pos] == 0x23 {
  290. pos = 9
  291. }
  292. // Error Message [string]
  293. return fmt.Errorf("Error %d: %s", errno, string(data[pos:]))
  294. }
  295. // Ok Packet
  296. // http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
  297. func (mc *mysqlConn) handleOkPacket(data []byte) {
  298. var n int
  299. // 0x00 [1 byte]
  300. // Affected rows [Length Coded Binary]
  301. mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
  302. // Insert id [Length Coded Binary]
  303. mc.insertId, _, _ = readLengthEncodedInteger(data[1+n:])
  304. // server_status [2 bytes]
  305. // warning count [2 bytes]
  306. // message [until end of packet]
  307. }
  308. // Read Packets as Field Packets until EOF-Packet or an Error appears
  309. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
  310. func (mc *mysqlConn) readColumns(count int) (columns []mysqlField, err error) {
  311. var data []byte
  312. var i, pos, n int
  313. var name []byte
  314. columns = make([]mysqlField, count)
  315. for {
  316. data, err = mc.readPacket()
  317. if err != nil {
  318. return
  319. }
  320. // EOF Packet
  321. if data[0] == iEOF && len(data) == 5 {
  322. if i != count {
  323. err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
  324. }
  325. return
  326. }
  327. // Catalog
  328. pos, err = skipLengthEnodedString(data)
  329. if err != nil {
  330. return
  331. }
  332. // Database [len coded string]
  333. n, err = skipLengthEnodedString(data[pos:])
  334. if err != nil {
  335. return
  336. }
  337. pos += n
  338. // Table [len coded string]
  339. n, err = skipLengthEnodedString(data[pos:])
  340. if err != nil {
  341. return
  342. }
  343. pos += n
  344. // Original table [len coded string]
  345. n, err = skipLengthEnodedString(data[pos:])
  346. if err != nil {
  347. return
  348. }
  349. pos += n
  350. // Name [len coded string]
  351. name, _, n, err = readLengthEnodedString(data[pos:])
  352. if err != nil {
  353. return
  354. }
  355. columns[i].name = string(name)
  356. pos += n
  357. // Original name [len coded string]
  358. n, err = skipLengthEnodedString(data[pos:])
  359. if err != nil {
  360. return
  361. }
  362. // Filler [1 byte]
  363. // Charset [16 bit uint]
  364. // Length [32 bit uint]
  365. pos += n + 1 + 2 + 4
  366. // Field type [byte]
  367. columns[i].fieldType = data[pos]
  368. pos++
  369. // Flags [16 bit uint]
  370. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  371. //pos += 2
  372. // Decimals [8 bit uint]
  373. //pos++
  374. // Default value [len coded binary]
  375. //if pos < len(data) {
  376. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  377. //}
  378. i++
  379. }
  380. return
  381. }
  382. // Read Packets as Field Packets until EOF-Packet or an Error appears
  383. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
  384. func (rows *mysqlRows) readRow(dest []driver.Value) (err error) {
  385. data, err := rows.mc.readPacket()
  386. if err != nil {
  387. return
  388. }
  389. // EOF Packet
  390. if data[0] == iEOF && len(data) == 5 {
  391. return io.EOF
  392. }
  393. // RowSet Packet
  394. var n int
  395. var isNull bool
  396. pos := 0
  397. for i := range dest {
  398. // Read bytes and convert to string
  399. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  400. pos += n
  401. if err == nil {
  402. if !isNull {
  403. continue
  404. } else {
  405. dest[i] = nil
  406. continue
  407. }
  408. }
  409. return // err
  410. }
  411. return
  412. }
  413. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  414. func (mc *mysqlConn) readUntilEOF() (err error) {
  415. var data []byte
  416. for {
  417. data, err = mc.readPacket()
  418. // No Err and no EOF Packet
  419. if err == nil && (data[0] != iEOF || len(data) != 5) {
  420. continue
  421. }
  422. return // Err or EOF
  423. }
  424. return
  425. }
  426. /******************************************************************************
  427. * Prepared Statements *
  428. ******************************************************************************/
  429. // Prepare Result Packets
  430. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  431. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  432. data, err := stmt.mc.readPacket()
  433. if err == nil {
  434. // Position
  435. pos := 0
  436. // packet indicator [1 byte]
  437. if data[pos] != iOK {
  438. err = stmt.mc.handleErrorPacket(data)
  439. return
  440. }
  441. pos++
  442. // statement id [4 bytes]
  443. stmt.id = binary.LittleEndian.Uint32(data[pos : pos+4])
  444. pos += 4
  445. // Column count [16 bit uint]
  446. columnCount = binary.LittleEndian.Uint16(data[pos : pos+2])
  447. pos += 2
  448. // Param count [16 bit uint]
  449. stmt.paramCount = int(binary.LittleEndian.Uint16(data[pos : pos+2]))
  450. pos += 2
  451. // Warning count [16 bit uint]
  452. // bytesToUint16(data[pos : pos+2])
  453. }
  454. return
  455. }
  456. // Execute Prepared Statement
  457. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-execute
  458. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  459. if len(args) != stmt.paramCount {
  460. return fmt.Errorf(
  461. "Arguments count mismatch (Got: %d Has: %d",
  462. len(args),
  463. stmt.paramCount)
  464. }
  465. // Reset packet-sequence
  466. stmt.mc.sequence = 0
  467. pktLen := 1 + 4 + 1 + 4 + ((stmt.paramCount + 7) >> 3) + 1 + (stmt.paramCount << 1)
  468. paramValues := make([][]byte, stmt.paramCount)
  469. paramTypes := make([]byte, (stmt.paramCount << 1))
  470. bitMask := uint64(0)
  471. var i int
  472. for i = range args {
  473. // build NULL-bitmap
  474. if args[i] == nil {
  475. bitMask += 1 << uint(i)
  476. paramTypes[i<<1] = fieldTypeNULL
  477. continue
  478. }
  479. // cache types and values
  480. switch v := args[i].(type) {
  481. case int64:
  482. paramTypes[i<<1] = fieldTypeLongLong
  483. paramValues[i] = uint64ToBytes(uint64(v))
  484. pktLen += 8
  485. continue
  486. case float64:
  487. paramTypes[i<<1] = fieldTypeDouble
  488. paramValues[i] = uint64ToBytes(math.Float64bits(v))
  489. pktLen += 8
  490. continue
  491. case bool:
  492. paramTypes[i<<1] = fieldTypeTiny
  493. pktLen++
  494. if v {
  495. paramValues[i] = []byte{0x01}
  496. } else {
  497. paramValues[i] = []byte{0x00}
  498. }
  499. continue
  500. case []byte:
  501. paramTypes[i<<1] = fieldTypeString
  502. paramValues[i] = append(
  503. lengthEncodedIntegerToBytes(uint64(len(v))),
  504. v...,
  505. )
  506. pktLen += len(paramValues[i])
  507. continue
  508. case string:
  509. paramTypes[i<<1] = fieldTypeString
  510. paramValues[i] = append(
  511. lengthEncodedIntegerToBytes(uint64(len(v))),
  512. []byte(v)...,
  513. )
  514. pktLen += len(paramValues[i])
  515. continue
  516. case time.Time:
  517. paramTypes[i<<1] = fieldTypeString
  518. val := []byte(v.Format(timeFormat))
  519. paramValues[i] = append(
  520. lengthEncodedIntegerToBytes(uint64(len(val))),
  521. val...,
  522. )
  523. pktLen += len(paramValues[i])
  524. continue
  525. default:
  526. return fmt.Errorf("Can't convert type: %T", args[i])
  527. }
  528. }
  529. data := make([]byte, pktLen+4)
  530. // packet header [4 bytes]
  531. data[0] = byte(pktLen)
  532. data[1] = byte(pktLen >> 8)
  533. data[2] = byte(pktLen >> 16)
  534. data[3] = stmt.mc.sequence
  535. // command [1 byte]
  536. data[4] = byte(comStmtExecute)
  537. // statement_id [4 bytes]
  538. data[5] = byte(stmt.id)
  539. data[6] = byte(stmt.id >> 8)
  540. data[7] = byte(stmt.id >> 16)
  541. data[8] = byte(stmt.id >> 24)
  542. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  543. //data[9] = 0x00
  544. // iteration_count (uint32(1)) [4 bytes]
  545. data[10] = 0x01
  546. //data[11] = 0x00
  547. //data[12] = 0x00
  548. //data[13] = 0x00
  549. if stmt.paramCount > 0 {
  550. // NULL-bitmap [(param_count+7)/8 bytes]
  551. pos := 14 + ((stmt.paramCount + 7) >> 3)
  552. // Convert bitMask to bytes
  553. for i = 14; i < pos; i++ {
  554. data[i] = byte(bitMask >> uint(i<<3))
  555. }
  556. // newParameterBoundFlag 1 [1 byte]
  557. data[pos] = 0x01
  558. pos++
  559. // type of parameters [param_count*2 byte]
  560. pos += copy(data[pos:], paramTypes)
  561. // values for the parameters [n byte]
  562. for i = range paramValues {
  563. pos += copy(data[pos:], paramValues[i])
  564. }
  565. }
  566. return stmt.mc.writePacket(data)
  567. }
  568. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::ResultsetRow
  569. func (rc *mysqlRows) readBinaryRow(dest []driver.Value) (err error) {
  570. data, err := rc.mc.readPacket()
  571. if err != nil {
  572. return
  573. }
  574. // packet indicator [1 byte]
  575. if data[0] != iOK {
  576. // EOF Packet
  577. if data[0] == iEOF && len(data) == 5 {
  578. return io.EOF
  579. } else {
  580. // Error otherwise
  581. return rc.mc.handleErrorPacket(data)
  582. }
  583. }
  584. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  585. pos := 1 + (len(dest)+7+2)>>3
  586. nullBitMap := data[1:pos]
  587. // values [rest]
  588. var n int
  589. var unsigned bool
  590. for i := range dest {
  591. // Field is NULL
  592. // (byte >> bit-pos) % 2 == 1
  593. if ((nullBitMap[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  594. dest[i] = nil
  595. continue
  596. }
  597. unsigned = rc.columns[i].flags&flagUnsigned != 0
  598. // Convert to byte-coded string
  599. switch rc.columns[i].fieldType {
  600. case fieldTypeNULL:
  601. dest[i] = nil
  602. continue
  603. // Numeric Typs
  604. case fieldTypeTiny:
  605. if unsigned {
  606. dest[i] = int64(data[pos])
  607. } else {
  608. dest[i] = int64(int8(data[pos]))
  609. }
  610. pos++
  611. continue
  612. case fieldTypeShort, fieldTypeYear:
  613. if unsigned {
  614. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  615. } else {
  616. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  617. }
  618. pos += 2
  619. continue
  620. case fieldTypeInt24, fieldTypeLong:
  621. if unsigned {
  622. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  623. } else {
  624. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  625. }
  626. pos += 4
  627. continue
  628. case fieldTypeLongLong:
  629. if unsigned {
  630. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  631. if val > math.MaxInt64 {
  632. dest[i] = uint64ToString(val)
  633. } else {
  634. dest[i] = int64(val)
  635. }
  636. } else {
  637. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  638. }
  639. pos += 8
  640. continue
  641. case fieldTypeFloat:
  642. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  643. pos += 4
  644. continue
  645. case fieldTypeDouble:
  646. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  647. pos += 8
  648. continue
  649. // Length coded Binary Strings
  650. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  651. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  652. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  653. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  654. var isNull bool
  655. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  656. pos += n
  657. if err == nil {
  658. if !isNull {
  659. continue
  660. } else {
  661. dest[i] = nil
  662. continue
  663. }
  664. }
  665. return // err
  666. // Date YYYY-MM-DD
  667. case fieldTypeDate, fieldTypeNewDate:
  668. var num uint64
  669. var isNull bool
  670. num, isNull, n = readLengthEncodedInteger(data[pos:])
  671. pos += n
  672. if num == 0 {
  673. if isNull {
  674. dest[i] = nil
  675. continue
  676. } else {
  677. dest[i] = []byte("0000-00-00")
  678. continue
  679. }
  680. } else {
  681. dest[i] = []byte(fmt.Sprintf("%04d-%02d-%02d",
  682. binary.LittleEndian.Uint16(data[pos:pos+2]),
  683. data[pos+2],
  684. data[pos+3]))
  685. pos += int(num)
  686. continue
  687. }
  688. // Time [-][H]HH:MM:SS[.fractal]
  689. case fieldTypeTime:
  690. var num uint64
  691. var isNull bool
  692. num, isNull, n = readLengthEncodedInteger(data[pos:])
  693. pos += n
  694. if num == 0 {
  695. if isNull {
  696. dest[i] = nil
  697. continue
  698. } else {
  699. dest[i] = []byte("00:00:00")
  700. continue
  701. }
  702. }
  703. var sign byte
  704. if data[pos] == 1 {
  705. sign = byte('-')
  706. }
  707. switch num {
  708. case 8:
  709. dest[i] = []byte(fmt.Sprintf(
  710. "%c%02d:%02d:%02d",
  711. sign,
  712. uint16(data[pos+1])*24+uint16(data[pos+5]),
  713. data[pos+6],
  714. data[pos+7],
  715. ))
  716. pos += 8
  717. continue
  718. case 12:
  719. dest[i] = []byte(fmt.Sprintf(
  720. "%c%02d:%02d:%02d.%06d",
  721. sign,
  722. uint16(data[pos+1])*24+uint16(data[pos+5]),
  723. data[pos+6],
  724. data[pos+7],
  725. binary.LittleEndian.Uint32(data[pos+8:pos+12]),
  726. ))
  727. pos += 12
  728. continue
  729. default:
  730. return fmt.Errorf("Invalid TIME-packet length %d", num)
  731. }
  732. // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  733. case fieldTypeTimestamp, fieldTypeDateTime:
  734. var num uint64
  735. var isNull bool
  736. num, isNull, n = readLengthEncodedInteger(data[pos:])
  737. pos += n
  738. if num == 0 {
  739. if isNull {
  740. dest[i] = nil
  741. continue
  742. } else {
  743. dest[i] = []byte("0000-00-00 00:00:00")
  744. continue
  745. }
  746. }
  747. switch num {
  748. case 4:
  749. dest[i] = []byte(fmt.Sprintf(
  750. "%04d-%02d-%02d 00:00:00",
  751. binary.LittleEndian.Uint16(data[pos:pos+2]),
  752. data[pos+2],
  753. data[pos+3],
  754. ))
  755. pos += 4
  756. continue
  757. case 7:
  758. dest[i] = []byte(fmt.Sprintf(
  759. "%04d-%02d-%02d %02d:%02d:%02d",
  760. binary.LittleEndian.Uint16(data[pos:pos+2]),
  761. data[pos+2],
  762. data[pos+3],
  763. data[pos+4],
  764. data[pos+5],
  765. data[pos+6],
  766. ))
  767. pos += 7
  768. continue
  769. case 11:
  770. dest[i] = []byte(fmt.Sprintf(
  771. "%04d-%02d-%02d %02d:%02d:%02d.%06d",
  772. binary.LittleEndian.Uint16(data[pos:pos+2]),
  773. data[pos+2],
  774. data[pos+3],
  775. data[pos+4],
  776. data[pos+5],
  777. data[pos+6],
  778. binary.LittleEndian.Uint32(data[pos+7:pos+11]),
  779. ))
  780. pos += 11
  781. continue
  782. default:
  783. return fmt.Errorf("Invalid DATETIME-packet length %d", num)
  784. }
  785. // Please report if this happens!
  786. default:
  787. return fmt.Errorf("Unknown FieldType %d", rc.columns[i].fieldType)
  788. }
  789. }
  790. return
  791. }