packets.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "bytes"
  11. "crypto/tls"
  12. "database/sql/driver"
  13. "encoding/binary"
  14. "encoding/json"
  15. "fmt"
  16. "io"
  17. "math"
  18. "strconv"
  19. "time"
  20. )
  21. // Packets documentation:
  22. // http://dev.mysql.com/doc/internals/en/client-server-protocol.html
  23. // Read packet to buffer 'data'
  24. func (mc *mysqlConn) readPacket() ([]byte, error) {
  25. var prevData []byte
  26. for {
  27. // read packet header
  28. data, err := mc.buf.readNext(4)
  29. if err != nil {
  30. if cerr := mc.canceled.Value(); cerr != nil {
  31. return nil, cerr
  32. }
  33. mc.log(err)
  34. mc.Close()
  35. return nil, ErrInvalidConn
  36. }
  37. // packet length [24 bit]
  38. pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16)
  39. // check packet sync [8 bit]
  40. if data[3] != mc.sequence {
  41. mc.Close()
  42. if data[3] > mc.sequence {
  43. return nil, ErrPktSyncMul
  44. }
  45. return nil, ErrPktSync
  46. }
  47. mc.sequence++
  48. // packets with length 0 terminate a previous packet which is a
  49. // multiple of (2^24)-1 bytes long
  50. if pktLen == 0 {
  51. // there was no previous packet
  52. if prevData == nil {
  53. mc.log(ErrMalformPkt)
  54. mc.Close()
  55. return nil, ErrInvalidConn
  56. }
  57. return prevData, nil
  58. }
  59. // read packet body [pktLen bytes]
  60. data, err = mc.buf.readNext(pktLen)
  61. if err != nil {
  62. if cerr := mc.canceled.Value(); cerr != nil {
  63. return nil, cerr
  64. }
  65. mc.log(err)
  66. mc.Close()
  67. return nil, ErrInvalidConn
  68. }
  69. // return data if this was the last packet
  70. if pktLen < maxPacketSize {
  71. // zero allocations for non-split packets
  72. if prevData == nil {
  73. return data, nil
  74. }
  75. return append(prevData, data...), nil
  76. }
  77. prevData = append(prevData, data...)
  78. }
  79. }
  80. // Write packet buffer 'data'
  81. func (mc *mysqlConn) writePacket(data []byte) error {
  82. pktLen := len(data) - 4
  83. if pktLen > mc.maxAllowedPacket {
  84. return ErrPktTooLarge
  85. }
  86. for {
  87. var size int
  88. if pktLen >= maxPacketSize {
  89. data[0] = 0xff
  90. data[1] = 0xff
  91. data[2] = 0xff
  92. size = maxPacketSize
  93. } else {
  94. data[0] = byte(pktLen)
  95. data[1] = byte(pktLen >> 8)
  96. data[2] = byte(pktLen >> 16)
  97. size = pktLen
  98. }
  99. data[3] = mc.sequence
  100. // Write packet
  101. if mc.writeTimeout > 0 {
  102. if err := mc.netConn.SetWriteDeadline(time.Now().Add(mc.writeTimeout)); err != nil {
  103. return err
  104. }
  105. }
  106. n, err := mc.netConn.Write(data[:4+size])
  107. if err == nil && n == 4+size {
  108. mc.sequence++
  109. if size != maxPacketSize {
  110. return nil
  111. }
  112. pktLen -= size
  113. data = data[size:]
  114. continue
  115. }
  116. // Handle error
  117. if err == nil { // n != len(data)
  118. mc.cleanup()
  119. mc.log(ErrMalformPkt)
  120. } else {
  121. if cerr := mc.canceled.Value(); cerr != nil {
  122. return cerr
  123. }
  124. if n == 0 && pktLen == len(data)-4 {
  125. // only for the first loop iteration when nothing was written yet
  126. return errBadConnNoWrite
  127. }
  128. mc.cleanup()
  129. mc.log(err)
  130. }
  131. return ErrInvalidConn
  132. }
  133. }
  134. /******************************************************************************
  135. * Initialization Process *
  136. ******************************************************************************/
  137. // Handshake Initialization Packet
  138. // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake
  139. func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err error) {
  140. data, err = mc.readPacket()
  141. if err != nil {
  142. // for init we can rewrite this to ErrBadConn for sql.Driver to retry, since
  143. // in connection initialization we don't risk retrying non-idempotent actions.
  144. if err == ErrInvalidConn {
  145. return nil, "", driver.ErrBadConn
  146. }
  147. return
  148. }
  149. if data[0] == iERR {
  150. return nil, "", mc.handleErrorPacket(data)
  151. }
  152. // protocol version [1 byte]
  153. if data[0] < minProtocolVersion {
  154. return nil, "", fmt.Errorf(
  155. "unsupported protocol version %d. Version %d or higher is required",
  156. data[0],
  157. minProtocolVersion,
  158. )
  159. }
  160. // server version [null terminated string]
  161. // connection id [4 bytes]
  162. pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4
  163. // first part of the password cipher [8 bytes]
  164. authData := data[pos : pos+8]
  165. // (filler) always 0x00 [1 byte]
  166. pos += 8 + 1
  167. // capability flags (lower 2 bytes) [2 bytes]
  168. mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  169. if mc.flags&clientProtocol41 == 0 {
  170. return nil, "", ErrOldProtocol
  171. }
  172. if mc.flags&clientSSL == 0 && mc.cfg.TLS != nil {
  173. if mc.cfg.AllowFallbackToPlaintext {
  174. mc.cfg.TLS = nil
  175. } else {
  176. return nil, "", ErrNoTLS
  177. }
  178. }
  179. pos += 2
  180. if len(data) > pos {
  181. // character set [1 byte]
  182. // status flags [2 bytes]
  183. // capability flags (upper 2 bytes) [2 bytes]
  184. // length of auth-plugin-data [1 byte]
  185. // reserved (all [00]) [10 bytes]
  186. pos += 1 + 2 + 2 + 1 + 10
  187. // second part of the password cipher [minimum 13 bytes],
  188. // where len=MAX(13, length of auth-plugin-data - 8)
  189. //
  190. // The web documentation is ambiguous about the length. However,
  191. // according to mysql-5.7/sql/auth/sql_authentication.cc line 538,
  192. // the 13th byte is "\0 byte, terminating the second part of
  193. // a scramble". So the second part of the password cipher is
  194. // a NULL terminated string that's at least 13 bytes with the
  195. // last byte being NULL.
  196. //
  197. // The official Python library uses the fixed length 12
  198. // which seems to work but technically could have a hidden bug.
  199. authData = append(authData, data[pos:pos+12]...)
  200. pos += 13
  201. // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2)
  202. // \NUL otherwise
  203. if end := bytes.IndexByte(data[pos:], 0x00); end != -1 {
  204. plugin = string(data[pos : pos+end])
  205. } else {
  206. plugin = string(data[pos:])
  207. }
  208. // make a memory safe copy of the cipher slice
  209. var b [20]byte
  210. copy(b[:], authData)
  211. return b[:], plugin, nil
  212. }
  213. // make a memory safe copy of the cipher slice
  214. var b [8]byte
  215. copy(b[:], authData)
  216. return b[:], plugin, nil
  217. }
  218. // Client Authentication Packet
  219. // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse
  220. func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error {
  221. // Adjust client flags based on server support
  222. clientFlags := clientProtocol41 |
  223. clientSecureConn |
  224. clientLongPassword |
  225. clientTransactions |
  226. clientLocalFiles |
  227. clientPluginAuth |
  228. clientMultiResults |
  229. clientConnectAttrs |
  230. mc.flags&clientLongFlag
  231. if mc.cfg.ClientFoundRows {
  232. clientFlags |= clientFoundRows
  233. }
  234. // To enable TLS / SSL
  235. if mc.cfg.TLS != nil {
  236. clientFlags |= clientSSL
  237. }
  238. if mc.cfg.MultiStatements {
  239. clientFlags |= clientMultiStatements
  240. }
  241. // encode length of the auth plugin data
  242. var authRespLEIBuf [9]byte
  243. authRespLen := len(authResp)
  244. authRespLEI := appendLengthEncodedInteger(authRespLEIBuf[:0], uint64(authRespLen))
  245. if len(authRespLEI) > 1 {
  246. // if the length can not be written in 1 byte, it must be written as a
  247. // length encoded integer
  248. clientFlags |= clientPluginAuthLenEncClientData
  249. }
  250. pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1 + len(authRespLEI) + len(authResp) + 21 + 1
  251. // To specify a db name
  252. if n := len(mc.cfg.DBName); n > 0 {
  253. clientFlags |= clientConnectWithDB
  254. pktLen += n + 1
  255. }
  256. // encode length of the connection attributes
  257. var connAttrsLEIBuf [9]byte
  258. connAttrsLen := len(mc.connector.encodedAttributes)
  259. connAttrsLEI := appendLengthEncodedInteger(connAttrsLEIBuf[:0], uint64(connAttrsLen))
  260. pktLen += len(connAttrsLEI) + len(mc.connector.encodedAttributes)
  261. // Calculate packet length and get buffer with that size
  262. data, err := mc.buf.takeBuffer(pktLen + 4)
  263. if err != nil {
  264. // cannot take the buffer. Something must be wrong with the connection
  265. mc.log(err)
  266. return errBadConnNoWrite
  267. }
  268. // ClientFlags [32 bit]
  269. data[4] = byte(clientFlags)
  270. data[5] = byte(clientFlags >> 8)
  271. data[6] = byte(clientFlags >> 16)
  272. data[7] = byte(clientFlags >> 24)
  273. // MaxPacketSize [32 bit] (none)
  274. data[8] = 0x00
  275. data[9] = 0x00
  276. data[10] = 0x00
  277. data[11] = 0x00
  278. // Collation ID [1 byte]
  279. cname := mc.cfg.Collation
  280. if cname == "" {
  281. cname = defaultCollation
  282. }
  283. var found bool
  284. data[12], found = collations[cname]
  285. if !found {
  286. // Note possibility for false negatives:
  287. // could be triggered although the collation is valid if the
  288. // collations map does not contain entries the server supports.
  289. return fmt.Errorf("unknown collation: %q", cname)
  290. }
  291. // Filler [23 bytes] (all 0x00)
  292. pos := 13
  293. for ; pos < 13+23; pos++ {
  294. data[pos] = 0
  295. }
  296. // SSL Connection Request Packet
  297. // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest
  298. if mc.cfg.TLS != nil {
  299. // Send TLS / SSL request packet
  300. if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil {
  301. return err
  302. }
  303. // Switch to TLS
  304. tlsConn := tls.Client(mc.netConn, mc.cfg.TLS)
  305. if err := tlsConn.Handshake(); err != nil {
  306. return err
  307. }
  308. mc.netConn = tlsConn
  309. mc.buf.nc = tlsConn
  310. }
  311. // User [null terminated string]
  312. if len(mc.cfg.User) > 0 {
  313. pos += copy(data[pos:], mc.cfg.User)
  314. }
  315. data[pos] = 0x00
  316. pos++
  317. // Auth Data [length encoded integer]
  318. pos += copy(data[pos:], authRespLEI)
  319. pos += copy(data[pos:], authResp)
  320. // Databasename [null terminated string]
  321. if len(mc.cfg.DBName) > 0 {
  322. pos += copy(data[pos:], mc.cfg.DBName)
  323. data[pos] = 0x00
  324. pos++
  325. }
  326. pos += copy(data[pos:], plugin)
  327. data[pos] = 0x00
  328. pos++
  329. // Connection Attributes
  330. pos += copy(data[pos:], connAttrsLEI)
  331. pos += copy(data[pos:], []byte(mc.connector.encodedAttributes))
  332. // Send Auth packet
  333. return mc.writePacket(data[:pos])
  334. }
  335. // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse
  336. func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error {
  337. pktLen := 4 + len(authData)
  338. data, err := mc.buf.takeSmallBuffer(pktLen)
  339. if err != nil {
  340. // cannot take the buffer. Something must be wrong with the connection
  341. mc.log(err)
  342. return errBadConnNoWrite
  343. }
  344. // Add the auth data [EOF]
  345. copy(data[4:], authData)
  346. return mc.writePacket(data)
  347. }
  348. /******************************************************************************
  349. * Command Packets *
  350. ******************************************************************************/
  351. func (mc *mysqlConn) writeCommandPacket(command byte) error {
  352. // Reset Packet Sequence
  353. mc.sequence = 0
  354. data, err := mc.buf.takeSmallBuffer(4 + 1)
  355. if err != nil {
  356. // cannot take the buffer. Something must be wrong with the connection
  357. mc.log(err)
  358. return errBadConnNoWrite
  359. }
  360. // Add command byte
  361. data[4] = command
  362. // Send CMD packet
  363. return mc.writePacket(data)
  364. }
  365. func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error {
  366. // Reset Packet Sequence
  367. mc.sequence = 0
  368. pktLen := 1 + len(arg)
  369. data, err := mc.buf.takeBuffer(pktLen + 4)
  370. if err != nil {
  371. // cannot take the buffer. Something must be wrong with the connection
  372. mc.log(err)
  373. return errBadConnNoWrite
  374. }
  375. // Add command byte
  376. data[4] = command
  377. // Add arg
  378. copy(data[5:], arg)
  379. // Send CMD packet
  380. return mc.writePacket(data)
  381. }
  382. func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error {
  383. // Reset Packet Sequence
  384. mc.sequence = 0
  385. data, err := mc.buf.takeSmallBuffer(4 + 1 + 4)
  386. if err != nil {
  387. // cannot take the buffer. Something must be wrong with the connection
  388. mc.log(err)
  389. return errBadConnNoWrite
  390. }
  391. // Add command byte
  392. data[4] = command
  393. // Add arg [32 bit]
  394. data[5] = byte(arg)
  395. data[6] = byte(arg >> 8)
  396. data[7] = byte(arg >> 16)
  397. data[8] = byte(arg >> 24)
  398. // Send CMD packet
  399. return mc.writePacket(data)
  400. }
  401. /******************************************************************************
  402. * Result Packets *
  403. ******************************************************************************/
  404. func (mc *mysqlConn) readAuthResult() ([]byte, string, error) {
  405. data, err := mc.readPacket()
  406. if err != nil {
  407. return nil, "", err
  408. }
  409. // packet indicator
  410. switch data[0] {
  411. case iOK:
  412. // resultUnchanged, since auth happens before any queries or
  413. // commands have been executed.
  414. return nil, "", mc.resultUnchanged().handleOkPacket(data)
  415. case iAuthMoreData:
  416. return data[1:], "", err
  417. case iEOF:
  418. if len(data) == 1 {
  419. // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest
  420. return nil, "mysql_old_password", nil
  421. }
  422. pluginEndIndex := bytes.IndexByte(data, 0x00)
  423. if pluginEndIndex < 0 {
  424. return nil, "", ErrMalformPkt
  425. }
  426. plugin := string(data[1:pluginEndIndex])
  427. authData := data[pluginEndIndex+1:]
  428. return authData, plugin, nil
  429. default: // Error otherwise
  430. return nil, "", mc.handleErrorPacket(data)
  431. }
  432. }
  433. // Returns error if Packet is not a 'Result OK'-Packet
  434. func (mc *okHandler) readResultOK() error {
  435. data, err := mc.conn().readPacket()
  436. if err != nil {
  437. return err
  438. }
  439. if data[0] == iOK {
  440. return mc.handleOkPacket(data)
  441. }
  442. return mc.conn().handleErrorPacket(data)
  443. }
  444. // Result Set Header Packet
  445. // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset
  446. func (mc *okHandler) readResultSetHeaderPacket() (int, error) {
  447. // handleOkPacket replaces both values; other cases leave the values unchanged.
  448. mc.result.affectedRows = append(mc.result.affectedRows, 0)
  449. mc.result.insertIds = append(mc.result.insertIds, 0)
  450. data, err := mc.conn().readPacket()
  451. if err == nil {
  452. switch data[0] {
  453. case iOK:
  454. return 0, mc.handleOkPacket(data)
  455. case iERR:
  456. return 0, mc.conn().handleErrorPacket(data)
  457. case iLocalInFile:
  458. return 0, mc.handleInFileRequest(string(data[1:]))
  459. }
  460. // column count
  461. num, _, _ := readLengthEncodedInteger(data)
  462. // ignore remaining data in the packet. see #1478.
  463. return int(num), nil
  464. }
  465. return 0, err
  466. }
  467. // Error Packet
  468. // http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-ERR_Packet
  469. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  470. if data[0] != iERR {
  471. return ErrMalformPkt
  472. }
  473. // 0xff [1 byte]
  474. // Error Number [16 bit uint]
  475. errno := binary.LittleEndian.Uint16(data[1:3])
  476. // 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION
  477. // 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover)
  478. if (errno == 1792 || errno == 1290) && mc.cfg.RejectReadOnly {
  479. // Oops; we are connected to a read-only connection, and won't be able
  480. // to issue any write statements. Since RejectReadOnly is configured,
  481. // we throw away this connection hoping this one would have write
  482. // permission. This is specifically for a possible race condition
  483. // during failover (e.g. on AWS Aurora). See README.md for more.
  484. //
  485. // We explicitly close the connection before returning
  486. // driver.ErrBadConn to ensure that `database/sql` purges this
  487. // connection and initiates a new one for next statement next time.
  488. mc.Close()
  489. return driver.ErrBadConn
  490. }
  491. me := &MySQLError{Number: errno}
  492. pos := 3
  493. // SQL State [optional: # + 5bytes string]
  494. if data[3] == 0x23 {
  495. copy(me.SQLState[:], data[4:4+5])
  496. pos = 9
  497. }
  498. // Error Message [string]
  499. me.Message = string(data[pos:])
  500. return me
  501. }
  502. func readStatus(b []byte) statusFlag {
  503. return statusFlag(b[0]) | statusFlag(b[1])<<8
  504. }
  505. // Returns an instance of okHandler for codepaths where mysqlConn.result doesn't
  506. // need to be cleared first (e.g. during authentication, or while additional
  507. // resultsets are being fetched.)
  508. func (mc *mysqlConn) resultUnchanged() *okHandler {
  509. return (*okHandler)(mc)
  510. }
  511. // okHandler represents the state of the connection when mysqlConn.result has
  512. // been prepared for processing of OK packets.
  513. //
  514. // To correctly populate mysqlConn.result (updated by handleOkPacket()), all
  515. // callpaths must either:
  516. //
  517. // 1. first clear it using clearResult(), or
  518. // 2. confirm that they don't need to (by calling resultUnchanged()).
  519. //
  520. // Both return an instance of type *okHandler.
  521. type okHandler mysqlConn
  522. // Exposes the underlying type's methods.
  523. func (mc *okHandler) conn() *mysqlConn {
  524. return (*mysqlConn)(mc)
  525. }
  526. // clearResult clears the connection's stored affectedRows and insertIds
  527. // fields.
  528. //
  529. // It returns a handler that can process OK responses.
  530. func (mc *mysqlConn) clearResult() *okHandler {
  531. mc.result = mysqlResult{}
  532. return (*okHandler)(mc)
  533. }
  534. // Ok Packet
  535. // http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet
  536. func (mc *okHandler) handleOkPacket(data []byte) error {
  537. var n, m int
  538. var affectedRows, insertId uint64
  539. // 0x00 [1 byte]
  540. // Affected rows [Length Coded Binary]
  541. affectedRows, _, n = readLengthEncodedInteger(data[1:])
  542. // Insert id [Length Coded Binary]
  543. insertId, _, m = readLengthEncodedInteger(data[1+n:])
  544. // Update for the current statement result (only used by
  545. // readResultSetHeaderPacket).
  546. if len(mc.result.affectedRows) > 0 {
  547. mc.result.affectedRows[len(mc.result.affectedRows)-1] = int64(affectedRows)
  548. }
  549. if len(mc.result.insertIds) > 0 {
  550. mc.result.insertIds[len(mc.result.insertIds)-1] = int64(insertId)
  551. }
  552. // server_status [2 bytes]
  553. mc.status = readStatus(data[1+n+m : 1+n+m+2])
  554. if mc.status&statusMoreResultsExists != 0 {
  555. return nil
  556. }
  557. // warning count [2 bytes]
  558. return nil
  559. }
  560. // Read Packets as Field Packets until EOF-Packet or an Error appears
  561. // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41
  562. func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) {
  563. columns := make([]mysqlField, count)
  564. for i := 0; ; i++ {
  565. data, err := mc.readPacket()
  566. if err != nil {
  567. return nil, err
  568. }
  569. // EOF Packet
  570. if data[0] == iEOF && (len(data) == 5 || len(data) == 1) {
  571. if i == count {
  572. return columns, nil
  573. }
  574. return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns))
  575. }
  576. // Catalog
  577. pos, err := skipLengthEncodedString(data)
  578. if err != nil {
  579. return nil, err
  580. }
  581. // Database [len coded string]
  582. n, err := skipLengthEncodedString(data[pos:])
  583. if err != nil {
  584. return nil, err
  585. }
  586. pos += n
  587. // Table [len coded string]
  588. if mc.cfg.ColumnsWithAlias {
  589. tableName, _, n, err := readLengthEncodedString(data[pos:])
  590. if err != nil {
  591. return nil, err
  592. }
  593. pos += n
  594. columns[i].tableName = string(tableName)
  595. } else {
  596. n, err = skipLengthEncodedString(data[pos:])
  597. if err != nil {
  598. return nil, err
  599. }
  600. pos += n
  601. }
  602. // Original table [len coded string]
  603. n, err = skipLengthEncodedString(data[pos:])
  604. if err != nil {
  605. return nil, err
  606. }
  607. pos += n
  608. // Name [len coded string]
  609. name, _, n, err := readLengthEncodedString(data[pos:])
  610. if err != nil {
  611. return nil, err
  612. }
  613. columns[i].name = string(name)
  614. pos += n
  615. // Original name [len coded string]
  616. n, err = skipLengthEncodedString(data[pos:])
  617. if err != nil {
  618. return nil, err
  619. }
  620. pos += n
  621. // Filler [uint8]
  622. pos++
  623. // Charset [charset, collation uint8]
  624. columns[i].charSet = data[pos]
  625. pos += 2
  626. // Length [uint32]
  627. columns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4])
  628. pos += 4
  629. // Field type [uint8]
  630. columns[i].fieldType = fieldType(data[pos])
  631. pos++
  632. // Flags [uint16]
  633. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  634. pos += 2
  635. // Decimals [uint8]
  636. columns[i].decimals = data[pos]
  637. //pos++
  638. // Default value [len coded binary]
  639. //if pos < len(data) {
  640. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  641. //}
  642. }
  643. }
  644. // Read Packets as Field Packets until EOF-Packet or an Error appears
  645. // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow
  646. func (rows *textRows) readRow(dest []driver.Value) error {
  647. mc := rows.mc
  648. if rows.rs.done {
  649. return io.EOF
  650. }
  651. data, err := mc.readPacket()
  652. if err != nil {
  653. return err
  654. }
  655. // EOF Packet
  656. if data[0] == iEOF && len(data) == 5 {
  657. // server_status [2 bytes]
  658. rows.mc.status = readStatus(data[3:])
  659. rows.rs.done = true
  660. if !rows.HasNextResultSet() {
  661. rows.mc = nil
  662. }
  663. return io.EOF
  664. }
  665. if data[0] == iERR {
  666. rows.mc = nil
  667. return mc.handleErrorPacket(data)
  668. }
  669. // RowSet Packet
  670. var (
  671. n int
  672. isNull bool
  673. pos int = 0
  674. )
  675. for i := range dest {
  676. // Read bytes and convert to string
  677. var buf []byte
  678. buf, isNull, n, err = readLengthEncodedString(data[pos:])
  679. pos += n
  680. if err != nil {
  681. return err
  682. }
  683. if isNull {
  684. dest[i] = nil
  685. continue
  686. }
  687. switch rows.rs.columns[i].fieldType {
  688. case fieldTypeTimestamp,
  689. fieldTypeDateTime,
  690. fieldTypeDate,
  691. fieldTypeNewDate:
  692. if mc.parseTime {
  693. dest[i], err = parseDateTime(buf, mc.cfg.Loc)
  694. } else {
  695. dest[i] = buf
  696. }
  697. case fieldTypeTiny, fieldTypeShort, fieldTypeInt24, fieldTypeYear, fieldTypeLong:
  698. dest[i], err = strconv.ParseInt(string(buf), 10, 64)
  699. case fieldTypeLongLong:
  700. if rows.rs.columns[i].flags&flagUnsigned != 0 {
  701. dest[i], err = strconv.ParseUint(string(buf), 10, 64)
  702. } else {
  703. dest[i], err = strconv.ParseInt(string(buf), 10, 64)
  704. }
  705. case fieldTypeFloat:
  706. var d float64
  707. d, err = strconv.ParseFloat(string(buf), 32)
  708. dest[i] = float32(d)
  709. case fieldTypeDouble:
  710. dest[i], err = strconv.ParseFloat(string(buf), 64)
  711. default:
  712. dest[i] = buf
  713. }
  714. if err != nil {
  715. return err
  716. }
  717. }
  718. return nil
  719. }
  720. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  721. func (mc *mysqlConn) readUntilEOF() error {
  722. for {
  723. data, err := mc.readPacket()
  724. if err != nil {
  725. return err
  726. }
  727. switch data[0] {
  728. case iERR:
  729. return mc.handleErrorPacket(data)
  730. case iEOF:
  731. if len(data) == 5 {
  732. mc.status = readStatus(data[3:])
  733. }
  734. return nil
  735. }
  736. }
  737. }
  738. /******************************************************************************
  739. * Prepared Statements *
  740. ******************************************************************************/
  741. // Prepare Result Packets
  742. // http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html
  743. func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) {
  744. data, err := stmt.mc.readPacket()
  745. if err == nil {
  746. // packet indicator [1 byte]
  747. if data[0] != iOK {
  748. return 0, stmt.mc.handleErrorPacket(data)
  749. }
  750. // statement id [4 bytes]
  751. stmt.id = binary.LittleEndian.Uint32(data[1:5])
  752. // Column count [16 bit uint]
  753. columnCount := binary.LittleEndian.Uint16(data[5:7])
  754. // Param count [16 bit uint]
  755. stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9]))
  756. // Reserved [8 bit]
  757. // Warning count [16 bit uint]
  758. return columnCount, nil
  759. }
  760. return 0, err
  761. }
  762. // http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html
  763. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {
  764. maxLen := stmt.mc.maxAllowedPacket - 1
  765. pktLen := maxLen
  766. // After the header (bytes 0-3) follows before the data:
  767. // 1 byte command
  768. // 4 bytes stmtID
  769. // 2 bytes paramID
  770. const dataOffset = 1 + 4 + 2
  771. // Cannot use the write buffer since
  772. // a) the buffer is too small
  773. // b) it is in use
  774. data := make([]byte, 4+1+4+2+len(arg))
  775. copy(data[4+dataOffset:], arg)
  776. for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset {
  777. if dataOffset+argLen < maxLen {
  778. pktLen = dataOffset + argLen
  779. }
  780. stmt.mc.sequence = 0
  781. // Add command byte [1 byte]
  782. data[4] = comStmtSendLongData
  783. // Add stmtID [32 bit]
  784. data[5] = byte(stmt.id)
  785. data[6] = byte(stmt.id >> 8)
  786. data[7] = byte(stmt.id >> 16)
  787. data[8] = byte(stmt.id >> 24)
  788. // Add paramID [16 bit]
  789. data[9] = byte(paramID)
  790. data[10] = byte(paramID >> 8)
  791. // Send CMD packet
  792. err := stmt.mc.writePacket(data[:4+pktLen])
  793. if err == nil {
  794. data = data[pktLen-dataOffset:]
  795. continue
  796. }
  797. return err
  798. }
  799. // Reset Packet Sequence
  800. stmt.mc.sequence = 0
  801. return nil
  802. }
  803. // Execute Prepared Statement
  804. // http://dev.mysql.com/doc/internals/en/com-stmt-execute.html
  805. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  806. if len(args) != stmt.paramCount {
  807. return fmt.Errorf(
  808. "argument count mismatch (got: %d; has: %d)",
  809. len(args),
  810. stmt.paramCount,
  811. )
  812. }
  813. const minPktLen = 4 + 1 + 4 + 1 + 4
  814. mc := stmt.mc
  815. // Determine threshold dynamically to avoid packet size shortage.
  816. longDataSize := mc.maxAllowedPacket / (stmt.paramCount + 1)
  817. if longDataSize < 64 {
  818. longDataSize = 64
  819. }
  820. // Reset packet-sequence
  821. mc.sequence = 0
  822. var data []byte
  823. var err error
  824. if len(args) == 0 {
  825. data, err = mc.buf.takeBuffer(minPktLen)
  826. } else {
  827. data, err = mc.buf.takeCompleteBuffer()
  828. // In this case the len(data) == cap(data) which is used to optimise the flow below.
  829. }
  830. if err != nil {
  831. // cannot take the buffer. Something must be wrong with the connection
  832. mc.log(err)
  833. return errBadConnNoWrite
  834. }
  835. // command [1 byte]
  836. data[4] = comStmtExecute
  837. // statement_id [4 bytes]
  838. data[5] = byte(stmt.id)
  839. data[6] = byte(stmt.id >> 8)
  840. data[7] = byte(stmt.id >> 16)
  841. data[8] = byte(stmt.id >> 24)
  842. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  843. data[9] = 0x00
  844. // iteration_count (uint32(1)) [4 bytes]
  845. data[10] = 0x01
  846. data[11] = 0x00
  847. data[12] = 0x00
  848. data[13] = 0x00
  849. if len(args) > 0 {
  850. pos := minPktLen
  851. var nullMask []byte
  852. if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= cap(data) {
  853. // buffer has to be extended but we don't know by how much so
  854. // we depend on append after all data with known sizes fit.
  855. // We stop at that because we deal with a lot of columns here
  856. // which makes the required allocation size hard to guess.
  857. tmp := make([]byte, pos+maskLen+typesLen)
  858. copy(tmp[:pos], data[:pos])
  859. data = tmp
  860. nullMask = data[pos : pos+maskLen]
  861. // No need to clean nullMask as make ensures that.
  862. pos += maskLen
  863. } else {
  864. nullMask = data[pos : pos+maskLen]
  865. for i := range nullMask {
  866. nullMask[i] = 0
  867. }
  868. pos += maskLen
  869. }
  870. // newParameterBoundFlag 1 [1 byte]
  871. data[pos] = 0x01
  872. pos++
  873. // type of each parameter [len(args)*2 bytes]
  874. paramTypes := data[pos:]
  875. pos += len(args) * 2
  876. // value of each parameter [n bytes]
  877. paramValues := data[pos:pos]
  878. valuesCap := cap(paramValues)
  879. for i, arg := range args {
  880. // build NULL-bitmap
  881. if arg == nil {
  882. nullMask[i/8] |= 1 << (uint(i) & 7)
  883. paramTypes[i+i] = byte(fieldTypeNULL)
  884. paramTypes[i+i+1] = 0x00
  885. continue
  886. }
  887. if v, ok := arg.(json.RawMessage); ok {
  888. arg = []byte(v)
  889. }
  890. // cache types and values
  891. switch v := arg.(type) {
  892. case int64:
  893. paramTypes[i+i] = byte(fieldTypeLongLong)
  894. paramTypes[i+i+1] = 0x00
  895. if cap(paramValues)-len(paramValues)-8 >= 0 {
  896. paramValues = paramValues[:len(paramValues)+8]
  897. binary.LittleEndian.PutUint64(
  898. paramValues[len(paramValues)-8:],
  899. uint64(v),
  900. )
  901. } else {
  902. paramValues = append(paramValues,
  903. uint64ToBytes(uint64(v))...,
  904. )
  905. }
  906. case uint64:
  907. paramTypes[i+i] = byte(fieldTypeLongLong)
  908. paramTypes[i+i+1] = 0x80 // type is unsigned
  909. if cap(paramValues)-len(paramValues)-8 >= 0 {
  910. paramValues = paramValues[:len(paramValues)+8]
  911. binary.LittleEndian.PutUint64(
  912. paramValues[len(paramValues)-8:],
  913. uint64(v),
  914. )
  915. } else {
  916. paramValues = append(paramValues,
  917. uint64ToBytes(uint64(v))...,
  918. )
  919. }
  920. case float64:
  921. paramTypes[i+i] = byte(fieldTypeDouble)
  922. paramTypes[i+i+1] = 0x00
  923. if cap(paramValues)-len(paramValues)-8 >= 0 {
  924. paramValues = paramValues[:len(paramValues)+8]
  925. binary.LittleEndian.PutUint64(
  926. paramValues[len(paramValues)-8:],
  927. math.Float64bits(v),
  928. )
  929. } else {
  930. paramValues = append(paramValues,
  931. uint64ToBytes(math.Float64bits(v))...,
  932. )
  933. }
  934. case bool:
  935. paramTypes[i+i] = byte(fieldTypeTiny)
  936. paramTypes[i+i+1] = 0x00
  937. if v {
  938. paramValues = append(paramValues, 0x01)
  939. } else {
  940. paramValues = append(paramValues, 0x00)
  941. }
  942. case []byte:
  943. // Common case (non-nil value) first
  944. if v != nil {
  945. paramTypes[i+i] = byte(fieldTypeString)
  946. paramTypes[i+i+1] = 0x00
  947. if len(v) < longDataSize {
  948. paramValues = appendLengthEncodedInteger(paramValues,
  949. uint64(len(v)),
  950. )
  951. paramValues = append(paramValues, v...)
  952. } else {
  953. if err := stmt.writeCommandLongData(i, v); err != nil {
  954. return err
  955. }
  956. }
  957. continue
  958. }
  959. // Handle []byte(nil) as a NULL value
  960. nullMask[i/8] |= 1 << (uint(i) & 7)
  961. paramTypes[i+i] = byte(fieldTypeNULL)
  962. paramTypes[i+i+1] = 0x00
  963. case string:
  964. paramTypes[i+i] = byte(fieldTypeString)
  965. paramTypes[i+i+1] = 0x00
  966. if len(v) < longDataSize {
  967. paramValues = appendLengthEncodedInteger(paramValues,
  968. uint64(len(v)),
  969. )
  970. paramValues = append(paramValues, v...)
  971. } else {
  972. if err := stmt.writeCommandLongData(i, []byte(v)); err != nil {
  973. return err
  974. }
  975. }
  976. case time.Time:
  977. paramTypes[i+i] = byte(fieldTypeString)
  978. paramTypes[i+i+1] = 0x00
  979. var a [64]byte
  980. var b = a[:0]
  981. if v.IsZero() {
  982. b = append(b, "0000-00-00"...)
  983. } else {
  984. b, err = appendDateTime(b, v.In(mc.cfg.Loc), mc.cfg.timeTruncate)
  985. if err != nil {
  986. return err
  987. }
  988. }
  989. paramValues = appendLengthEncodedInteger(paramValues,
  990. uint64(len(b)),
  991. )
  992. paramValues = append(paramValues, b...)
  993. default:
  994. return fmt.Errorf("cannot convert type: %T", arg)
  995. }
  996. }
  997. // Check if param values exceeded the available buffer
  998. // In that case we must build the data packet with the new values buffer
  999. if valuesCap != cap(paramValues) {
  1000. data = append(data[:pos], paramValues...)
  1001. if err = mc.buf.store(data); err != nil {
  1002. mc.log(err)
  1003. return errBadConnNoWrite
  1004. }
  1005. }
  1006. pos += len(paramValues)
  1007. data = data[:pos]
  1008. }
  1009. return mc.writePacket(data)
  1010. }
  1011. // For each remaining resultset in the stream, discards its rows and updates
  1012. // mc.affectedRows and mc.insertIds.
  1013. func (mc *okHandler) discardResults() error {
  1014. for mc.status&statusMoreResultsExists != 0 {
  1015. resLen, err := mc.readResultSetHeaderPacket()
  1016. if err != nil {
  1017. return err
  1018. }
  1019. if resLen > 0 {
  1020. // columns
  1021. if err := mc.conn().readUntilEOF(); err != nil {
  1022. return err
  1023. }
  1024. // rows
  1025. if err := mc.conn().readUntilEOF(); err != nil {
  1026. return err
  1027. }
  1028. }
  1029. }
  1030. return nil
  1031. }
  1032. // http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html
  1033. func (rows *binaryRows) readRow(dest []driver.Value) error {
  1034. data, err := rows.mc.readPacket()
  1035. if err != nil {
  1036. return err
  1037. }
  1038. // packet indicator [1 byte]
  1039. if data[0] != iOK {
  1040. // EOF Packet
  1041. if data[0] == iEOF && len(data) == 5 {
  1042. rows.mc.status = readStatus(data[3:])
  1043. rows.rs.done = true
  1044. if !rows.HasNextResultSet() {
  1045. rows.mc = nil
  1046. }
  1047. return io.EOF
  1048. }
  1049. mc := rows.mc
  1050. rows.mc = nil
  1051. // Error otherwise
  1052. return mc.handleErrorPacket(data)
  1053. }
  1054. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  1055. pos := 1 + (len(dest)+7+2)>>3
  1056. nullMask := data[1:pos]
  1057. for i := range dest {
  1058. // Field is NULL
  1059. // (byte >> bit-pos) % 2 == 1
  1060. if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  1061. dest[i] = nil
  1062. continue
  1063. }
  1064. // Convert to byte-coded string
  1065. switch rows.rs.columns[i].fieldType {
  1066. case fieldTypeNULL:
  1067. dest[i] = nil
  1068. continue
  1069. // Numeric Types
  1070. case fieldTypeTiny:
  1071. if rows.rs.columns[i].flags&flagUnsigned != 0 {
  1072. dest[i] = int64(data[pos])
  1073. } else {
  1074. dest[i] = int64(int8(data[pos]))
  1075. }
  1076. pos++
  1077. continue
  1078. case fieldTypeShort, fieldTypeYear:
  1079. if rows.rs.columns[i].flags&flagUnsigned != 0 {
  1080. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  1081. } else {
  1082. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  1083. }
  1084. pos += 2
  1085. continue
  1086. case fieldTypeInt24, fieldTypeLong:
  1087. if rows.rs.columns[i].flags&flagUnsigned != 0 {
  1088. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  1089. } else {
  1090. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  1091. }
  1092. pos += 4
  1093. continue
  1094. case fieldTypeLongLong:
  1095. if rows.rs.columns[i].flags&flagUnsigned != 0 {
  1096. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  1097. if val > math.MaxInt64 {
  1098. dest[i] = uint64ToString(val)
  1099. } else {
  1100. dest[i] = int64(val)
  1101. }
  1102. } else {
  1103. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  1104. }
  1105. pos += 8
  1106. continue
  1107. case fieldTypeFloat:
  1108. dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4]))
  1109. pos += 4
  1110. continue
  1111. case fieldTypeDouble:
  1112. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  1113. pos += 8
  1114. continue
  1115. // Length coded Binary Strings
  1116. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  1117. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  1118. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  1119. fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON:
  1120. var isNull bool
  1121. var n int
  1122. dest[i], isNull, n, err = readLengthEncodedString(data[pos:])
  1123. pos += n
  1124. if err == nil {
  1125. if !isNull {
  1126. continue
  1127. } else {
  1128. dest[i] = nil
  1129. continue
  1130. }
  1131. }
  1132. return err
  1133. case
  1134. fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD
  1135. fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal]
  1136. fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  1137. num, isNull, n := readLengthEncodedInteger(data[pos:])
  1138. pos += n
  1139. switch {
  1140. case isNull:
  1141. dest[i] = nil
  1142. continue
  1143. case rows.rs.columns[i].fieldType == fieldTypeTime:
  1144. // database/sql does not support an equivalent to TIME, return a string
  1145. var dstlen uint8
  1146. switch decimals := rows.rs.columns[i].decimals; decimals {
  1147. case 0x00, 0x1f:
  1148. dstlen = 8
  1149. case 1, 2, 3, 4, 5, 6:
  1150. dstlen = 8 + 1 + decimals
  1151. default:
  1152. return fmt.Errorf(
  1153. "protocol error, illegal decimals value %d",
  1154. rows.rs.columns[i].decimals,
  1155. )
  1156. }
  1157. dest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen)
  1158. case rows.mc.parseTime:
  1159. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc)
  1160. default:
  1161. var dstlen uint8
  1162. if rows.rs.columns[i].fieldType == fieldTypeDate {
  1163. dstlen = 10
  1164. } else {
  1165. switch decimals := rows.rs.columns[i].decimals; decimals {
  1166. case 0x00, 0x1f:
  1167. dstlen = 19
  1168. case 1, 2, 3, 4, 5, 6:
  1169. dstlen = 19 + 1 + decimals
  1170. default:
  1171. return fmt.Errorf(
  1172. "protocol error, illegal decimals value %d",
  1173. rows.rs.columns[i].decimals,
  1174. )
  1175. }
  1176. }
  1177. dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen)
  1178. }
  1179. if err == nil {
  1180. pos += int(num)
  1181. continue
  1182. } else {
  1183. return err
  1184. }
  1185. // Please report if this happens!
  1186. default:
  1187. return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType)
  1188. }
  1189. }
  1190. return nil
  1191. }