Skip to content

Commit

Permalink
dbutil/queryhelper: return zero-value if no rows found
Browse files Browse the repository at this point in the history
Without this commit, the QueryOne function would return whatever the
(DataStruct[T]).Scan function returns as the value in the sql.ErrNoRows
error case. In some cases, the value returned  might be an initialized
value. For example, if the following pattern is followed:

	func (s *MyStruct) Scan(row dbutil.Scannable) (*MyStruct, error) {
		err := row.Scan(&s.A, &s.B, &s.C)
		return s, err
	}

Note that even in the error case, the "s" variable will be initialized.

The alternative would be to force the (DataStruct[T]).Scan function to
return nil if there is an error, but that forces unnecessary verbosity
onto the implementer of the interface since they would have to do
something like:

	func (s *MyStruct) Scan(row dbutil.Scannable) (*MyStruct, error) {
		err := row.Scan(&s.A, &s.B, &s.C)
		if err != nil {
			return nil, err
		}
		return s, nil
	}

Signed-off-by: Sumner Evans <[email protected]>
  • Loading branch information
sumnerevans committed Jul 2, 2024
1 parent 5776177 commit bd1da3c
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion dbutil/queryhelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (qh *QueryHelper[T]) scanNew(row Scannable) (T, error) {
func (qh *QueryHelper[T]) QueryOne(ctx context.Context, query string, args ...any) (val T, err error) {
val, err = qh.scanNew(qh.db.QueryRow(ctx, query, args...))
if errors.Is(err, sql.ErrNoRows) {
err = nil
return *new(T), nil
}
return val, err
}
Expand Down

0 comments on commit bd1da3c

Please sign in to comment.