Skip to content

Commit

Permalink
Merge pull request #767 from liftoffio/gpark.sqlx.reset-slice
Browse files Browse the repository at this point in the history
Make Select reset slice length
  • Loading branch information
jmoiron authored Apr 16, 2022
2 parents a62bc60 + 421d1cd commit 28212d4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
8 changes: 5 additions & 3 deletions sqlx.go
Original file line number Diff line number Diff line change
Expand Up @@ -878,9 +878,10 @@ func structOnlyError(t reflect.Type) error {
}

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

isPtr := slice.Elem().Kind() == reflect.Ptr
base := reflectx.Deref(slice.Elem())
Expand Down
32 changes: 32 additions & 0 deletions sqlx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1892,3 +1892,35 @@ func TestIn130Regression(t *testing.T) {
}
})
}

func TestSelectReset(t *testing.T) {
RunWithSchema(defaultSchema, t, func(db *DB, t *testing.T, now string) {
loadDefaultFixture(db, t)

filledDest := []string{"a", "b", "c"}
err := db.Select(&filledDest, "SELECT first_name FROM person ORDER BY first_name ASC;")
if err != nil {
t.Fatal(err)
}
if len(filledDest) != 2 {
t.Errorf("Expected 2 first names, got %d.", len(filledDest))
}
expected := []string{"Jason", "John"}
for i, got := range filledDest {
if got != expected[i] {
t.Errorf("Expected %d result to be %s, but got %s.", i, expected[i], got)
}
}

var emptyDest []string
err = db.Select(&emptyDest, "SELECT first_name FROM person WHERE first_name = 'Jack';")
if err != nil {
t.Fatal(err)
}
// Verify that selecting 0 rows into a nil target didn't create a
// non-nil slice.
if emptyDest != nil {
t.Error("Expected emptyDest to be nil")
}
})
}

0 comments on commit 28212d4

Please sign in to comment.