packets.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. pos := 0
  390. for i := range dest {
  391. // Read bytes and convert to string
  392. dest[i], n, err = readLengthEnodedString(data[pos:])
  393. pos += n
  394. if err == nil {
  395. continue
  396. }
  397. return // err
  398. }
  399. return
  400. }
  401. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  402. func (mc *mysqlConn) readUntilEOF() (err error) {
  403. var data []byte
  404. for {
  405. data, err = mc.readPacket()
  406. // No Err and no EOF Packet
  407. if err == nil && (data[0] != 254 || len(data) != 5) {
  408. continue
  409. }
  410. return
  411. }
  412. return
  413. }
  414. /******************************************************************************
  415. * Prepared Statements *
  416. ******************************************************************************/
  417. // Prepare Result Packets
  418. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  419. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  420. data, err := stmt.mc.readPacket()
  421. if err == nil {
  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. }
  442. return
  443. }
  444. // Execute Prepared Statement
  445. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-execute
  446. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  447. if len(args) != stmt.paramCount {
  448. return fmt.Errorf(
  449. "Arguments count mismatch (Got: %d Has: %d",
  450. len(args),
  451. stmt.paramCount)
  452. }
  453. // Reset packet-sequence
  454. stmt.mc.sequence = 0
  455. pktLen := 1 + 4 + 1 + 4 + ((stmt.paramCount + 7) >> 3) + 1 + (stmt.paramCount << 1)
  456. paramValues := make([][]byte, stmt.paramCount)
  457. paramTypes := make([]byte, (stmt.paramCount << 1))
  458. bitMask := uint64(0)
  459. var i int
  460. for i = range args {
  461. // build NULL-bitmap
  462. if args[i] == nil {
  463. bitMask += 1 << uint(i)
  464. paramTypes[i<<1] = FIELD_TYPE_NULL
  465. continue
  466. }
  467. // cache types and values
  468. switch args[i].(type) {
  469. case int64:
  470. paramTypes[i<<1] = FIELD_TYPE_LONGLONG
  471. paramValues[i] = uint64ToBytes(uint64(args[i].(int64)))
  472. pktLen += 8
  473. continue
  474. case float64:
  475. paramTypes[i<<1] = FIELD_TYPE_DOUBLE
  476. paramValues[i] = uint64ToBytes(math.Float64bits(args[i].(float64)))
  477. pktLen += 8
  478. continue
  479. case bool:
  480. paramTypes[i<<1] = FIELD_TYPE_TINY
  481. pktLen++
  482. if args[i].(bool) {
  483. paramValues[i] = []byte{0x01}
  484. } else {
  485. paramValues[i] = []byte{0x00}
  486. }
  487. continue
  488. case []byte:
  489. paramTypes[i<<1] = FIELD_TYPE_STRING
  490. val := args[i].([]byte)
  491. paramValues[i] = append(
  492. lengthEncodedIntegerToBytes(uint64(len(val))),
  493. val...,
  494. )
  495. pktLen += len(paramValues[i])
  496. continue
  497. case string:
  498. paramTypes[i<<1] = FIELD_TYPE_STRING
  499. val := []byte(args[i].(string))
  500. paramValues[i] = append(
  501. lengthEncodedIntegerToBytes(uint64(len(val))),
  502. val...,
  503. )
  504. pktLen += len(paramValues[i])
  505. continue
  506. case time.Time:
  507. paramTypes[i<<1] = FIELD_TYPE_STRING
  508. val := []byte(args[i].(time.Time).Format(TIME_FORMAT))
  509. paramValues[i] = append(
  510. lengthEncodedIntegerToBytes(uint64(len(val))),
  511. val...,
  512. )
  513. pktLen += len(paramValues[i])
  514. continue
  515. default:
  516. return fmt.Errorf("Can't convert type: %T", args[i])
  517. }
  518. }
  519. data := make([]byte, pktLen+4)
  520. // packet header [4 bytes]
  521. data[0] = byte(pktLen)
  522. data[1] = byte(pktLen >> 8)
  523. data[2] = byte(pktLen >> 16)
  524. data[3] = stmt.mc.sequence
  525. // command [1 byte]
  526. data[4] = byte(COM_STMT_EXECUTE)
  527. // statement_id [4 bytes]
  528. data[5] = byte(stmt.id)
  529. data[6] = byte(stmt.id >> 8)
  530. data[7] = byte(stmt.id >> 16)
  531. data[8] = byte(stmt.id >> 24)
  532. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  533. //data[9] = 0x00
  534. // iteration_count (uint32(1)) [4 bytes]
  535. data[10] = 0x01
  536. //data[11] = 0x00
  537. //data[12] = 0x00
  538. //data[13] = 0x00
  539. if stmt.paramCount > 0 {
  540. // NULL-bitmap [(param_count+7)/8 bytes]
  541. pos := 14 + ((stmt.paramCount + 7) >> 3)
  542. // Convert bitMask to bytes
  543. for i = 14; i < pos; i++ {
  544. data[i] = byte(bitMask >> uint(i<<3))
  545. }
  546. // newParameterBoundFlag 1 [1 byte]
  547. data[pos] = 0x01
  548. pos++
  549. // type of parameters [param_count*2 byte]
  550. pos += copy(data[pos:], paramTypes)
  551. // values for the parameters [n byte]
  552. for i = range paramValues {
  553. pos += copy(data[pos:], paramValues[i])
  554. }
  555. }
  556. return stmt.mc.writePacket(data)
  557. }
  558. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::ResultsetRow
  559. func (rc *mysqlRows) readBinaryRow(dest []driver.Value) (err error) {
  560. data, err := rc.mc.readPacket()
  561. if err != nil {
  562. return
  563. }
  564. // packet header [1 byte]
  565. if data[0] != 0x00 {
  566. // EOF Packet
  567. if data[0] == 254 && len(data) == 5 {
  568. return io.EOF
  569. } else {
  570. // Error otherwise
  571. return rc.mc.handleErrorPacket(data)
  572. }
  573. }
  574. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  575. pos := 1 + (len(dest)+7+2)>>3
  576. nullBitMap := data[1:pos]
  577. // values [rest]
  578. var n int
  579. var unsigned bool
  580. for i := range dest {
  581. // Field is NULL
  582. // (byte >> bit-pos) % 2 == 1
  583. if ((nullBitMap[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  584. dest[i] = nil
  585. continue
  586. }
  587. unsigned = rc.columns[i].flags&FLAG_UNSIGNED != 0
  588. // Convert to byte-coded string
  589. switch rc.columns[i].fieldType {
  590. case FIELD_TYPE_NULL:
  591. dest[i] = nil
  592. continue
  593. // Numeric Typs
  594. case FIELD_TYPE_TINY:
  595. if unsigned {
  596. dest[i] = int64(data[pos])
  597. } else {
  598. dest[i] = int64(int8(data[pos]))
  599. }
  600. pos++
  601. continue
  602. case FIELD_TYPE_SHORT, FIELD_TYPE_YEAR:
  603. if unsigned {
  604. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  605. } else {
  606. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  607. }
  608. pos += 2
  609. continue
  610. case FIELD_TYPE_INT24, FIELD_TYPE_LONG:
  611. if unsigned {
  612. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  613. } else {
  614. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  615. }
  616. pos += 4
  617. continue
  618. case FIELD_TYPE_LONGLONG:
  619. if unsigned {
  620. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  621. if val > math.MaxInt64 {
  622. dest[i] = uint64ToString(val)
  623. } else {
  624. dest[i] = int64(val)
  625. }
  626. } else {
  627. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  628. }
  629. pos += 8
  630. continue
  631. case FIELD_TYPE_FLOAT:
  632. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  633. pos += 4
  634. continue
  635. case FIELD_TYPE_DOUBLE:
  636. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  637. pos += 8
  638. continue
  639. // Length coded Binary Strings
  640. case FIELD_TYPE_DECIMAL, FIELD_TYPE_NEWDECIMAL, FIELD_TYPE_VARCHAR,
  641. FIELD_TYPE_BIT, FIELD_TYPE_ENUM, FIELD_TYPE_SET,
  642. FIELD_TYPE_TINY_BLOB, FIELD_TYPE_MEDIUM_BLOB, FIELD_TYPE_LONG_BLOB,
  643. FIELD_TYPE_BLOB, FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING,
  644. FIELD_TYPE_GEOMETRY:
  645. dest[i], n, err = readLengthEnodedString(data[pos:])
  646. pos += n
  647. if err == nil {
  648. continue
  649. }
  650. return // err
  651. // Date YYYY-MM-DD
  652. case FIELD_TYPE_DATE, FIELD_TYPE_NEWDATE:
  653. var num uint64
  654. var isNull bool
  655. num, isNull, n = readLengthEncodedInteger(data[pos:])
  656. if num == 0 {
  657. if isNull {
  658. dest[i] = nil
  659. pos++ // always n=1
  660. continue
  661. } else {
  662. dest[i] = []byte("0000-00-00")
  663. pos += n
  664. continue
  665. }
  666. } else {
  667. dest[i] = []byte(fmt.Sprintf("%04d-%02d-%02d",
  668. binary.LittleEndian.Uint16(data[pos:pos+2]),
  669. data[pos+2],
  670. data[pos+3]))
  671. pos += n + int(num)
  672. continue
  673. }
  674. // Time [-][H]HH:MM:SS[.fractal]
  675. case FIELD_TYPE_TIME:
  676. var num uint64
  677. var isNull bool
  678. num, isNull, n = readLengthEncodedInteger(data[pos:])
  679. if num == 0 {
  680. if isNull {
  681. dest[i] = nil
  682. pos++ // always n=1
  683. continue
  684. } else {
  685. dest[i] = []byte("00:00:00")
  686. pos += n
  687. continue
  688. }
  689. }
  690. pos += n
  691. var sign byte
  692. if data[pos] == 1 {
  693. sign = byte('-')
  694. }
  695. switch num {
  696. case 8:
  697. dest[i] = []byte(fmt.Sprintf(
  698. "%c%02d:%02d:%02d",
  699. sign,
  700. uint16(data[pos+1])*24+uint16(data[pos+5]),
  701. data[pos+6],
  702. data[pos+7],
  703. ))
  704. pos += 8
  705. continue
  706. case 12:
  707. dest[i] = []byte(fmt.Sprintf(
  708. "%c%02d:%02d:%02d.%06d",
  709. sign,
  710. uint16(data[pos+1])*24+uint16(data[pos+5]),
  711. data[pos+6],
  712. data[pos+7],
  713. binary.LittleEndian.Uint32(data[pos+8:pos+12]),
  714. ))
  715. pos += 12
  716. continue
  717. default:
  718. return fmt.Errorf("Invalid TIME-packet length %d", num)
  719. }
  720. // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  721. case FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  722. var num uint64
  723. var isNull bool
  724. num, isNull, n = readLengthEncodedInteger(data[pos:])
  725. if num == 0 {
  726. if isNull {
  727. dest[i] = nil
  728. pos++ // always n=1
  729. continue
  730. } else {
  731. dest[i] = []byte("0000-00-00 00:00:00")
  732. pos += n
  733. continue
  734. }
  735. }
  736. pos += n
  737. switch num {
  738. case 4:
  739. dest[i] = []byte(fmt.Sprintf(
  740. "%04d-%02d-%02d 00:00:00",
  741. binary.LittleEndian.Uint16(data[pos:pos+2]),
  742. data[pos+2],
  743. data[pos+3],
  744. ))
  745. pos += 4
  746. continue
  747. case 7:
  748. dest[i] = []byte(fmt.Sprintf(
  749. "%04d-%02d-%02d %02d:%02d:%02d",
  750. binary.LittleEndian.Uint16(data[pos:pos+2]),
  751. data[pos+2],
  752. data[pos+3],
  753. data[pos+4],
  754. data[pos+5],
  755. data[pos+6],
  756. ))
  757. pos += 7
  758. continue
  759. case 11:
  760. dest[i] = []byte(fmt.Sprintf(
  761. "%04d-%02d-%02d %02d:%02d:%02d.%06d",
  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. binary.LittleEndian.Uint32(data[pos+7:pos+11]),
  769. ))
  770. pos += 11
  771. continue
  772. default:
  773. return fmt.Errorf("Invalid DATETIME-packet length %d", num)
  774. }
  775. // Please report if this happens!
  776. default:
  777. return fmt.Errorf("Unknown FieldType %d", rc.columns[i].fieldType)
  778. }
  779. }
  780. return
  781. }