Files
dbx/query.go
T
end f9befa1b0a 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>
2026-06-29 17:46:54 -07:00

50 lines
1.4 KiB
Go

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
}