packets.go 21 KB

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