Skip to content

Commit

Permalink
added db.QueryValueReplaceErrNoRows and QueryRowStructReplaceErrNoRows
Browse files Browse the repository at this point in the history
  • Loading branch information
ungerik committed Mar 13, 2024
1 parent 87d94d5 commit 679b2e8
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions db/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ func QueryValue[T any](ctx context.Context, query string, args ...any) (value T,
return value, nil
}

// QueryValueReplaceErrNoRows queries a single value of type T.
// In case of an sql.ErrNoRows error, errNoRows will be called
// and its result returned together with the default value for T.
func QueryValueReplaceErrNoRows[T any](ctx context.Context, errNoRows func() error, query string, args ...any) (value T, err error) {
err = Conn(ctx).QueryRow(query, args...).Scan(&value)
if err != nil {
if errors.Is(err, sql.ErrNoRows) && errNoRows != nil {
return *new(T), errNoRows()
}
return *new(T), err
}
return value, nil
}

// QueryValueOr queries a single value of type T
// or returns the passed defaultValue in case of sql.ErrNoRows.
func QueryValueOr[T any](ctx context.Context, defaultValue T, query string, args ...any) (value T, err error) {
Expand All @@ -66,6 +80,20 @@ func QueryRowStruct[S any](ctx context.Context, query string, args ...any) (row
return row, nil
}

// QueryRowStructReplaceErrNoRows queries a row and scans it as struct.
// In case of an sql.ErrNoRows error, errNoRows will be called
// and its result returned as error together with nil as row.
func QueryRowStructReplaceErrNoRows[S any](ctx context.Context, errNoRows func() error, query string, args ...any) (row *S, err error) {
err = Conn(ctx).QueryRow(query, args...).ScanStruct(&row)
if err != nil {
if errors.Is(err, sql.ErrNoRows) && errNoRows != nil {
return nil, errNoRows()
}
return nil, err
}
return row, nil
}

// QueryRowStructOrNil queries a row and scans it as struct
// or returns nil in case of sql.ErrNoRows.
func QueryRowStructOrNil[S any](ctx context.Context, query string, args ...any) (row *S, err error) {
Expand Down

0 comments on commit 679b2e8

Please sign in to comment.