packets.go 34 KB

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