Skip to content

feat: add row-level locking to LoadUserByID #187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/opentreehole/go-common"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)

type User struct {
Expand Down Expand Up @@ -181,9 +182,15 @@ func GetCurrLoginUser(c *fiber.Ctx) (*User, error) {
return user, err
}

// LoadUserByID load user from database.
// if user not found, create a new user with default config.
// This method starts a transaction and would add a lock on the user row, as soon as it starts to read.
func (user *User) LoadUserByID(userID int) error {
return DB.Transaction(func(tx *gorm.DB) error {
err := tx.Take(&user, userID).Error
// Lock it for update (SELECT ... FOR UPDATE),
// see [MySQL Official Manual](https://dev.mysql.com/doc/refman/8.4/en/innodb-locking-reads.html)
// We do the query on userID, which is the primary key, so the lock should be on the row.
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Take(&user, userID).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
// insert user if not found
Expand Down