refactor: split dbx package into domain files
Reorganize monolithic dbx.go and utility.go into focused files by concern, add package doc.go, and gitignore coverage.out. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package dbx
|
||||
|
||||
import "errors"
|
||||
|
||||
// Fetch queries the database and returns the result as a slice. If the query
|
||||
// returns no rows, it returns an empty slice and no error.
|
||||
func Fetch[T any](sqlo Queryable, stmt Statement) ([]*T, error) {
|
||||
var result []*T
|
||||
if err := stmt.Query(sqlo, &result); err != nil && !errors.Is(err, ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// MustFetch queries the database and returns the result as a slice. If the query
|
||||
// returns no rows, it returns an empty slice and the desired error.
|
||||
func MustFetch[T any](sqlo Queryable, stmt Statement, notFoundErr error) ([]*T, error) {
|
||||
result, err := Fetch[T](sqlo, stmt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil, notFoundErr
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// FetchOne queries the database and returns a single result. If the query
|
||||
// returns no rows, it returns nil and no error.
|
||||
func FetchOne[T any](sqlo Queryable, stmt Statement) (*T, error) {
|
||||
result, err := Fetch[T](sqlo, stmt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return result[0], nil
|
||||
}
|
||||
|
||||
// MustFetchOne queries the database and returns a single result. If the query
|
||||
// returns no rows, it returns nil and the desired error.
|
||||
func MustFetchOne[T any](sqlo Queryable, stmt Statement, notFoundErr error) (*T, error) {
|
||||
result, err := MustFetch[T](sqlo, stmt, notFoundErr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result[0], nil
|
||||
}
|
||||
Reference in New Issue
Block a user