packets.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol
  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. // To specify a db name
  185. if len(mc.cfg.dbname) > 0 {
  186. clientFlags |= uint32(CLIENT_CONNECT_WITH_DB)
  187. }
  188. // User Password
  189. scrambleBuff := scramblePassword(mc.server.scrambleBuff, []byte(mc.cfg.passwd))
  190. // Calculate packet length and make buffer with that size
  191. pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff) + len(mc.cfg.dbname) + 1
  192. data := make([]byte, 0, pktLen+4)
  193. // Add the packet header
  194. data = append(data, uint24ToBytes(uint32(pktLen))...)
  195. data = append(data, mc.sequence)
  196. // ClientFlags
  197. data = append(data, uint32ToBytes(clientFlags)...)
  198. // MaxPacketSize
  199. data = append(data, uint32ToBytes(MAX_PACKET_SIZE)...)
  200. // Charset
  201. data = append(data, mc.server.charset)
  202. // Filler
  203. data = append(data, make([]byte, 23)...)
  204. // User
  205. if len(mc.cfg.user) > 0 {
  206. data = append(data, []byte(mc.cfg.user)...)
  207. }
  208. // Null-Terminator
  209. data = append(data, 0x0)
  210. // ScrambleBuffer
  211. data = append(data, byte(len(scrambleBuff)))
  212. if len(scrambleBuff) > 0 {
  213. data = append(data, scrambleBuff...)
  214. }
  215. // Databasename
  216. if len(mc.cfg.dbname) > 0 {
  217. data = append(data, []byte(mc.cfg.dbname)...)
  218. // Null-Terminator
  219. data = append(data, 0x0)
  220. }
  221. // Send Auth packet
  222. return mc.writePacket(&data)
  223. }
  224. /******************************************************************************
  225. * Command Packets *
  226. ******************************************************************************/
  227. /* Command Packet
  228. Bytes Name
  229. ----- ----
  230. 1 command
  231. n arg
  232. */
  233. func (mc *mysqlConn) writeCommandPacket(command commandType, args ...interface{}) (e error) {
  234. // Reset Packet Sequence
  235. mc.sequence = 0
  236. var arg []byte
  237. switch command {
  238. // Commands without args
  239. case COM_QUIT, COM_PING:
  240. if len(args) > 0 {
  241. return fmt.Errorf("Too much arguments (Got: %d Has: 0)", len(args))
  242. }
  243. arg = []byte{}
  244. // Commands with 1 arg unterminated string
  245. case COM_QUERY, COM_STMT_PREPARE:
  246. if len(args) != 1 {
  247. return fmt.Errorf("Invalid arguments count (Got: %d Has: 1)", len(args))
  248. }
  249. arg = []byte(args[0].(string))
  250. // Commands with 1 arg 32 bit uint
  251. case COM_STMT_CLOSE:
  252. if len(args) != 1 {
  253. return fmt.Errorf("Invalid arguments count (Got: %d Has: 1)", len(args))
  254. }
  255. arg = uint32ToBytes(args[0].(uint32))
  256. default:
  257. return fmt.Errorf("Unknown command: %d", command)
  258. }
  259. pktLen := 1 + len(arg)
  260. data := make([]byte, 0, pktLen+4)
  261. // Add the packet header
  262. data = append(data, uint24ToBytes(uint32(pktLen))...)
  263. data = append(data, mc.sequence)
  264. // Add command byte
  265. data = append(data, byte(command))
  266. // Add arg
  267. data = append(data, arg...)
  268. // Send CMD packet
  269. return mc.writePacket(&data)
  270. }
  271. /******************************************************************************
  272. * Result Packets *
  273. ******************************************************************************/
  274. // Returns error if Packet is not an 'Result OK'-Packet
  275. func (mc *mysqlConn) readResultOK() (e error) {
  276. data, e := mc.readPacket()
  277. if e != nil {
  278. return
  279. }
  280. switch data[0] {
  281. // OK
  282. case 0:
  283. return mc.handleOkPacket(data)
  284. // ERROR
  285. case 255:
  286. return mc.handleErrorPacket(data)
  287. default:
  288. e = errors.New("Invalid Result Packet-Type")
  289. return
  290. }
  291. return
  292. }
  293. /* Error Packet
  294. Bytes Name
  295. ----- ----
  296. 1 field_count, always = 0xff
  297. 2 errno
  298. 1 (sqlstate marker), always '#'
  299. 5 sqlstate (5 characters)
  300. n message
  301. */
  302. func (mc *mysqlConn) handleErrorPacket(data []byte) (e error) {
  303. if data[0] != 255 {
  304. e = errors.New("Wrong Packet-Type: Not an Error-Packet")
  305. return
  306. }
  307. pos := 1
  308. // Error Number [16 bit uint]
  309. errno := bytesToUint16(data[pos : pos+2])
  310. pos += 2
  311. // SQL State [# + 5bytes string]
  312. //sqlstate := string(data[pos : pos+6])
  313. pos += 6
  314. // Error Message [string]
  315. message := string(data[pos:])
  316. e = fmt.Errorf("Error %d: %s", errno, message)
  317. return
  318. }
  319. /* Ok Packet
  320. Bytes Name
  321. ----- ----
  322. 1 (Length Coded Binary) field_count, always = 0
  323. 1-9 (Length Coded Binary) affected_rows
  324. 1-9 (Length Coded Binary) insert_id
  325. 2 server_status
  326. 2 warning_count
  327. n (until end of packet) message
  328. */
  329. func (mc *mysqlConn) handleOkPacket(data []byte) (e error) {
  330. if data[0] != 0 {
  331. e = errors.New("Wrong Packet-Type: Not an OK-Packet")
  332. return
  333. }
  334. // Position
  335. pos := 1
  336. // Affected rows [Length Coded Binary]
  337. affectedRows, n, e := bytesToLengthCodedBinary(data[pos:])
  338. if e != nil {
  339. return
  340. }
  341. pos += n
  342. // Insert id [Length Coded Binary]
  343. insertID, n, e := bytesToLengthCodedBinary(data[pos:])
  344. if e != nil {
  345. return
  346. }
  347. // Skip remaining data
  348. mc.affectedRows = affectedRows
  349. mc.insertId = insertID
  350. return
  351. }
  352. /* Result Set Header Packet
  353. Bytes Name
  354. ----- ----
  355. 1-9 (Length-Coded-Binary) field_count
  356. 1-9 (Length-Coded-Binary) extra
  357. The order of packets for a result set is:
  358. (Result Set Header Packet) the number of columns
  359. (Field Packets) column descriptors
  360. (EOF Packet) marker: end of Field Packets
  361. (Row Data Packets) row contents
  362. (EOF Packet) marker: end of Data Packets
  363. */
  364. func (mc *mysqlConn) readResultSetHeaderPacket() (fieldCount int, e error) {
  365. data, e := mc.readPacket()
  366. if e != nil {
  367. errLog.Print(`packets:437 `, e)
  368. e = driver.ErrBadConn
  369. return
  370. }
  371. if data[0] == 255 {
  372. e = mc.handleErrorPacket(data)
  373. return
  374. } else if data[0] == 0 {
  375. e = mc.handleOkPacket(data)
  376. return
  377. }
  378. num, n, e := bytesToLengthCodedBinary(data)
  379. if e != nil || (n-len(data)) != 0 {
  380. e = errors.New("Malformed Packet")
  381. return
  382. }
  383. fieldCount = int(num)
  384. return
  385. }
  386. // Read Packets as Field Packets until EOF-Packet or an Error appears
  387. func (mc *mysqlConn) readColumns(n int) (columns []mysqlField, e error) {
  388. var data []byte
  389. for {
  390. data, e = mc.readPacket()
  391. if e != nil {
  392. return
  393. }
  394. // EOF Packet
  395. if data[0] == 254 && len(data) == 5 {
  396. if len(columns) != n {
  397. e = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", n, len(columns))
  398. }
  399. return
  400. }
  401. var pos, n int
  402. var name []byte
  403. //var catalog, database, table, orgTable, name, orgName []byte
  404. //var defaultVal uint64
  405. // Catalog
  406. //catalog, n, _, e = readLengthCodedBinary(data)
  407. n, e = readAndDropLengthCodedBinary(data)
  408. if e != nil {
  409. return
  410. }
  411. pos += n
  412. // Database [len coded string]
  413. //database, n, _, e = readLengthCodedBinary(data[pos:])
  414. n, e = readAndDropLengthCodedBinary(data[pos:])
  415. if e != nil {
  416. return
  417. }
  418. pos += n
  419. // Table [len coded string]
  420. //table, n, _, e = readLengthCodedBinary(data[pos:])
  421. n, e = readAndDropLengthCodedBinary(data[pos:])
  422. if e != nil {
  423. return
  424. }
  425. pos += n
  426. // Original table [len coded string]
  427. //orgTable, n, _, e = readLengthCodedBinary(data[pos:])
  428. n, e = readAndDropLengthCodedBinary(data[pos:])
  429. if e != nil {
  430. return
  431. }
  432. pos += n
  433. // Name [len coded string]
  434. name, n, _, e = readLengthCodedBinary(data[pos:])
  435. if e != nil {
  436. return
  437. }
  438. pos += n
  439. // Original name [len coded string]
  440. //orgName, n, _, e = readLengthCodedBinary(data[pos:])
  441. n, e = readAndDropLengthCodedBinary(data[pos:])
  442. if e != nil {
  443. return
  444. }
  445. pos += n
  446. // Filler
  447. pos++
  448. // Charset [16 bit uint]
  449. //charsetNumber := bytesToUint16(data[pos : pos+2])
  450. pos += 2
  451. // Length [32 bit uint]
  452. //length := bytesToUint32(data[pos : pos+4])
  453. pos += 4
  454. // Field type [byte]
  455. fieldType := FieldType(data[pos])
  456. pos++
  457. // Flags [16 bit uint]
  458. flags := FieldFlag(bytesToUint16(data[pos : pos+2]))
  459. //pos += 2
  460. // Decimals [8 bit uint]
  461. //decimals := data[pos]
  462. //pos++
  463. // Default value [len coded binary]
  464. //if pos < len(data) {
  465. // defaultVal, _, e = bytesToLengthCodedBinary(data[pos:])
  466. //}
  467. columns = append(columns, mysqlField{name: string(name), fieldType: fieldType, flags: flags})
  468. }
  469. return
  470. }
  471. // Read Packets as Field Packets until EOF-Packet or an Error appears
  472. func (mc *mysqlConn) readRows(columnsCount int) (rows []*[][]byte, e error) {
  473. var data []byte
  474. var i, pos, n int
  475. var isNull bool
  476. for {
  477. data, e = mc.readPacket()
  478. if e != nil {
  479. return
  480. }
  481. // EOF Packet
  482. if data[0] == 254 && len(data) == 5 {
  483. return
  484. }
  485. // RowSet Packet
  486. row := make([][]byte, columnsCount)
  487. pos = 0
  488. for i = 0; i < columnsCount; i++ {
  489. // Read bytes and convert to string
  490. row[i], n, isNull, e = readLengthCodedBinary(data[pos:])
  491. if e != nil {
  492. return
  493. }
  494. // Append nil if field is NULL
  495. if isNull {
  496. row[i] = nil
  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. argsLen := len(*args)
  587. if argsLen < stmt.paramCount {
  588. return fmt.Errorf(
  589. "Not enough Arguments to call STMT_EXEC (Got: %d Has: %d",
  590. argsLen,
  591. stmt.paramCount)
  592. }
  593. // Reset packet-sequence
  594. stmt.mc.sequence = 0
  595. pktLen := 1 + 4 + 1 + 4 + (stmt.paramCount+7)/8 + 1 + argsLen*2
  596. paramValues := make([][]byte, 0, argsLen)
  597. paramTypes := make([]byte, 0, argsLen*2)
  598. bitMask := uint64(0)
  599. var i, valLen int
  600. var pv reflect.Value
  601. for i = 0; i < stmt.paramCount; i++ {
  602. // build nullBitMap
  603. if (*args)[i] == nil {
  604. bitMask += 1 << uint(i)
  605. }
  606. // cache types and values
  607. switch (*args)[i].(type) {
  608. case nil:
  609. paramTypes = append(paramTypes, []byte{
  610. byte(FIELD_TYPE_NULL),
  611. 0x0}...)
  612. continue
  613. case []byte:
  614. paramTypes = append(paramTypes, []byte{byte(FIELD_TYPE_STRING), 0x0}...)
  615. val := (*args)[i].([]byte)
  616. valLen = len(val)
  617. lcb := lengthCodedBinaryToBytes(uint64(valLen))
  618. pktLen += len(lcb) + valLen
  619. paramValues = append(paramValues, lcb)
  620. paramValues = append(paramValues, val)
  621. continue
  622. case time.Time:
  623. // Format to string for time+date Fields
  624. // Data is packed in case reflect.String below
  625. (*args)[i] = (*args)[i].(time.Time).Format(TIME_FORMAT)
  626. }
  627. pv = reflect.ValueOf((*args)[i])
  628. switch pv.Kind() {
  629. case reflect.Int64:
  630. paramTypes = append(paramTypes, []byte{byte(FIELD_TYPE_LONGLONG), 0x0}...)
  631. val := int64ToBytes(pv.Int())
  632. pktLen += len(val)
  633. paramValues = append(paramValues, val)
  634. continue
  635. case reflect.Float64:
  636. paramTypes = append(paramTypes, []byte{byte(FIELD_TYPE_DOUBLE), 0x0}...)
  637. val := float64ToBytes(pv.Float())
  638. pktLen += len(val)
  639. paramValues = append(paramValues, val)
  640. continue
  641. case reflect.Bool:
  642. paramTypes = append(paramTypes, []byte{byte(FIELD_TYPE_TINY), 0x0}...)
  643. val := pv.Bool()
  644. pktLen++
  645. if val {
  646. paramValues = append(paramValues, []byte{byte(1)})
  647. } else {
  648. paramValues = append(paramValues, []byte{byte(0)})
  649. }
  650. continue
  651. case reflect.String:
  652. paramTypes = append(paramTypes, []byte{byte(FIELD_TYPE_STRING), 0x0}...)
  653. val := []byte(pv.String())
  654. valLen = len(val)
  655. lcb := lengthCodedBinaryToBytes(uint64(valLen))
  656. pktLen += valLen + len(lcb)
  657. paramValues = append(paramValues, lcb)
  658. paramValues = append(paramValues, val)
  659. continue
  660. default:
  661. return fmt.Errorf("Invalid Value: %s", pv.Kind().String())
  662. }
  663. }
  664. data := make([]byte, 0, pktLen+4)
  665. // Add the packet header
  666. data = append(data, uint24ToBytes(uint32(pktLen))...)
  667. data = append(data, stmt.mc.sequence)
  668. // code [1 byte]
  669. data = append(data, byte(COM_STMT_EXECUTE))
  670. // statement_id [4 bytes]
  671. data = append(data, uint32ToBytes(stmt.id)...)
  672. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  673. data = append(data, byte(0))
  674. // iteration_count [4 bytes]
  675. data = append(data, uint32ToBytes(1)...)
  676. // append nullBitMap [(param_count+7)/8 bytes]
  677. if stmt.paramCount > 0 {
  678. // Convert bitMask to bytes
  679. nullBitMap := make([]byte, (stmt.paramCount+7)/8)
  680. for i = 0; i < len(nullBitMap); i++ {
  681. nullBitMap[i] = byte(bitMask >> uint(i*8))
  682. }
  683. data = append(data, nullBitMap...)
  684. }
  685. // newParameterBoundFlag 1 [1 byte]
  686. data = append(data, byte(1))
  687. // type of parameters [n*2 byte]
  688. data = append(data, paramTypes...)
  689. // values for the parameters [n byte]
  690. for _, paramValue := range paramValues {
  691. data = append(data, paramValue...)
  692. }
  693. return stmt.mc.writePacket(&data)
  694. }
  695. func (mc *mysqlConn) readBinaryRows(rc *rowsContent) (e error) {
  696. var data, nullBitMap []byte
  697. var i, pos, n int
  698. var unsigned, isNull bool
  699. columnsCount := len(rc.columns)
  700. for {
  701. data, e = mc.readPacket()
  702. if e != nil {
  703. return
  704. }
  705. pos = 0
  706. // EOF Packet
  707. if data[pos] == 254 && len(data) == 5 {
  708. return
  709. }
  710. pos++
  711. // BinaryRowSet Packet
  712. row := make([][]byte, columnsCount)
  713. nullBitMap = data[pos : pos+(columnsCount+7+2)/8]
  714. pos += (columnsCount + 7 + 2) / 8
  715. for i = 0; i < columnsCount; i++ {
  716. // Field is NULL
  717. if (nullBitMap[(i+2)/8] >> uint((i+2)%8) & 1) == 1 {
  718. row[i] = nil
  719. continue
  720. }
  721. unsigned = rc.columns[i].flags&FLAG_UNSIGNED != 0
  722. // Convert to byte-coded string
  723. switch rc.columns[i].fieldType {
  724. case FIELD_TYPE_NULL:
  725. row[i] = nil
  726. // Numeric Typs
  727. case FIELD_TYPE_TINY:
  728. if unsigned {
  729. row[i] = uintToByteStr(uint64(byteToUint8(data[pos])))
  730. } else {
  731. row[i] = intToByteStr(int64(int8(byteToUint8(data[pos]))))
  732. }
  733. pos++
  734. case FIELD_TYPE_SHORT, FIELD_TYPE_YEAR:
  735. if unsigned {
  736. row[i] = uintToByteStr(uint64(bytesToUint16(data[pos : pos+2])))
  737. } else {
  738. row[i] = intToByteStr(int64(int16(bytesToUint16(data[pos : pos+2]))))
  739. }
  740. pos += 2
  741. case FIELD_TYPE_INT24, FIELD_TYPE_LONG:
  742. if unsigned {
  743. row[i] = uintToByteStr(uint64(bytesToUint32(data[pos : pos+4])))
  744. } else {
  745. row[i] = intToByteStr(int64(int32(bytesToUint32(data[pos : pos+4]))))
  746. }
  747. pos += 4
  748. case FIELD_TYPE_LONGLONG:
  749. if unsigned {
  750. row[i] = uintToByteStr(bytesToUint64(data[pos : pos+8]))
  751. } else {
  752. row[i] = intToByteStr(int64(bytesToUint64(data[pos : pos+8])))
  753. }
  754. pos += 8
  755. case FIELD_TYPE_FLOAT:
  756. row[i] = float32ToByteStr(bytesToFloat32(data[pos : pos+4]))
  757. pos += 4
  758. case FIELD_TYPE_DOUBLE:
  759. row[i] = float64ToByteStr(bytesToFloat64(data[pos : pos+8]))
  760. pos += 8
  761. case FIELD_TYPE_DECIMAL, FIELD_TYPE_NEWDECIMAL:
  762. row[i], n, isNull, e = readLengthCodedBinary(data[pos:])
  763. if e != nil {
  764. return
  765. }
  766. if isNull && rc.columns[i].flags&FLAG_NOT_NULL == 0 {
  767. row[i] = nil
  768. }
  769. pos += n
  770. // Length coded Binary Strings
  771. case FIELD_TYPE_VARCHAR, FIELD_TYPE_BIT, FIELD_TYPE_ENUM,
  772. FIELD_TYPE_SET, FIELD_TYPE_TINY_BLOB, FIELD_TYPE_MEDIUM_BLOB,
  773. FIELD_TYPE_LONG_BLOB, FIELD_TYPE_BLOB, FIELD_TYPE_VAR_STRING,
  774. FIELD_TYPE_STRING, FIELD_TYPE_GEOMETRY:
  775. row[i], n, isNull, e = readLengthCodedBinary(data[pos:])
  776. if e != nil {
  777. return
  778. }
  779. if isNull && rc.columns[i].flags&FLAG_NOT_NULL == 0 {
  780. row[i] = nil
  781. }
  782. pos += n
  783. // Date YYYY-MM-DD
  784. case FIELD_TYPE_DATE, FIELD_TYPE_NEWDATE:
  785. var num uint64
  786. num, n, e = bytesToLengthCodedBinary(data[pos:])
  787. if e != nil {
  788. return
  789. }
  790. pos += n
  791. if num == 0 {
  792. row[i] = []byte("0000-00-00")
  793. } else {
  794. row[i] = []byte(fmt.Sprintf("%04d-%02d-%02d",
  795. bytesToUint16(data[pos:pos+2]),
  796. data[pos+2],
  797. data[pos+3]))
  798. }
  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. if num == 0 {
  808. row[i] = []byte("00:00:00")
  809. } else {
  810. row[i] = []byte(fmt.Sprintf("%02d:%02d:%02d",
  811. data[pos+6],
  812. data[pos+7],
  813. data[pos+8]))
  814. }
  815. pos += n + int(num)
  816. // Timestamp YYYY-MM-DD HH:MM:SS
  817. case FIELD_TYPE_TIMESTAMP, FIELD_TYPE_DATETIME:
  818. var num uint64
  819. num, n, e = bytesToLengthCodedBinary(data[pos:])
  820. if e != nil {
  821. return
  822. }
  823. pos += n
  824. switch num {
  825. case 0:
  826. row[i] = []byte("0000-00-00 00:00:00")
  827. case 4:
  828. row[i] = []byte(fmt.Sprintf("%04d-%02d-%02d 00:00:00",
  829. bytesToUint16(data[pos:pos+2]),
  830. data[pos+2],
  831. data[pos+3]))
  832. default:
  833. if num < 7 {
  834. return fmt.Errorf("Invalid datetime-packet length %d", num)
  835. }
  836. row[i] = []byte(fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d",
  837. bytesToUint16(data[pos:pos+2]),
  838. data[pos+2],
  839. data[pos+3],
  840. data[pos+4],
  841. data[pos+5],
  842. data[pos+6]))
  843. }
  844. pos += int(num)
  845. // Please report if this happens!
  846. default:
  847. return fmt.Errorf("Unknown FieldType %d", rc.columns[i].fieldType)
  848. }
  849. }
  850. rc.rows = append(rc.rows, &row)
  851. }
  852. mc.affectedRows = uint64(len(rc.rows))
  853. return
  854. }