2014-02-05 16:21:07 +02:00
|
|
|
package sqlmock
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql/driver"
|
|
|
|
"encoding/csv"
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2014-02-07 08:58:27 +02:00
|
|
|
// a struct which implements database/sql/driver.Rows
|
2014-02-05 16:21:07 +02:00
|
|
|
type rows struct {
|
|
|
|
cols []string
|
|
|
|
rows [][]driver.Value
|
|
|
|
pos int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *rows) Columns() []string {
|
|
|
|
return r.cols
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *rows) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *rows) Err() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-02-07 08:58:27 +02:00
|
|
|
// advances to next row
|
2014-02-05 16:21:07 +02:00
|
|
|
func (r *rows) Next(dest []driver.Value) error {
|
|
|
|
r.pos++
|
|
|
|
if r.pos > len(r.rows) {
|
|
|
|
return io.EOF // per interface spec
|
|
|
|
}
|
|
|
|
|
|
|
|
for i, col := range r.rows[r.pos-1] {
|
|
|
|
dest[i] = col
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-02-07 10:44:41 +02:00
|
|
|
// Create Rows from CSV string
|
|
|
|
// to be used for mocked queries. Satisfies sql driver Rows interface
|
2014-02-05 16:21:07 +02:00
|
|
|
func RowsFromCSVString(columns []string, s string) driver.Rows {
|
|
|
|
rs := &rows{}
|
|
|
|
rs.cols = columns
|
|
|
|
|
|
|
|
r := strings.NewReader(strings.TrimSpace(s))
|
|
|
|
csvReader := csv.NewReader(r)
|
|
|
|
|
|
|
|
for {
|
|
|
|
r, err := csvReader.Read()
|
|
|
|
if err != nil || r == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
row := make([]driver.Value, len(columns))
|
|
|
|
for i, v := range r {
|
|
|
|
v := strings.TrimSpace(v)
|
2014-02-06 17:03:46 +02:00
|
|
|
row[i] = []byte(v)
|
2014-02-05 16:21:07 +02:00
|
|
|
}
|
|
|
|
rs.rows = append(rs.rows, row)
|
|
|
|
}
|
|
|
|
return rs
|
|
|
|
}
|