packets.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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)
  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. return nil, err
  38. }
  39. // Check Packet Sync
  40. if data[3] != mc.sequence {
  41. if data[3] > mc.sequence {
  42. return nil, errPktSyncMul
  43. } else {
  44. return nil, errPktSync
  45. }
  46. }
  47. mc.sequence++
  48. // Read packet body
  49. data = make([]byte, pktLen)
  50. err = mc.buf.read(data)
  51. if err == nil {
  52. return data, nil
  53. }
  54. errLog.Print(err)
  55. return nil, driver.ErrBadConn
  56. }
  57. // Write packet buffer 'data'
  58. // The packet header must be already included
  59. func (mc *mysqlConn) writePacket(data []byte) error {
  60. // Write packet
  61. n, err := mc.netConn.Write(data)
  62. if err == nil || n == len(data) {
  63. mc.sequence++
  64. return nil
  65. }
  66. if err == nil { // n != len(data)
  67. errLog.Print(errMalformPkt)
  68. } else {
  69. errLog.Print(err)
  70. }
  71. return driver.ErrBadConn
  72. }
  73. /******************************************************************************
  74. * Initialisation Process *
  75. ******************************************************************************/
  76. // Handshake Initialization Packet
  77. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
  78. func (mc *mysqlConn) readInitPacket() (err error) {
  79. data, err := mc.readPacket()
  80. if err != nil {
  81. return
  82. }
  83. // protocol version [1 byte]
  84. if data[0] < MIN_PROTOCOL_VERSION {
  85. err = fmt.Errorf(
  86. "Unsupported MySQL Protocol Version %d. Protocol Version %d or higher is required",
  87. data[0],
  88. MIN_PROTOCOL_VERSION)
  89. }
  90. // server version [null terminated string]
  91. // connection id [4 bytes]
  92. pos := 1 + (bytes.IndexByte(data[1:], 0x00) + 1) + 4
  93. // first part of scramble buffer [8 bytes]
  94. mc.scrambleBuff = data[pos : pos+8]
  95. // (filler) always 0x00 [1 byte]
  96. pos += 8 + 1
  97. // capability flags (lower 2 bytes) [2 bytes]
  98. mc.flags = ClientFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  99. if mc.flags&CLIENT_PROTOCOL_41 == 0 {
  100. err = errors.New("MySQL-Server does not support required Protocol 41+")
  101. }
  102. pos += 2
  103. if len(data) > pos {
  104. // character set [1 byte]
  105. mc.charset = data[pos]
  106. // status flags [2 bytes]
  107. // capability flags (upper 2 bytes) [2 bytes]
  108. // length of auth-plugin-data [1 byte]
  109. // reserved (all [00]) [10 byte]
  110. pos += 1 + 2 + 2 + 1 + 10
  111. mc.scrambleBuff = append(mc.scrambleBuff, data[pos:len(data)-1]...)
  112. if data[len(data)-1] == 0 {
  113. return
  114. }
  115. return errMalformPkt
  116. }
  117. return
  118. }
  119. // Client Authentication Packet
  120. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::HandshakeResponse
  121. func (mc *mysqlConn) writeAuthPacket() error {
  122. // Adjust client flags based on server support
  123. clientFlags := uint32(
  124. CLIENT_PROTOCOL_41 |
  125. CLIENT_SECURE_CONN |
  126. CLIENT_LONG_PASSWORD |
  127. CLIENT_TRANSACTIONS,
  128. )
  129. if mc.flags&CLIENT_LONG_FLAG > 0 {
  130. clientFlags |= uint32(CLIENT_LONG_FLAG)
  131. }
  132. // User Password
  133. scrambleBuff := scramblePassword(mc.scrambleBuff, []byte(mc.cfg.passwd))
  134. mc.scrambleBuff = nil
  135. pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff)
  136. // To specify a db name
  137. if len(mc.cfg.dbname) > 0 {
  138. clientFlags |= uint32(CLIENT_CONNECT_WITH_DB)
  139. pktLen += len(mc.cfg.dbname) + 1
  140. }
  141. // Calculate packet length and make buffer with that size
  142. data := make([]byte, pktLen+4)
  143. // Add the packet header [24bit length + 1 byte sequence]
  144. data[0] = byte(pktLen)
  145. data[1] = byte(pktLen >> 8)
  146. data[2] = byte(pktLen >> 16)
  147. data[3] = mc.sequence
  148. // ClientFlags [32 bit]
  149. data[4] = byte(clientFlags)
  150. data[5] = byte(clientFlags >> 8)
  151. data[6] = byte(clientFlags >> 16)
  152. data[7] = byte(clientFlags >> 24)
  153. // MaxPacketSize [32 bit] (1<<24 - 1)
  154. data[8] = 0xff
  155. data[9] = 0xff
  156. data[10] = 0xff
  157. //data[11] = 0x00
  158. // Charset [1 byte]
  159. data[12] = mc.charset
  160. // Filler [23 byte] (all 0x00)
  161. pos := 13 + 23
  162. // User [null terminated string]
  163. if len(mc.cfg.user) > 0 {
  164. pos += copy(data[pos:], mc.cfg.user)
  165. }
  166. //data[pos] = 0x00
  167. pos++
  168. // ScrambleBuffer [length encoded integer]
  169. data[pos] = byte(len(scrambleBuff))
  170. pos += 1 + copy(data[pos+1:], scrambleBuff)
  171. // Databasename [null terminated string]
  172. if len(mc.cfg.dbname) > 0 {
  173. pos += copy(data[pos:], mc.cfg.dbname)
  174. //data[pos] = 0x00
  175. }
  176. // Send Auth packet
  177. return mc.writePacket(data)
  178. }
  179. /******************************************************************************
  180. * Command Packets *
  181. ******************************************************************************/
  182. func (mc *mysqlConn) writeCommandPacket(command commandType) error {
  183. // Reset Packet Sequence
  184. mc.sequence = 0
  185. // Send CMD packet
  186. return mc.writePacket([]byte{
  187. // Add the packet header [24bit length + 1 byte sequence]
  188. 0x05, // 5 bytes long
  189. 0x00,
  190. 0x00,
  191. mc.sequence,
  192. // Add command byte
  193. byte(command),
  194. })
  195. }
  196. func (mc *mysqlConn) writeCommandPacketStr(command commandType, arg string) error {
  197. // Reset Packet Sequence
  198. mc.sequence = 0
  199. pktLen := 1 + len(arg)
  200. data := make([]byte, pktLen+4)
  201. // Add the packet header [24bit length + 1 byte sequence]
  202. data[0] = byte(pktLen)
  203. data[1] = byte(pktLen >> 8)
  204. data[2] = byte(pktLen >> 16)
  205. data[3] = mc.sequence
  206. // Add command byte
  207. data[4] = byte(command)
  208. // Add arg
  209. copy(data[5:], arg)
  210. // Send CMD packet
  211. return mc.writePacket(data)
  212. }
  213. func (mc *mysqlConn) writeCommandPacketUint32(command commandType, arg uint32) error {
  214. // Reset Packet Sequence
  215. mc.sequence = 0
  216. // Send CMD packet
  217. return mc.writePacket([]byte{
  218. // Add the packet header [24bit length + 1 byte sequence]
  219. 0x05, // 5 bytes long
  220. 0x00,
  221. 0x00,
  222. mc.sequence,
  223. // Add command byte
  224. byte(command),
  225. // Add arg [32 bit]
  226. byte(arg),
  227. byte(arg >> 8),
  228. byte(arg >> 16),
  229. byte(arg >> 24),
  230. })
  231. }
  232. /******************************************************************************
  233. * Result Packets *
  234. ******************************************************************************/
  235. // Returns error if Packet is not an 'Result OK'-Packet
  236. func (mc *mysqlConn) readResultOK() error {
  237. data, err := mc.readPacket()
  238. if err != nil {
  239. return err
  240. }
  241. switch data[0] {
  242. // OK
  243. case 0:
  244. mc.handleOkPacket(data)
  245. return nil
  246. // EOF, someone is using old_passwords
  247. case 254:
  248. return errOldPassword
  249. }
  250. // ERROR
  251. return mc.handleErrorPacket(data)
  252. }
  253. // Result Set Header Packet
  254. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
  255. func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
  256. data, err := mc.readPacket()
  257. if err != nil {
  258. return 0, err
  259. }
  260. if data[0] == 0 {
  261. mc.handleOkPacket(data)
  262. return 0, nil
  263. } else if data[0] == 255 {
  264. return 0, mc.handleErrorPacket(data)
  265. }
  266. // column count
  267. num, _, n := readLengthEncodedInteger(data)
  268. if n-len(data) == 0 {
  269. return int(num), nil
  270. }
  271. return 0, errMalformPkt
  272. }
  273. // Error Packet
  274. // http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
  275. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  276. if data[0] != 255 {
  277. return errMalformPkt
  278. }
  279. // 0xff [1 byte]
  280. // Error Number [16 bit uint]
  281. errno := binary.LittleEndian.Uint16(data[1:3])
  282. // SQL State [# + 5bytes string]
  283. //sqlstate := string(data[pos : pos+6])
  284. // Error Message [string]
  285. return fmt.Errorf("Error %d: %s", errno, string(data[9:]))
  286. }
  287. // Ok Packet
  288. // http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
  289. func (mc *mysqlConn) handleOkPacket(data []byte) {
  290. var n int
  291. // 0x00 [1 byte]
  292. // Affected rows [Length Coded Binary]
  293. mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
  294. // Insert id [Length Coded Binary]
  295. mc.insertId, _, _ = readLengthEncodedInteger(data[1+n:])
  296. // server_status [2 bytes]
  297. // warning count [2 bytes]
  298. // message [until end of packet]
  299. }
  300. // Read Packets as Field Packets until EOF-Packet or an Error appears
  301. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
  302. func (mc *mysqlConn) readColumns(count int) (columns []mysqlField, err error) {
  303. var data []byte
  304. var i, pos, n int
  305. var name []byte
  306. columns = make([]mysqlField, count)
  307. for {
  308. data, err = mc.readPacket()
  309. if err != nil {
  310. return
  311. }
  312. // EOF Packet
  313. if data[0] == 254 && len(data) == 5 {
  314. if i != count {
  315. err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
  316. }
  317. return
  318. }
  319. // Catalog
  320. pos, err = skipLengthEnodedString(data)
  321. if err != nil {
  322. return
  323. }
  324. // Database [len coded string]
  325. n, err = skipLengthEnodedString(data[pos:])
  326. if err != nil {
  327. return
  328. }
  329. pos += n
  330. // Table [len coded string]
  331. n, err = skipLengthEnodedString(data[pos:])
  332. if err != nil {
  333. return
  334. }
  335. pos += n
  336. // Original table [len coded string]
  337. n, err = skipLengthEnodedString(data[pos:])
  338. if err != nil {
  339. return
  340. }
  341. pos += n
  342. // Name [len coded string]
  343. name, n, err = readLengthEnodedString(data[pos:])
  344. if err != nil {
  345. return
  346. }
  347. columns[i].name = string(name)
  348. pos += n
  349. // Original name [len coded string]
  350. n, err = skipLengthEnodedString(data[pos:])
  351. if err != nil {
  352. return
  353. }
  354. // Filler [1 byte]
  355. // Charset [16 bit uint]
  356. // Length [32 bit uint]
  357. pos += n + 1 + 2 + 4
  358. // Field type [byte]
  359. columns[i].fieldType = FieldType(data[pos])
  360. pos++
  361. // Flags [16 bit uint]
  362. columns[i].flags = FieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  363. //pos += 2
  364. // Decimals [8 bit uint]
  365. //pos++
  366. // Default value [len coded binary]
  367. //if pos < len(data) {
  368. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  369. //}
  370. i++
  371. }
  372. return
  373. }
  374. // Read Packets as Field Packets until EOF-Packet or an Error appears
  375. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
  376. func (rows *mysqlRows) readRow(dest []driver.Value) (err error) {
  377. data, err := rows.mc.readPacket()
  378. if err != nil {
  379. return
  380. }
  381. // EOF Packet
  382. if data[0] == 254 && len(data) == 5 {
  383. return io.EOF
  384. }
  385. // RowSet Packet
  386. var n int
  387. pos := 0
  388. for i := range dest {
  389. // Read bytes and convert to string
  390. dest[i], n, err = readLengthEnodedString(data[pos:])
  391. pos += n
  392. if err == nil {
  393. continue
  394. }
  395. return // err
  396. }
  397. return
  398. }
  399. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  400. func (mc *mysqlConn) readUntilEOF() (count uint64, err error) {
  401. var data []byte
  402. for {
  403. data, err = mc.readPacket()
  404. // Err or EOF Packet
  405. if err != nil || (data[0] == 254 && len(data) == 5) {
  406. return
  407. }
  408. count++
  409. }
  410. return
  411. }
  412. /******************************************************************************
  413. * Prepared Statements *
  414. ******************************************************************************/
  415. // Prepare Result Packets
  416. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  417. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  418. data, err := stmt.mc.readPacket()
  419. if err != nil {
  420. return
  421. }
  422. // Position
  423. pos := 0
  424. // packet marker [1 byte]
  425. if data[pos] != 0 { // not OK (0) ?
  426. err = stmt.mc.handleErrorPacket(data)
  427. return
  428. }
  429. pos++
  430. // statement id [4 bytes]
  431. stmt.id = binary.LittleEndian.Uint32(data[pos : pos+4])
  432. pos += 4
  433. // Column count [16 bit uint]
  434. columnCount = binary.LittleEndian.Uint16(data[pos : pos+2])
  435. pos += 2
  436. // Param count [16 bit uint]
  437. stmt.paramCount = int(binary.LittleEndian.Uint16(data[pos : pos+2]))
  438. pos += 2
  439. // Warning count [16 bit uint]
  440. // bytesToUint16(data[pos : pos+2])
  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. }