Skip to content

Commit 679b2e8

Browse files
committed
added db.QueryValueReplaceErrNoRows and QueryRowStructReplaceErrNoRows
1 parent 87d94d5 commit 679b2e8

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

db/query.go

+28
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ func QueryValue[T any](ctx context.Context, query string, args ...any) (value T,
4444
return value, nil
4545
}
4646

47+
// QueryValueReplaceErrNoRows queries a single value of type T.
48+
// In case of an sql.ErrNoRows error, errNoRows will be called
49+
// and its result returned together with the default value for T.
50+
func QueryValueReplaceErrNoRows[T any](ctx context.Context, errNoRows func() error, query string, args ...any) (value T, err error) {
51+
err = Conn(ctx).QueryRow(query, args...).Scan(&value)
52+
if err != nil {
53+
if errors.Is(err, sql.ErrNoRows) && errNoRows != nil {
54+
return *new(T), errNoRows()
55+
}
56+
return *new(T), err
57+
}
58+
return value, nil
59+
}
60+
4761
// QueryValueOr queries a single value of type T
4862
// or returns the passed defaultValue in case of sql.ErrNoRows.
4963
func QueryValueOr[T any](ctx context.Context, defaultValue T, query string, args ...any) (value T, err error) {
@@ -66,6 +80,20 @@ func QueryRowStruct[S any](ctx context.Context, query string, args ...any) (row
6680
return row, nil
6781
}
6882

83+
// QueryRowStructReplaceErrNoRows queries a row and scans it as struct.
84+
// In case of an sql.ErrNoRows error, errNoRows will be called
85+
// and its result returned as error together with nil as row.
86+
func QueryRowStructReplaceErrNoRows[S any](ctx context.Context, errNoRows func() error, query string, args ...any) (row *S, err error) {
87+
err = Conn(ctx).QueryRow(query, args...).ScanStruct(&row)
88+
if err != nil {
89+
if errors.Is(err, sql.ErrNoRows) && errNoRows != nil {
90+
return nil, errNoRows()
91+
}
92+
return nil, err
93+
}
94+
return row, nil
95+
}
96+
6997
// QueryRowStructOrNil queries a row and scans it as struct
7098
// or returns nil in case of sql.ErrNoRows.
7199
func QueryRowStructOrNil[S any](ctx context.Context, query string, args ...any) (row *S, err error) {

0 commit comments

Comments
 (0)