Skip to content

Commit

Permalink
fix: DeleteUser in users model
Browse files Browse the repository at this point in the history
previously, the DeleteUser function was not working as it chained
`.Delete(&user)` after `.First(&user)`. this resulted in a query as
shown, and its corresponding error:

* `ERROR: table name "users" specified more than once (SQLSTATE 42712)
[8.059ms] [rows:1] UPDATE "users" SET "deleted_at"='2024-02-12
20:52:41.02' FROM "users" WHERE id = 4 AND "users"."deleted_at" IS NULL
AND "users"."id" = 4`

the intent of `.First(&user)` was likely to store the user to be deleted
first in the `user` variable with the use of a `SELECT` SQL statement.
however, chaining another method at the end of a finisher method likely
led to some errors (see chaining
[here](https://gorm.io/docs/method_chaining.html)).

thus, this commit attempts to separate the two statements, preserving
the initial intent of storing the user to be deleted before deleting,
and then returning this user.
  • Loading branch information
zsiggg committed Feb 12, 2024
1 parent 1db8c90 commit 62d5baf
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion model/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,19 @@ func DeleteUser(db *gorm.DB, userID int) (User, error) {
err := db.
Model(&user).
Where("id = ?", userID).
First(&user). // store the value to be returned
First(&user).
Error
if err != nil {
return user, database.HandleDBError(err, "user")
}

err = db.
Model(&user).
Delete(&user).
Error
if err != nil {
return user, database.HandleDBError(err, "user")
}

return user, nil
}

0 comments on commit 62d5baf

Please sign in to comment.