Skip to content

Commit 1d85708

Browse files
authored
fix: transaction for user update and deletion
1 parent a9647e8 commit 1d85708

File tree

1 file changed

+13
-6
lines changed
  • packages/gorm/challenge-1-crud-operations/submissions/shansing

1 file changed

+13
-6
lines changed

packages/gorm/challenge-1-crud-operations/submissions/shansing/solution.go

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"errors"
45
"fmt"
56
"time"
67

@@ -68,10 +69,13 @@ func GetAllUsers(db *gorm.DB) ([]User, error) {
6869
func UpdateUser(db *gorm.DB, user *User) error {
6970
// Implement user update
7071
return db.Transaction(func(tx *gorm.DB) error {
71-
if u := db.First(&User{}, user.ID); u.Error != nil {
72-
return fmt.Errorf("user with id %d not found or error", user.ID)
72+
if u := tx.First(&User{}, user.ID); u.Error != nil {
73+
if errors.Is(u.Error, gorm.ErrRecordNotFound) {
74+
return fmt.Errorf("user with id %d not found", user.ID)
75+
}
76+
return fmt.Errorf("user with id %d error", user.ID)
7377
}
74-
result := db.Save(user)
78+
result := tx.Save(user)
7579
if result.Error != nil {
7680
return result.Error
7781
}
@@ -83,10 +87,13 @@ func UpdateUser(db *gorm.DB, user *User) error {
8387
func DeleteUser(db *gorm.DB, id uint) error {
8488
// Implement user deletion
8589
return db.Transaction(func(tx *gorm.DB) error {
86-
if u := db.First(&User{}, id); u.Error != nil {
87-
return fmt.Errorf("user with id %d not found or error", id)
90+
if u := tx.First(&User{}, id); u.Error != nil {
91+
if errors.Is(u.Error, gorm.ErrRecordNotFound) {
92+
return fmt.Errorf("user with id %d not found", id)
93+
}
94+
return fmt.Errorf("user with id %d error", id)
8895
}
89-
result := db.Delete(&User{}, id)
96+
result := tx.Delete(&User{}, id)
9097
if result.Error != nil {
9198
return result.Error
9299
}

0 commit comments

Comments
 (0)