From 2a38ae39982e34de4400c8790c45885806505095 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Sun, 13 Jun 2021 15:11:17 -0300 Subject: [PATCH] Improve Update method to return ErrRecordNotFound if no rows were updated --- ksql.go | 18 ++++++++++++++++-- ksql_test.go | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/ksql.go b/ksql.go index 1f9195f..b359b36 100644 --- a/ksql.go +++ b/ksql.go @@ -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( diff --git a/ksql_test.go b/ksql_test.go index 3eea91a..eccec01 100644 --- a/ksql_test.go +++ b/ksql_test.go @@ -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()