Skip to content

Instantly share code, notes, and snippets.

@nwillc
Created July 14, 2022 14:30
Show Gist options
  • Save nwillc/26342808ea28d4e7f486520ec92e6fff to your computer and use it in GitHub Desktop.
Save nwillc/26342808ea28d4e7f486520ec92e6fff to your computer and use it in GitHub Desktop.
Go generics enhanced database query
func Query[T any](
db *sql.DB,
binder func(*T) []any,
query string,
args ...any) (error, []*T) {
rows, err := db.Query(query, args...)
if err != nil {
return err, nil
}
defer func() {
_ = rows.Close()
}()
var results []*T
for rows.Next() {
var result T
cols := binder(&result)
err = rows.Scan(cols...)
if err != nil {
return err, nil
}
results = append(results, &result)
}
return nil, results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment