Improve Update method to return ErrRecordNotFound if no rows were updated

pull/2/head
Vinícius Garcia 2021-06-13 15:11:17 -03:00
parent 5b351c8ba2
commit 2a38ae3998
2 changed files with 30 additions and 2 deletions

18
ksql.go
View File

@ -541,9 +541,23 @@ func (c DB) Update(
return err
}
_, err = c.db.ExecContext(ctx, query, params...)
result, err := c.db.ExecContext(ctx, query, params...)
if err != nil {
return err
}
return err
n, err := result.RowsAffected()
if err != nil {
return fmt.Errorf(
"unexpected error: unable to fetch how many rows were affected by the update: %s",
err,
)
}
if n < 1 {
return ErrRecordNotFound
}
return nil
}
func buildInsertQuery(

View File

@ -1026,6 +1026,20 @@ func TestUpdate(t *testing.T) {
assert.Equal(t, 42, result.Age)
})
t.Run("should return ErrRecordNotFound when asked to update an inexistent user", func(t *testing.T) {
db := connectDB(t, driver)
defer db.Close()
ctx := context.Background()
c := newTestDB(db, driver)
err = c.Update(ctx, UsersTable, User{
ID: 4200,
Name: "Thayane",
})
assert.Equal(t, ErrRecordNotFound, err)
})
t.Run("should report database errors correctly", func(t *testing.T) {
db := connectDB(t, driver)
defer db.Close()