Skip to content

Commit 845a9a7

Browse files
authored
Merge branch 'master' into issue-380
2 parents f93ad2c + 28212d4 commit 845a9a7

2 files changed

Lines changed: 36 additions & 3 deletions

File tree

sqlx.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -888,9 +888,10 @@ func structOnlyError(t reflect.Type) error {
888888
}
889889

890890
// scanAll scans all rows into a destination, which must be a slice of any
891-
// type. If the destination slice type is a Struct, then StructScan will be
892-
// used on each row. If the destination is some other kind of base type, then
893-
// each row must only have one column which can scan into that type. This
891+
// type. It resets the slice length to zero before appending each element to
892+
// the slice. If the destination slice type is a Struct, then StructScan will
893+
// be used on each row. If the destination is some other kind of base type,
894+
// then each row must only have one column which can scan into that type. This
894895
// allows you to do something like:
895896
//
896897
// rows, _ := db.Query("select id from people;")
@@ -920,6 +921,7 @@ func scanAll(rows rowsi, dest interface{}, structOnly bool) error {
920921
if err != nil {
921922
return err
922923
}
924+
direct.SetLen(0)
923925

924926
isPtr := slice.Elem().Kind() == reflect.Ptr
925927
base := reflectx.Deref(slice.Elem())

sqlx_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1996,6 +1996,37 @@ func TestMultiResultSet(t *testing.T) {
19961996
if rows.NextResultSet() {
19971997
t.Fatalf("[%s] Did not expected a second recordset", db.DriverName())
19981998
}
1999+
})
2000+
}
2001+
2002+
func TestSelectReset(t *testing.T) {
2003+
RunWithSchema(defaultSchema, t, func(db *DB, t *testing.T, now string) {
2004+
loadDefaultFixture(db, t)
19992005

2006+
filledDest := []string{"a", "b", "c"}
2007+
err := db.Select(&filledDest, "SELECT first_name FROM person ORDER BY first_name ASC;")
2008+
if err != nil {
2009+
t.Fatal(err)
2010+
}
2011+
if len(filledDest) != 2 {
2012+
t.Errorf("Expected 2 first names, got %d.", len(filledDest))
2013+
}
2014+
expected := []string{"Jason", "John"}
2015+
for i, got := range filledDest {
2016+
if got != expected[i] {
2017+
t.Errorf("Expected %d result to be %s, but got %s.", i, expected[i], got)
2018+
}
2019+
}
2020+
2021+
var emptyDest []string
2022+
err = db.Select(&emptyDest, "SELECT first_name FROM person WHERE first_name = 'Jack';")
2023+
if err != nil {
2024+
t.Fatal(err)
2025+
}
2026+
// Verify that selecting 0 rows into a nil target didn't create a
2027+
// non-nil slice.
2028+
if emptyDest != nil {
2029+
t.Error("Expected emptyDest to be nil")
2030+
}
20002031
})
20012032
}

0 commit comments

Comments
 (0)