packets.go 24 KB

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