1
0
mirror of https://github.com/DATA-DOG/go-sqlmock.git synced 2024-11-28 08:49:01 +02:00

allow null values from csv string to be converted to nil

This commit is contained in:
gedi 2015-08-05 11:50:16 +03:00
parent dc0efdab8f
commit acfbd5d998
2 changed files with 42 additions and 1 deletions

12
rows.go
View File

@ -7,6 +7,16 @@ import (
"strings"
)
// CSVColumnParser is a function which converts trimmed csv
// column string to a []byte representation.
var CSVColumnParser = func(s string) []byte {
switch {
case strings.ToLower(s) == "null":
return nil
}
return []byte(s)
}
// Rows interface allows to construct rows
// which also satisfies database/sql/driver.Rows interface
type Rows interface {
@ -113,7 +123,7 @@ func (r *rows) FromCSVString(s string) Rows {
row := make([]driver.Value, len(r.cols))
for i, v := range res {
row[i] = []byte(strings.TrimSpace(v))
row[i] = CSVColumnParser(strings.TrimSpace(v))
}
r.rows = append(r.rows, row)
}

View File

@ -207,3 +207,34 @@ func TODO_TestRowsColumnsError(t *testing.T) {
t.Fatal(err)
}
}
func TestCSVRowParser(t *testing.T) {
t.Parallel()
rs := NewRows([]string{"col1", "col2"}).FromCSVString("a,NULL")
db, mock, err := New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectQuery("SELECT").WillReturnRows(rs)
rw, err := db.Query("SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
defer rw.Close()
var col1 string
var col2 []byte
rw.Next()
if err = rw.Scan(&col1, &col2); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if col1 != "a" {
t.Fatalf("expected col1 to be 'a', but got [%T]:%+v", col1, col1)
}
if col2 != nil {
t.Fatalf("expected col2 to be nil, but got [%T]:%+v", col2, col2)
}
}