packets.go 21 KB

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