packets.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. "database/sql/driver"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "reflect"
  16. "time"
  17. )
  18. // Packets documentation:
  19. // http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol
  20. // Read packet to buffer 'data'
  21. func (mc *mysqlConn) readPacket() (data []byte, e error) {
  22. // Packet Length
  23. pktLen, e := mc.readNumber(3)
  24. if e != nil {
  25. return
  26. }
  27. if int(pktLen) == 0 {
  28. return
  29. }
  30. // Packet Number
  31. pktSeq, e := mc.readNumber(1)
  32. if e != nil {
  33. return
  34. }
  35. // Check Packet Sync
  36. if uint8(pktSeq) != mc.sequence {
  37. e = errors.New("Commands out of sync; you can't run this command now")
  38. return
  39. }
  40. mc.sequence++
  41. // Read rest of packet
  42. data = make([]byte, pktLen)
  43. var n, add int
  44. n, e = mc.netConn.Read(data)
  45. // Read conventionally returns what is available instead of waiting for more
  46. for e == nil && n < int(pktLen) {
  47. add, e = mc.netConn.Read(data[n:])
  48. n += add
  49. }
  50. if e != nil || n != int(pktLen) {
  51. errLog.Print(e)
  52. e = driver.ErrBadConn
  53. return
  54. }
  55. return data[:pktLen], e // Return without scratch space
  56. }
  57. // Send Packet with given data
  58. func (mc *mysqlConn) writePacket(data []byte) (e error) {
  59. // Set time BEFORE to avoid possible collisions
  60. if mc.server.keepalive > 0 {
  61. mc.lastCmdTime = time.Now()
  62. }
  63. pktLen := uint32(len(data))
  64. if int(pktLen) == 0 {
  65. return
  66. }
  67. // Add the packet header
  68. pktData := make([]byte, 0, len(data)+4)
  69. pktData = append(pktData, uint24ToBytes(pktLen)...)
  70. pktData = append(pktData, mc.sequence)
  71. pktData = append(pktData, data...)
  72. // Write packet
  73. n, e := mc.netConn.Write(pktData)
  74. if e != nil || n != len(pktData) {
  75. if e == nil {
  76. e = errors.New("Length of send data does not match packet length")
  77. }
  78. errLog.Print(e)
  79. e = driver.ErrBadConn
  80. return
  81. }
  82. mc.sequence++
  83. return
  84. }
  85. // Read n bytes long number num
  86. func (mc *mysqlConn) readNumber(n uint8) (num uint64, e error) {
  87. // Read bytes into array
  88. buf := make([]byte, n)
  89. nr, err := io.ReadFull(mc.netConn, buf)
  90. if err != nil || nr != int(n) {
  91. if e == nil {
  92. e = errors.New("Length of read data does not match header length")
  93. }
  94. errLog.Print(e)
  95. e = driver.ErrBadConn
  96. return
  97. }
  98. // Convert to uint64
  99. num = 0
  100. for i := uint8(0); i < n; i++ {
  101. num |= uint64(buf[i]) << (i * 8)
  102. }
  103. return
  104. }
  105. /******************************************************************************
  106. * Initialisation Process *
  107. ******************************************************************************/
  108. /* Handshake Initialization Packet
  109. Bytes Name
  110. ----- ----
  111. 1 protocol_version
  112. n (Null-Terminated String) server_version
  113. 4 thread_id
  114. 8 scramble_buff
  115. 1 (filler) always 0x00
  116. 2 server_capabilities
  117. 1 server_language
  118. 2 server_status
  119. 2 server capabilities (two upper bytes)
  120. 1 length of the scramble
  121. 10 (filler) always 0
  122. n rest of the plugin provided data (at least 12 bytes)
  123. 1 \0 byte, terminating the second part of a scramble
  124. */
  125. func (mc *mysqlConn) readInitPacket() (e error) {
  126. data, e := mc.readPacket()
  127. if e != nil {
  128. return
  129. }
  130. mc.server = new(serverSettings)
  131. // Position
  132. pos := 0
  133. // Protocol version [8 bit uint]
  134. mc.server.protocol = data[pos]
  135. if mc.server.protocol < MIN_PROTOCOL_VERSION {
  136. e = fmt.Errorf(
  137. "Unsupported MySQL Protocol Version %d. Protocol Version %d or higher is required",
  138. mc.server.protocol,
  139. MIN_PROTOCOL_VERSION)
  140. }
  141. pos++
  142. // Server version [null terminated string]
  143. slice, err := readSlice(data[pos:], 0x00)
  144. if err != nil {
  145. return
  146. }
  147. mc.server.version = string(slice)
  148. pos += len(slice) + 1
  149. // Thread id [32 bit uint]
  150. mc.server.threadID = bytesToUint32(data[pos : pos+4])
  151. pos += 4
  152. // First part of scramble buffer [8 bytes]
  153. mc.server.scrambleBuff = make([]byte, 8)
  154. mc.server.scrambleBuff = data[pos : pos+8]
  155. pos += 9
  156. // Server capabilities [16 bit uint]
  157. mc.server.flags = ClientFlag(bytesToUint16(data[pos : pos+2]))
  158. if mc.server.flags&CLIENT_PROTOCOL_41 == 0 {
  159. e = errors.New("MySQL-Server does not support required Protocol 41+")
  160. }
  161. pos += 2
  162. // Server language [8 bit uint]
  163. mc.server.charset = data[pos]
  164. pos++
  165. // Server status [16 bit uint]
  166. pos += 15
  167. mc.server.scrambleBuff = append(mc.server.scrambleBuff, data[pos:pos+12]...)
  168. return
  169. }
  170. /* Client Authentication Packet
  171. Bytes Name
  172. ----- ----
  173. 4 client_flags
  174. 4 max_packet_size
  175. 1 charset_number
  176. 23 (filler) always 0x00...
  177. n (Null-Terminated String) user
  178. n (Length Coded Binary) scramble_buff (1 + x bytes)
  179. n (Null-Terminated String) databasename (optional)
  180. */
  181. func (mc *mysqlConn) writeAuthPacket() (e error) {
  182. // Adjust client flags based on server support
  183. clientFlags := uint32(CLIENT_MULTI_STATEMENTS |
  184. // CLIENT_MULTI_RESULTS |
  185. CLIENT_PROTOCOL_41 |
  186. CLIENT_SECURE_CONN |
  187. CLIENT_LONG_PASSWORD |
  188. CLIENT_TRANSACTIONS)
  189. if mc.server.flags&CLIENT_LONG_FLAG > 0 {
  190. clientFlags |= uint32(CLIENT_LONG_FLAG)
  191. }
  192. // To specify a db name
  193. if len(mc.cfg.dbname) > 0 {
  194. clientFlags |= uint32(CLIENT_CONNECT_WITH_DB)
  195. }
  196. // User Password
  197. scrambleBuff := scramblePassword(mc.server.scrambleBuff, []byte(mc.cfg.passwd))
  198. // Calculate packet length and make buffer with that size
  199. dataLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff) + len(mc.cfg.dbname) + 1
  200. data := make([]byte, 0, dataLen)
  201. // ClientFlags
  202. data = append(data, uint32ToBytes(clientFlags)...)
  203. // MaxPacketSize
  204. data = append(data, uint32ToBytes(MAX_PACKET_SIZE)...)
  205. // Charset
  206. data = append(data, mc.server.charset)
  207. // Filler
  208. data = append(data, make([]byte, 23)...)
  209. // User
  210. if len(mc.cfg.user) > 0 {
  211. data = append(data, []byte(mc.cfg.user)...)
  212. }
  213. // Null-Terminator
  214. data = append(data, 0x0)
  215. // ScrambleBuffer
  216. data = append(data, byte(len(scrambleBuff)))
  217. if len(scrambleBuff) > 0 {
  218. data = append(data, scrambleBuff...)
  219. }
  220. // Databasename
  221. if len(mc.cfg.dbname) > 0 {
  222. data = append(data, []byte(mc.cfg.dbname)...)
  223. // Null-Terminator
  224. data = append(data, 0x0)
  225. }
  226. // Send Auth-Packet
  227. mc.writePacket(data)
  228. return
  229. }
  230. /******************************************************************************
  231. * Command Packets *
  232. ******************************************************************************/
  233. /* Command Packet
  234. Bytes Name
  235. ----- ----
  236. 1 command
  237. n arg
  238. */
  239. func (mc *mysqlConn) writeCommandPacket(command commandType, args ...interface{}) (e error) {
  240. // Reset Packet Sequence
  241. mc.sequence = 0
  242. // Make slice from command byte
  243. data := []byte{byte(command)}
  244. switch command {
  245. // Commands without args
  246. case COM_QUIT, COM_PING:
  247. if len(args) > 0 {
  248. return fmt.Errorf("Too much arguments (Got: %d Has: 0)", len(args))
  249. }
  250. // Commands with 1 arg unterminated string
  251. case COM_QUERY, COM_STMT_PREPARE:
  252. if len(args) != 1 {
  253. return fmt.Errorf("Invalid arguments count (Got: %d Has: 1)", len(args))
  254. }
  255. data = append(data, []byte(args[0].(string))...)
  256. // Commands with 1 arg 32 bit uint
  257. case COM_STMT_CLOSE:
  258. if len(args) != 1 {
  259. return fmt.Errorf("Invalid arguments count (Got: %d Has: 1)", len(args))
  260. }
  261. data = append(data, uint32ToBytes(args[0].(uint32))...)
  262. default:
  263. return fmt.Errorf("Unknown command: %d", command)
  264. }
  265. // Send CMD packet
  266. return mc.writePacket(data)
  267. }
  268. /******************************************************************************
  269. * Result Packets *
  270. ******************************************************************************/
  271. // Returns error if Packet is not an 'Result OK'-Packet
  272. func (mc *mysqlConn) readResultOK() (e error) {
  273. data, e := mc.readPacket()
  274. if e != nil {
  275. return
  276. }
  277. switch data[0] {
  278. // OK
  279. case 0:
  280. return mc.handleOkPacket(data)
  281. // ERROR
  282. case 255:
  283. return mc.handleErrorPacket(data)
  284. default:
  285. e = errors.New("Invalid Result Packet-Type")
  286. return
  287. }
  288. return
  289. }
  290. /* Error Packet
  291. Bytes Name
  292. ----- ----
  293. 1 field_count, always = 0xff
  294. 2 errno
  295. 1 (sqlstate marker), always '#'
  296. 5 sqlstate (5 characters)
  297. n message
  298. */
  299. func (mc *mysqlConn) handleErrorPacket(data []byte) (e error) {
  300. if data[0] != 255 {
  301. e = errors.New("Wrong Packet-Type: Not an Error-Packet")
  302. return
  303. }
  304. pos := 1
  305. // Error Number [16 bit uint]
  306. errno := bytesToUint16(data[pos : pos+2])
  307. pos += 2
  308. // SQL State [# + 5bytes string]
  309. //sqlstate := string(data[pos : pos+6])
  310. pos += 6
  311. // Error Message [string]
  312. message := string(data[pos:])
  313. e = fmt.Errorf("Error %d: %s", errno, message)
  314. return
  315. }
  316. /* Ok Packet
  317. Bytes Name
  318. ----- ----
  319. 1 (Length Coded Binary) field_count, always = 0
  320. 1-9 (Length Coded Binary) affected_rows
  321. 1-9 (Length Coded Binary) insert_id
  322. 2 server_status
  323. 2 warning_count
  324. n (until end of packet) message
  325. */
  326. func (mc *mysqlConn) handleOkPacket(data []byte) (e error) {
  327. if data[0] != 0 {
  328. e = errors.New("Wrong Packet-Type: Not an OK-Packet")
  329. return
  330. }
  331. // Position
  332. pos := 1
  333. // Affected rows [Length Coded Binary]
  334. affectedRows, n, e := bytesToLengthCodedBinary(data[pos:])
  335. if e != nil {
  336. return
  337. }
  338. pos += n
  339. // Insert id [Length Coded Binary]
  340. insertID, n, e := bytesToLengthCodedBinary(data[pos:])
  341. if e != nil {
  342. return
  343. }
  344. // Skip remaining data
  345. mc.affectedRows = affectedRows
  346. mc.insertId = insertID
  347. return
  348. }
  349. /* Result Set Header Packet
  350. Bytes Name
  351. ----- ----
  352. 1-9 (Length-Coded-Binary) field_count
  353. 1-9 (Length-Coded-Binary) extra
  354. The order of packets for a result set is:
  355. (Result Set Header Packet) the number of columns
  356. (Field Packets) column descriptors
  357. (EOF Packet) marker: end of Field Packets
  358. (Row Data Packets) row contents
  359. (EOF Packet) marker: end of Data Packets
  360. */
  361. func (mc *mysqlConn) readResultSetHeaderPacket() (fieldCount int, e error) {
  362. data, e := mc.readPacket()
  363. if e != nil {
  364. errLog.Print(e)
  365. e = driver.ErrBadConn
  366. return
  367. }
  368. if data[0] == 255 {
  369. e = mc.handleErrorPacket(data)
  370. return
  371. } else if data[0] == 0 {
  372. e = mc.handleOkPacket(data)
  373. return
  374. }
  375. num, n, e := bytesToLengthCodedBinary(data)
  376. if e != nil || (n-len(data)) != 0 {
  377. e = errors.New("Malformed Packet")
  378. return
  379. }
  380. fieldCount = int(num)
  381. return
  382. }
  383. // Read Packets as Field Packets until EOF-Packet or an Error appears
  384. func (mc *mysqlConn) readColumns(n int) (columns []*mysqlField, e error) {
  385. var data []byte
  386. for {
  387. data, e = mc.readPacket()
  388. if e != nil {
  389. return
  390. }
  391. // EOF Packet
  392. if data[0] == 254 && len(data) == 5 {
  393. if len(columns) != n {
  394. e = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", n, len(columns))
  395. }
  396. return
  397. }
  398. var pos, n int
  399. var name []byte
  400. //var catalog, database, table, orgTable, name, orgName []byte
  401. //var defaultVal uint64
  402. // Catalog
  403. //catalog, n, _, e = readLengthCodedBinary(data)
  404. n, e = readAndDropLengthCodedBinary(data)
  405. if e != nil {
  406. return
  407. }
  408. pos += n
  409. // Database [len coded string]
  410. //database, n, _, e = readLengthCodedBinary(data[pos:])
  411. n, e = readAndDropLengthCodedBinary(data[pos:])
  412. if e != nil {
  413. return
  414. }
  415. pos += n
  416. // Table [len coded string]
  417. //table, n, _, e = readLengthCodedBinary(data[pos:])
  418. n, e = readAndDropLengthCodedBinary(data[pos:])
  419. if e != nil {
  420. return
  421. }
  422. pos += n
  423. // Original table [len coded string]
  424. //orgTable, n, _, e = readLengthCodedBinary(data[pos:])
  425. n, e = readAndDropLengthCodedBinary(data[pos:])
  426. if e != nil {
  427. return
  428. }
  429. pos += n
  430. // Name [len coded string]
  431. name, n, _, e = readLengthCodedBinary(data[pos:])
  432. if e != nil {
  433. return
  434. }
  435. pos += n
  436. // Original name [len coded string]
  437. //orgName, n, _, e = readLengthCodedBinary(data[pos:])
  438. n, e = readAndDropLengthCodedBinary(data[pos:])
  439. if e != nil {
  440. return
  441. }
  442. pos += n
  443. // Filler
  444. pos++
  445. // Charset [16 bit uint]
  446. //charsetNumber := bytesToUint16(data[pos : pos+2])
  447. pos += 2
  448. // Length [32 bit uint]
  449. //length := bytesToUint32(data[pos : pos+4])
  450. pos += 4
  451. // Field type [byte]
  452. fieldType := FieldType(data[pos])
  453. pos++
  454. // Flags [16 bit uint]
  455. flags := FieldFlag(bytesToUint16(data[pos : pos+2]))
  456. //pos += 2
  457. // Decimals [8 bit uint]
  458. //decimals := data[pos]
  459. //pos++
  460. // Default value [len coded binary]
  461. //if pos < len(data) {
  462. // defaultVal, _, e = bytesToLengthCodedBinary(data[pos:])
  463. //}
  464. columns = append(columns, &mysqlField{name: string(name), fieldType: fieldType, flags: flags})
  465. }
  466. return
  467. }
  468. // Read Packets as Field Packets until EOF-Packet or an Error appears
  469. func (mc *mysqlConn) readRows(columnsCount int) (rows []*[]*[]byte, e error) {
  470. var data []byte
  471. var i, pos, n int
  472. var isNull bool
  473. for {
  474. data, e = mc.readPacket()
  475. if e != nil {
  476. return
  477. }
  478. // EOF Packet
  479. if data[0] == 254 && len(data) == 5 {
  480. return
  481. }
  482. // RowSet Packet
  483. row := make([]*[]byte, 0, columnsCount)
  484. pos = 0
  485. for i = 0; i < columnsCount; i++ {
  486. // Read bytes and convert to string
  487. var value []byte
  488. value, n, isNull, e = readLengthCodedBinary(data[pos:])
  489. if e != nil {
  490. return
  491. }
  492. // Append nil if field is NULL
  493. if isNull {
  494. row = append(row, nil)
  495. } else {
  496. row = append(row, &value)
  497. }
  498. pos += n
  499. }
  500. rows = append(rows, &row)
  501. }
  502. mc.affectedRows = uint64(len(rows))
  503. return
  504. }
  505. // Reads Packets Packets until EOF-Packet or an Error appears. Returns count of Packets read
  506. func (mc *mysqlConn) readUntilEOF() (count uint64, e error) {
  507. var data []byte
  508. for {
  509. data, e = mc.readPacket()
  510. if e != nil {
  511. return
  512. }
  513. // EOF Packet
  514. if data[0] == 254 && len(data) == 5 {
  515. return
  516. }
  517. count++
  518. }
  519. return
  520. }
  521. /******************************************************************************
  522. * Prepared Statements *
  523. ******************************************************************************/
  524. /* Prepare Result Packets
  525. Type Of Result Packet Hexadecimal Value Of First Byte (field_count)
  526. --------------------- ---------------------------------------------
  527. Prepare OK Packet 00
  528. Error Packet ff
  529. Prepare OK Packet
  530. Bytes Name
  531. ----- ----
  532. 1 0 - marker for OK packet
  533. 4 statement_handler_id
  534. 2 number of columns in result set
  535. 2 number of parameters in query
  536. 1 filler (always 0)
  537. 2 warning count
  538. It is made up of:
  539. a PREPARE_OK packet
  540. if "number of parameters" > 0
  541. (field packets) as in a Result Set Header Packet
  542. (EOF packet)
  543. if "number of columns" > 0
  544. (field packets) as in a Result Set Header Packet
  545. (EOF packet)
  546. */
  547. func (stmt mysqlStmt) readPrepareResultPacket() (columnCount uint16, e error) {
  548. data, e := stmt.mc.readPacket()
  549. if e != nil {
  550. return
  551. }
  552. // Position
  553. pos := 0
  554. if data[pos] != 0 {
  555. e = stmt.mc.handleErrorPacket(data)
  556. return
  557. }
  558. pos++
  559. stmt.id = bytesToUint32(data[pos : pos+4])
  560. pos += 4
  561. // Column count [16 bit uint]
  562. columnCount = bytesToUint16(data[pos : pos+2])
  563. pos += 2
  564. // Param count [16 bit uint]
  565. stmt.paramCount = int(bytesToUint16(data[pos : pos+2]))
  566. pos += 2
  567. // Warning count [16 bit uint]
  568. // bytesToUint16(data[pos : pos+2])
  569. return
  570. }
  571. /* Command Packet
  572. Bytes Name
  573. ----- ----
  574. 1 code
  575. 4 statement_id
  576. 1 flags
  577. 4 iteration_count
  578. if param_count > 0:
  579. (param_count+7)/8 null_bit_map
  580. 1 new_parameter_bound_flag
  581. if new_params_bound == 1:
  582. n*2 type of parameters
  583. n values for the parameters
  584. */
  585. func (stmt mysqlStmt) buildExecutePacket(args *[]driver.Value) (e error) {
  586. if len(*args) < stmt.paramCount {
  587. return fmt.Errorf(
  588. "Not enough Arguments to call STMT_EXEC (Got: %d Has: %d",
  589. len(*args),
  590. stmt.paramCount)
  591. }
  592. // Reset packet-sequence
  593. stmt.mc.sequence = 0
  594. data := make([]byte, 0, 10)
  595. // code [1 byte]
  596. data = append(data, byte(COM_STMT_EXECUTE))
  597. // statement_id [4 bytes]
  598. data = append(data, uint32ToBytes(stmt.id)...)
  599. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  600. data = append(data, byte(0))
  601. // iteration_count [4 bytes]
  602. data = append(data, uint32ToBytes(1)...)
  603. if stmt.paramCount > 0 {
  604. var i int
  605. // build nullBitMap
  606. nullBitMap := make([]byte, (stmt.paramCount+7)/8)
  607. bitMask := uint64(0)
  608. // Check for NULL fields
  609. for i = 0; i < stmt.paramCount; i++ {
  610. if (*args)[i] == nil {
  611. bitMask += 1 << uint(i)
  612. }
  613. }
  614. // Convert bitMask to bytes
  615. for i = 0; i < len(nullBitMap); i++ {
  616. nullBitMap[i] = byte(bitMask >> uint(i*8))
  617. }
  618. // append nullBitMap [(param_count+7)/8 bytes]
  619. data = append(data, nullBitMap...)
  620. // newParameterBoundFlag 1 [1 byte]
  621. data = append(data, byte(1))
  622. // append types and cache values
  623. paramValues := make([]byte, 0)
  624. var pv reflect.Value
  625. for i = 0; i < stmt.paramCount; i++ {
  626. switch (*args)[i].(type) {
  627. case nil:
  628. data = append(data, []byte{
  629. byte(FIELD_TYPE_NULL),
  630. 0x0}...)
  631. continue
  632. case []byte:
  633. data = append(data, []byte{
  634. byte(FIELD_TYPE_STRING),
  635. 0x0}...)
  636. val := (*args)[i].([]byte)
  637. paramValues = append(paramValues, lengthCodedBinaryToBytes(uint64(len(val)))...)
  638. paramValues = append(paramValues, val...)
  639. continue
  640. case time.Time:
  641. // Format to string for time+date Fields
  642. // Data is packed in case reflect.String below
  643. (*args)[i] = (*args)[i].(time.Time).Format(TIME_FORMAT)
  644. }
  645. pv = reflect.ValueOf((*args)[i])
  646. switch pv.Kind() {
  647. case reflect.Int64:
  648. data = append(data, []byte{
  649. byte(FIELD_TYPE_LONGLONG),
  650. 0x0}...)
  651. paramValues = append(paramValues, int64ToBytes(pv.Int())...)
  652. continue
  653. case reflect.Float64:
  654. data = append(data, []byte{
  655. byte(FIELD_TYPE_DOUBLE),
  656. 0x0}...)
  657. paramValues = append(paramValues, float64ToBytes(pv.Float())...)
  658. continue
  659. case reflect.Bool:
  660. data = append(data, []byte{
  661. byte(FIELD_TYPE_TINY),
  662. 0x0}...)
  663. val := pv.Bool()
  664. if val {
  665. paramValues = append(paramValues, byte(1))
  666. } else {
  667. paramValues = append(paramValues, byte(0))
  668. }
  669. continue
  670. case reflect.String:
  671. data = append(data, []byte{
  672. byte(FIELD_TYPE_STRING),
  673. 0x0}...)
  674. val := pv.String()
  675. paramValues = append(paramValues, lengthCodedBinaryToBytes(uint64(len(val)))...)
  676. paramValues = append(paramValues, []byte(val)...)
  677. continue
  678. default:
  679. return fmt.Errorf("Invalid Value: %s", pv.Kind().String())
  680. }
  681. }
  682. // append cached values
  683. data = append(data, paramValues...)
  684. }
  685. return stmt.mc.writePacket(data)
  686. }
  687. func (mc *mysqlConn) readBinaryRows(rc *rowsContent) (e error) {
  688. var data, nullBitMap []byte
  689. var i, pos, n int
  690. var unsigned, isNull bool
  691. columnsCount := len(rc.columns)
  692. for {
  693. data, e = mc.readPacket()
  694. if e != nil {
  695. return
  696. }
  697. pos = 0
  698. // EOF Packet
  699. if data[pos] == 254 && len(data) == 5 {
  700. return
  701. }
  702. pos++
  703. // BinaryRowSet Packet
  704. row := make([]*[]byte, columnsCount)
  705. nullBitMap = data[pos : pos+(columnsCount+7+2)/8]
  706. pos += (columnsCount + 7 + 2) / 8
  707. for i = 0; i < columnsCount; i++ {
  708. // Field is NULL
  709. if (nullBitMap[(i+2)/8] >> uint((i+2)%8) & 1) == 1 {
  710. row[i] = nil
  711. continue
  712. }
  713. unsigned = rc.columns[i].flags&FLAG_UNSIGNED != 0
  714. // Convert to byte-coded string
  715. switch rc.columns[i].fieldType {
  716. case FIELD_TYPE_NULL:
  717. row[i] = nil
  718. // Numeric Typs
  719. case FIELD_TYPE_TINY:
  720. if unsigned {
  721. row[i] = uintToByteStr(uint64(byteToUint8(data[pos])))
  722. } else {
  723. row[i] = intToByteStr(int64(int8(byteToUint8(data[pos]))))
  724. }
  725. pos++
  726. case FIELD_TYPE_SHORT, FIELD_TYPE_YEAR:
  727. if unsigned {
  728. row[i] = uintToByteStr(uint64(bytesToUint16(data[pos : pos+2])))
  729. } else {
  730. row[i] = intToByteStr(int64(int16(bytesToUint16(data[pos : pos+2]))))
  731. }
  732. pos += 2
  733. case FIELD_TYPE_INT24, FIELD_TYPE_LONG:
  734. if unsigned {
  735. row[i] = uintToByteStr(uint64(bytesToUint32(data[pos : pos+4])))
  736. } else {
  737. row[i] = intToByteStr(int64(int32(bytesToUint32(data[pos : pos+4]))))
  738. }
  739. pos += 4
  740. case FIELD_TYPE_LONGLONG:
  741. if unsigned {
  742. row[i] = uintToByteStr(bytesToUint64(data[pos : pos+8]))
  743. } else {
  744. row[i] = intToByteStr(int64(bytesToUint64(data[pos : pos+8])))
  745. }
  746. pos += 8
  747. case FIELD_TYPE_FLOAT:
  748. row[i] = float32ToByteStr(bytesToFloat32(data[pos : pos+4]))
  749. pos += 4
  750. case FIELD_TYPE_DOUBLE:
  751. row[i] = float64ToByteStr(bytesToFloat64(data[pos : pos+8]))
  752. pos += 8
  753. case FIELD_TYPE_DECIMAL, FIELD_TYPE_NEWDECIMAL:
  754. var tmp []byte
  755. tmp, n, isNull, e = readLengthCodedBinary(data[pos:])
  756. if e != nil {
  757. return
  758. }
  759. if isNull && rc.columns[i].flags&FLAG_NOT_NULL == 0 {
  760. row[i] = nil
  761. } else {
  762. row[i] = &tmp
  763. }
  764. pos += n
  765. // Length coded Binary Strings
  766. case FIELD_TYPE_VARCHAR, FIELD_TYPE_BIT, FIELD_TYPE_ENUM,
  767. FIELD_TYPE_SET, FIELD_TYPE_TINY_BLOB, FIELD_TYPE_MEDIUM_BLOB,
  768. FIELD_TYPE_LONG_BLOB, FIELD_TYPE_BLOB, FIELD_TYPE_VAR_STRING,
  769. FIELD_TYPE_STRING, FIELD_TYPE_GEOMETRY:
  770. var tmp []byte
  771. tmp, n, isNull, e = readLengthCodedBinary(data[pos:])
  772. if e != nil {
  773. return
  774. }
  775. if isNull && rc.columns[i].flags&FLAG_NOT_NULL == 0 {
  776. row[i] = nil
  777. } else {
  778. row[i] = &tmp
  779. }
  780. pos += n
  781. // Date YYYY-MM-DD
  782. case FIELD_TYPE_DATE, FIELD_TYPE_NEWDATE:
  783. var num uint64
  784. num, n, e = bytesToLengthCodedBinary(data[pos:])
  785. if e != nil {
  786. return
  787. }
  788. pos += n
  789. var tmp []byte
  790. if num == 0 {
  791. tmp = []byte("0000-00-00")
  792. } else {
  793. tmp = []byte(fmt.Sprintf("%04d-%02d-%02d",
  794. bytesToUint16(data[pos:pos+2]),
  795. data[pos+2],
  796. data[pos+3]))
  797. }
  798. row[i] = &tmp
  799. pos += int(num)
  800. // Time HH:MM:SS
  801. case FIELD_TYPE_TIME:
  802. var num uint64
  803. num, n, e = bytesToLengthCodedBinary(data[pos:])
  804. if e != nil {
  805. return
  806. }
  807. var tmp []byte
  808. if num == 0 {
  809. tmp = []byte("00:00:00")
  810. } else {
  811. tmp = []byte(fmt.Sprintf("%02d:%02d:%02d",
  812. data[pos+6],
  813. data[pos+7],
  814. data[pos+8]))
  815. }
  816. row[i] = &tmp
  817. pos += n + int(num)
  818. // Timestamp YYYY-MM-DD HH:MM:SS
  819. case FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  820. var num uint64
  821. num, n, e = bytesToLengthCodedBinary(data[pos:])
  822. if e != nil {
  823. return
  824. }
  825. pos += n
  826. var tmp []byte
  827. if num == 0 {
  828. tmp = []byte("0000-00-00 00:00:00")
  829. } else {
  830. tmp = []byte(fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d",
  831. bytesToUint16(data[pos:pos+2]),
  832. data[pos+2],
  833. data[pos+3],
  834. data[pos+4],
  835. data[pos+5],
  836. data[pos+6]))
  837. }
  838. row[i] = &tmp
  839. pos += int(num)
  840. // Please report if this happens!
  841. default:
  842. return fmt.Errorf("Unknown FieldType %d", rc.columns[i].fieldType)
  843. }
  844. }
  845. rc.rows = append(rc.rows, &row)
  846. }
  847. mc.affectedRows = uint64(len(rc.rows))
  848. return
  849. }