Created
July 14, 2022 14:30
-
-
Save nwillc/26342808ea28d4e7f486520ec92e6fff to your computer and use it in GitHub Desktop.
Go generics enhanced database query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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