Skip to content

Commit

Permalink
Add AppendRows helper
Browse files Browse the repository at this point in the history
  • Loading branch information
espadolini authored and jackc committed Jan 23, 2024
1 parent 517c654 commit a57bb8c
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,12 +417,10 @@ type CollectableRow interface {
// RowToFunc is a function that scans or otherwise converts row to a T.
type RowToFunc[T any] func(row CollectableRow) (T, error)

// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T.
func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) {
// AppendRows iterates through rows, calling fn for each row, and appending the results into a slice of T.
func AppendRows[T any, S ~[]T](slice S, rows Rows, fn RowToFunc[T]) (S, error) {
defer rows.Close()

slice := []T{}

for rows.Next() {
value, err := fn(rows)
if err != nil {
Expand All @@ -438,6 +436,11 @@ func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) {
return slice, nil
}

// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T.
func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) {
return AppendRows([]T(nil), rows, fn)
}

// CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true.
// CollectOneRow is to CollectRows as QueryRow is to Query.
func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) {
Expand Down

0 comments on commit a57bb8c

Please sign in to comment.