Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Select reset slice length #767

Merged
merged 1 commit into from Apr 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 5 additions & 3 deletions sqlx.go
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
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")
}
})
}