Skip to content

Commit f9f57c4

Browse files
muhlemmerkardianos
authored andcommitted
database/sql: add method Err on sql.Row
The Row.Err method is intended to assist wrapping sql.DB. Because sql.Row is a struct with private fields, a wrapper in an existing code base cannot easily provide users with a different implementation without large rewrites. Adding this method allows query level errors to be handled centrally. Fixes #35804 Change-Id: I94e6329de89a7ee1284ce9ef76af4363d2d081f9 Reviewed-on: https://go-review.googlesource.com/c/go/+/214317 Reviewed-by: Daniel Theophanes <[email protected]> Run-TryBot: Daniel Theophanes <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent b3b174f commit f9f57c4

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/database/sql/sql.go

+8
Original file line numberDiff line numberDiff line change
@@ -3174,6 +3174,14 @@ func (r *Row) Scan(dest ...interface{}) error {
31743174
return r.rows.Close()
31753175
}
31763176

3177+
// Err provides a way for wrapping packages to check for
3178+
// query errors without calling Scan.
3179+
// Err returns the error, if any, that was encountered while running the query.
3180+
// If this error is not nil, this error will also be returned from Scan.
3181+
func (r *Row) Err() error {
3182+
return r.err
3183+
}
3184+
31773185
// A Result summarizes an executed SQL command.
31783186
type Result interface {
31793187
// LastInsertId returns the integer generated by the database

src/database/sql/sql_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,24 @@ func TestQueryRow(t *testing.T) {
788788
}
789789
}
790790

791+
func TestRowErr(t *testing.T) {
792+
db := newTestDB(t, "people")
793+
794+
err := db.QueryRowContext(context.Background(), "SELECT|people|bdate|age=?", 3).Err()
795+
if err != nil {
796+
t.Errorf("Unexpected err = %v; want %v", err, nil)
797+
}
798+
799+
ctx, cancel := context.WithCancel(context.Background())
800+
cancel()
801+
802+
err = db.QueryRowContext(ctx, "SELECT|people|bdate|age=?", 3).Err()
803+
exp := "context canceled"
804+
if err == nil || !strings.Contains(err.Error(), exp) {
805+
t.Errorf("Expected err = %v; got %v", exp, err)
806+
}
807+
}
808+
791809
func TestTxRollbackCommitErr(t *testing.T) {
792810
db := newTestDB(t, "people")
793811
defer closeDB(t, db)

0 commit comments

Comments
 (0)