rows.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. "io"
  14. )
  15. type mysqlField struct {
  16. name string
  17. fieldType FieldType
  18. flags FieldFlag
  19. }
  20. type rowsContent struct {
  21. mc *mysqlConn
  22. binary bool
  23. unread int
  24. columns []mysqlField
  25. }
  26. type mysqlRows struct {
  27. content *rowsContent
  28. }
  29. func (rows mysqlRows) Columns() (columns []string) {
  30. columns = make([]string, len(rows.content.columns))
  31. for i := 0; i < cap(columns); i++ {
  32. columns[i] = rows.content.columns[i].name
  33. }
  34. return
  35. }
  36. func (rows mysqlRows) Close() (e error) {
  37. defer func() {
  38. rows.content.mc = nil
  39. rows.content = nil
  40. }()
  41. // Remove unread packets from stream
  42. if rows.content.unread > -1 {
  43. if rows.content.mc == nil {
  44. return errors.New("Invalid Connection")
  45. }
  46. _, e = rows.content.mc.readUntilEOF()
  47. if e != nil {
  48. return
  49. }
  50. }
  51. return nil
  52. }
  53. // Next returns []driver.Value filled with either nil values for NULL entries
  54. // or []byte's for all other entries. Type conversion is done on rows.scan(),
  55. // when the dest type is know, which makes type conversion easier and avoids
  56. // unnecessary conversions.
  57. func (rows mysqlRows) Next(dest []driver.Value) error {
  58. if rows.content.unread > 0 {
  59. if rows.content.mc == nil {
  60. return errors.New("Invalid Connection")
  61. }
  62. columnsCount := cap(dest)
  63. // Fetch next row from stream
  64. var row *[]*[]byte
  65. var e error
  66. if rows.content.binary {
  67. row, e = rows.content.mc.readBinaryRow(rows.content)
  68. } else {
  69. row, e = rows.content.mc.readRow(columnsCount)
  70. }
  71. rows.content.unread--
  72. if e != nil {
  73. return e
  74. }
  75. for i := 0; i < columnsCount; i++ {
  76. if (*row)[i] == nil {
  77. dest[i] = nil
  78. } else {
  79. dest[i] = *(*row)[i]
  80. }
  81. }
  82. } else {
  83. return io.EOF
  84. }
  85. return nil
  86. }